Design a Weekly Top-Comments Email Digest

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a backend platform that delivers a weekly summary email to each post author highlighting the highest-quality comments left on their content.

Core system requirements:

  • Readers submit comments on published posts continuously across a seven-day window.
  • Once every week, each post author receives an email featuring the highest-ranked N comments written on their post during that cycle.
  • Comment quality rankings rely on numeric scores returned by an external machine-learning inference service.
  • That external inference endpoint enforces a strict request rate cap, making it infeasible to batch-score an entire week's accumulated comments right when weekly emails are due.
  • The backend must support tens of millions of posts and comments, tolerate worker retries and partial outages gracefully, and guarantee that authors do not receive duplicate digest emails.

Scope & Expectations

  • Present an end-to-end architecture and storage schema decoupling ongoing comment ingestion and ML evaluation from weekly digest assembly and email dispatch.
  • Detail how candidate comments are filtered, prioritized, and scored throughout the week while staying safely underneath the external ML service's rate ceiling and surviving provider slowdowns.
  • Specify how final top-N rankings handle ties, deleted or moderated comments, and missing scores when weekly windows close.
  • Explain your scheduling design and worker state machine so weekly digests go out reliably with zero silent drops and no duplicate deliveries.

Step-by-step walkthrough

  1. Clarify requirements and scope

    The defining architectural constraint here is the strict throughput cap on the external ML inference API, which rules out scoring a seven-day backlog right before Monday morning delivery. Almost every design choice flows from that bottleneck, so pin down the product rules and numbers first.

    Functional requirements

    • Published posts accumulate reader comments around the clock. Every week, authors whose posts received eligible activity get a summary email showcasing the highest-ranked N comments (default N = 5) per active post.
    • Ranking uses quality scores from the third-party ML endpoint, paired with deterministic tie-breakers and a clean fallback whenever scores are unavailable.
    • Deleted, hidden, or moderated comments must never appear in an email, even if they were scored days earlier.
    • Authors can opt out in account preferences or unsubscribe with a single click.

    Non-functional requirements

    • Scale to tens of millions of active posts and hundreds of millions of comments per week.
    • Strictly obey the global ML rate limit and degrade gracefully during ML slowdowns or outages.
    • Tolerate worker crashes, retries, and partial failures with zero silent drops and no duplicate emails.
    • Deliver at a predictable local morning hour (Monday 09:00 in the owner's local timezone).

    Key assumptions confirmed upfront

    • One consolidated email per owner per week (containing up to 10 post sections ordered by activity, plus a "View all posts" link), rather than spamming a power user with 30 separate emails.
    • Window definition: Comments created during the owner's local Monday 00:00 to Monday 00:00 window (excluding the post owner's own comments). That leaves a clean 9-hour grace window before Monday 09:00 delivery.
    • External ML limit: Assumed global ceiling of 300 comments/s, batched up to 50 comments/request. We target 90% (270 comments/s) so clock skew or retries never trip provider throttling.
    • Not every comment needs an ML score: Only comments that could plausibly make a post's top N need scoring; posts with <= N eligible comments need zero ML calls!
  2. Back-of-the-envelope numbers

    Walk through the arithmetic explicitly — two back-of-the-envelope checks prove why both naive batching and blind streaming fail:

    Weekly traffic (1 week = 7 * 86,400 s = 604,800 seconds)
      200M comments/week                    = ~331 comments/s average, ~1,000/s at 3x daytime peak
      20M active posts (>= 1 comment/week) across 8M post owners (~2.5 active posts/owner)
    
    ML scoring capacity check
      Max theoretical capacity (300/s)      300 * 604,800 s = 181.4M scores/week (100% utilization)
      Safe operating rate (90% = 270/s)     270 * 604,800 s = 163.3M scores/week
      Naive Sunday-night batch              200M / 300/s    = 666,667 s = ~7.7 days (impossible!)
      Continuous scoring of ALL comments    200M > 181.4M   = still exceeds 100% weekly capacity!
    

    Takeaway 1: We must score continuously throughout the week and selectively filter which comments consume ML quota.

    Because social/workspace comment volume is heavily skewed (many quiet posts, a few viral posts), selective scoring fits comfortably:

    Heavy-tailed comment breakdown across 20M active posts:
      12M small posts (<= 5 eligible comments)   ~25M comments  -> 0 ML scores needed!
       8M larger posts (> 5 comments)           ~175M comments
         - after free prefilter (~30% owner/emoji/1-word/spam)  -> ~122M eligible comments
         - Tier A (first 50 active eligible comments per post)  -> ~70M/week  = ~116/s average
         - Tier B (overflow > 50 on viral posts, best-effort)   -> ~52M/week
    
    Quota headroom at 270/s operating target:
      Tier A steady average = 116/s (~43% of 270/s budget)
      Spare capacity        = 154/s (~57%) to absorb daytime peaks, outages, edits, and Tier B!
      Example: a 6-hour ML outage queues 116/s * 21,600 s = ~2.5M Tier-A comments,
               which 154/s of spare capacity drains in ~4.5 hours.
    

    Monday delivery & storage sizing

    Monday 09:00 local delivery:
      8M digests/week total; busiest timezone (~25% = 2M owners) spread over 60 min (3,600 s)
      Peak send rate    = 2,000,000 / 3,600 s = ~556 emails/s
      Peak comment read = 556 digests/s * ~20 candidate rows = ~11,100 point lookups/s
    
    Weekly storage (compact and inexpensive):
      post_week_scores   ~120M scored rows * ~100 B = ~12 GB/week (retain 5 weeks ~ 60 GB)
      post_week_stats    20M post-weeks * ~100 B    = ~2 GB/week
      digest             8M owner-weeks * ~300 B    = ~2.4 GB/week
      payload snapshots  8M HTML/JSON blobs * ~5 KB = ~40 GB/week in object storage (30-day TTL)
    
  3. Events and API contracts

    1. Inbound comment stream

    To ensure we never save a comment in the primary database without emitting its event, the comment service publishes via a transactional outbox or Change Data Capture (CDC) — writing the event in the same database transaction as the comment and streaming committed log entries into Kafka keyed by post_id (guaranteeing per-post ordering):

    Kafka topic: comment-events (partition key = post_id)
      CommentCreated  { comment_id, post_id, author_id, created_at, text, like_count }
      CommentEdited   { comment_id, post_id, edited_at, text }
      CommentRemoved  { comment_id, post_id, reason: "deleted" | "hidden" | "moderated" }
    

    2. External ML batch scoring API

    POST /v1/score
    {
      "model": "comment-quality-v7",
      "items": [ { "id": "c_101", "text": "...", "post_title": "..." }, ... ]   // <= 50 items
    }
    -> 200 OK   { "scores": [ { "id": "c_101", "score": 0.91 }, ... ] }
    -> 429      Retry-After: 2
    

    3. User, support, and provider webhook endpoints

    PUT  /v1/users/{user_id}/digest-settings       { "enabled": true }
    POST /v1/digest/unsubscribe?token=<signed>     One-click RFC 8058 unsubscribe
    GET  /v1/internal/digest/{owner_id}/{week_key} Inspect status + frozen snapshot for support
    POST /v1/esp/webhooks                          Delivery, bounce, and spam-complaint events
    
  4. Data model and timezone bucketing

    In wide-column stores (Cassandra / DynamoDB), the partition key (PK) chooses which storage node holds a group of rows, while the clustering (sort) key (CK) keeps rows sorted together on disk inside that partition for fast single-seek reads.

    Source-of-truth tables (owned by core app, read-only for digest service)
      comments   comment_id PK, post_id, author_id, text, created_at, status, like_count
      posts      post_id PK, owner_id, title, status
      users      user_id PK, email, timezone, digest_enabled
    
    Digest service tables
      post_week_stats   PK (post_id, week_key)
                        owner_id, bucket_utc, eligible_count, scoring_started (bool),
                        first_ids (set of up to N comment_ids), active_tier_a_count
    
      post_week_scores  PK (post_id, week_key), CK (comment_id)
                        score, model_version, content_hash, scored_at, removed (bool)
    
      active_owner      PK (bucket_utc, shard), CK (owner_id, post_id)
                        shard = hash(owner_id) % 64
    
      schedule_run      PK (bucket_utc)
                        status (PENDING | ENQUEUING | DONE), shard_cursors (map 0..63), updated_at
    
      digest            PK (owner_id, week_key)
                        status (BUILDING | READY | SENDING | SENT | SKIPPED | FAILED),
                        lease_until, attempt, payload_ref, esp_message_id, sent_at
    

    Three data-modeling traps this schema avoids:

    • bucket_utc is an absolute UTC timestamp, never a time-of-day string. For example, New York (UTC-5 in November) closes ISO week 2026-W48 on Monday 2026-11-30 00:00 EST and sends at 09:00 EST = 2026-11-30T14:00Z. Why must bucket_utc include the date? Compare Kiribati (UTC+14) and Hawaii (UTC-10):
    Owner in Kiribati (UTC+14): Monday 09:00 local  ->  Sunday 19:00 UTC
    Owner in Hawaii   (UTC-10): Monday 09:00 local  ->  Monday 19:00 UTC (24 hours later!)
    

    Both translate to 19:00 UTC, a full day apart! Keying by absolute bucket_utc prevents sending Hawaii's email on Sunday morning while their week still has 15 hours left. - active_owner is sharded 64 ways per bucket (~2M owners / 64 = ~31k owners and ~80k post entries per partition) so the scheduler never scans the global users table or creates a giant hot partition. - post_week_scores stores all scored candidates per (post_id, week_key) rather than a fragile top-N heap. Because scoring is capped per post (<= 3,410 rows even on a mega-viral post, typically 10–50), reading the partition and sorting at Monday build time handles late comment deletions and edits cleanly with zero heap-repair bugs.

  5. High-level architecture: decoupling scoring from Monday delivery

      [Comment DB] --(Outbox / CDC)--> Kafka: comment-events (key = post_id)
                                                  |
                                                  v
                                     +----------------------------+
                                     | Candidate Selector         |---> post_week_stats
                                     | prefilter, lazy N+1 gate,  |---> active_owner
                                     | Tier-A cap                 |
                                     +-------------+--------------+
                                                   |
                             +---------------------+---------------------+
                             v                                           v
                  Kafka: score-a (priority 1)              Kafka: score-b (priority 2,
                  must-score <= 50/post                    hourly proxy top-20 rounds)
                             |                                           |
                             +---------------------+---------------------+
                                                   v
                                     +----------------------------+     +--------------------+
                                     | Scoring Workers            |---->| External ML API    |
                                     | global Redis token bucket  |<----| (300/s limit,      |
                                     | 270/s, batch=50, AIMD      |     |  <= 50 items/call) |
                                     +-------------+--------------+     +--------------------+
                                                   |
                                                   v
                                            post_week_scores
    
      ======================= (Decoupled through tables; 0 ML calls below!) =======================
    
      [Leader Scheduler] ---> Kafka: digest-jobs ---> [Digest Builders] ---> Kafka: send-jobs
       wakes every 1 min,      (key = owner_id,        read active_owner,          |
       pages active_owner       60-min jitter)         post_week_scores,           v
       64 shards                                       verify comments,     [Email Senders]
                                                       freeze snapshot,      state machine +
                                                       status = READY        idempotency key -> ESP
    

    The Scoring Pipeline runs continuously all week and writes post_week_scores; the Digest Pipeline wakes per timezone bucket on Monday and performs only fast local database reads and email rendering. When Monday 09:00 arrives, the rate-limited ML service is completely off the critical path.

  6. Deep dive 1: selecting which comments to score

    How do we turn 200M raw weekly comments into ~70M guaranteed scores without ruining digest quality? Apply five rules in order:

    1. Zero-cost prefilter: Immediately ignore the post owner's own comments, spam/moderated items, emoji-only or < 3-word replies ("Thanks!", "+1"), and exact text duplicates on the same post.
    2. Lazy N + 1 trigger: While a post has <= N (5) eligible comments, save their IDs in post_week_stats.first_ids and call the ML service zero times — if no 6th comment arrives, all <= 5 comments automatically make the top 5! Only when comment 6 arrives do we flip scoring_started = true and enqueue all 6 comments to score-a:
    Trace on Post P (N = 5):
      c1..c5 arrive -> eligible_count = 5, first_ids = {c1..c5}, scoring_started = false (0 ML calls!)
      c6 arrives    -> eligible_count = 6 > 5 -> flip scoring_started = true, push c1..c6 to score-a
      c7 arrives    -> scoring_started is true -> push c7 directly to score-a
    
    1. Tier-A cap of 50 active comments per post: Up to 50 non-removed eligible comments per (post_id, week_key) enter high-priority score-a (if moderators delete early spam, active_tier_a_count decrements so legitimate later comments can still fill the 50 guaranteed slots). Without a per-post cap, one celebrity thread with 100,000 comments would starve thousands of normal posts.
    2. Proxy-ranked Tier B for viral overflow: Comments beyond 50 wait in the comment store. Once per hour, a lightweight job ranks each capped post's unscored comments using a free engagement proxy (2 * likes + 3 * author_replies + log(length)) and pushes up to 20 top candidates per post into low-priority score-b, tagged with round_hour. Workers read score-b only when score-a is empty, and automatically drop entries from older round_hours so score-b never accumulates an infinite backlog.
    3. Round-robin emission across viral posts: If 200,000 viral posts each offer 20 Tier-B comments (4M candidates) during an hour that only has 500k spare ML tokens, emitting [Post1_#1..Post1_#20, Post2_#1..] would score all 20 on Post 1 and 0 on Post 50,000. Instead, emit rank-by-rank across posts so every viral post gets its #1 candidate scored before any post gets #2:
    Bad (post-by-post):  [P1_#1, P1_#2, ..., P1_#20, P2_#1, ...] -> starves P3..Pk when quota runs out
    Good (round-robin):  Round 1 [P1_#1, P2_#1, P3_#1, ...] -> Round 2 [P1_#2, P2_#2, ...] -> fair!
    

    For CommentEdited, re-score if sha256(text) changed (score-a if currently in top 2N, else score-b). For CommentRemoved, mark removed = true in post_week_scores and remove from first_ids. Audit recall continuously by scoring all comments on a random 0.5–1% sample of viral posts and measuring top-N overlap.

  7. Deep dive 2: respecting the global ML rate limit and surviving outages

    Because dozens of scoring workers share one 300 comments/s vendor limit, local per-worker sleeps drift and trigger 429 storms. Centralize rate coordination with four mechanisms:

    • Shared Redis token bucket + full batching: A token bucket is a shared counter refilled at 270 tokens/s (capped at burst 270). Before calling POST /v1/score with 50 comments, a worker atomically claims 50 tokens via a single Redis Lua script. Batching 50 items per HTTP request turns 270 comments/s into just 5.4 HTTP requests/s across the entire fleet.
    • AIMD (Additive Increase, Multiplicative Decrease) on HTTP 429: If the vendor returns 429 Too Many Requests, honor Retry-After and immediately cut the token refill rate in half (270 -> 135/s); for every full minute with zero 429s, nudge the rate back up by +5/s up to 270/s.
    • Circuit breaker & strict queue priority: If 5xx errors or timeouts exceed 20% over 30 seconds, a circuit breaker pauses outbound ML calls for 15 seconds and probes with one batch while events buffer safely in Kafka. Workers always drain score-a before touching score-b.
    • Poison-comment isolation & the 9-hour grace buffer: Scoring writes are idempotent upserts keyed by (post_id, week_key, comment_id). If a batch of 50 fails repeatedly due to one malformed string, bisect the batch, retry the offending comment 3 times, and route it to a dead-letter queue (DLQ) marked unscorable. Meanwhile, the 9-hour gap between Monday 00:00 week-close and Monday 09:00 delivery provides 9 * 3,600 * 270/s = ~8.7M scores of catch-up capacity before a single email is built.
  8. Deep dive 3: deterministic final ranking and graceful fallbacks

    At Monday 09:00 local, a Digest Builder processes one owner_id using zero ML calls:

    1. Small posts (scoring_started == false): Read first_ids, batch-fetch those <= N rows from comments to confirm status == "visible" and fetch fresh text/author names, and sort by (like_count DESC, created_at ASC, comment_id ASC).
    2. Scored posts (scoring_started == true): Read the (post_id, week_key) partition from post_week_scores, discard removed == true, take the top 2N (10) candidates, and batch-fetch those 10 IDs from the authoritative comments table. Re-checking live visibility catches any deletion whose Kafka event was delayed, while fetching 2N leaves N valid winners even if several top comments were just deleted.
    3. Deterministic tie-breaking: Rank surviving comments by (score DESC, like_count DESC, created_at ASC, comment_id ASC). Identical inputs always produce the exact same top N.
    4. Fallback when < N visible scored comments remain (for example, after a multi-hour ML outage or after moderators deleted 48 spam comments out of the first 50): query the post's visible comments for the week from comments, fill any remaining slots up to N using the engagement proxy, and tag ranking_complete = false for observability.
    5. Model-version consistency: Pin one model_version per weekly cycle so a post never mixes uncalibrated v6 and v7 scores; if the vendor forcibly retires v6 mid-week, align old scores using a monotone quantile mapping fitted on 100k dual-scored comments rather than burning 80M calls re-scoring everything.
    6. Payload snapshot: Render the owner's top <= 10 active post sections (skipping and marking SKIPPED if digest_enabled == false, email is on the bounce/complaint suppression list, or zero visible comments remain) and write the frozen payload to object storage under payload_ref before enqueueing delivery.
  9. Deep dive 4: scheduling and delivering without duplicate or lost emails

    1. Fault-tolerant timezone scheduling

    • Roughly 40 active bucket_utc slots fire per week (UTC offsets from UTC+14 to UTC-12, including 30- and 45-minute offsets).
    • A single leader-elected Scheduler wakes every minute, checks schedule_run for due buckets not yet DONE, pages all 64 active_owner shards in parallel (1,000 owners/page), emits one digest-jobs message per distinct owner_id with a deterministic delivery delay hash(owner_id) % 3600s (smoothing the 2M-owner peak to ~556/s), and checkpoints each shard's cursor.
    • Reconciliation sweeps: Queue redelivery alone misses edge cases (e.g., a builder wrote READY and crashed before publishing to send-jobs). At +2h, +6h, and +12h after each bucket's slot (up to a hard 24h staleness cutoff), the scheduler sweeps active_owner and re-enqueues any owner whose digest row is not SENT, SKIPPED, or FAILED.

    2. Lease-guarded state machine & idempotent ESP delivery

    Every (owner_id, week_key) row in digest progresses forward through atomic conditional updates with expiring leases (temporary ownership timestamps such as now + 10 min so crashed workers never lock a row forever):

              insert-if-absent             save snapshot               CAS + 5-min lease
     (none) -------------------> BUILDING ---------------> READY ------------------------> SENDING
                                    |                                                         |
                                    | opted out / 0 visible comments             ESP 200 OK   |
                                    v                                                         v
                                 SKIPPED                                                    SENT
    
    • Builder: Executes INSERT IF NOT EXISTS with status = BUILDING, lease_until = now + 10m. If a row already exists in SENT / SKIPPED / FAILED, exit immediately; if READY, re-publish send-jobs; if BUILDING with an expired lease, take over and rebuild.
    • Sender: Executes atomic compare-and-swap (UPDATE ... SET status = 'SENDING', lease_until = now + 5m WHERE status = 'READY'). Only one worker can win. It reads payload_ref and calls the ESP (Email Service Provider) passing idempotency key digest:{owner_id}:{week_key} (an identifier telling the ESP to deduplicate retries of the same logical send within 24–72 hours), then records status = SENT and esp_message_id.
    • Handling the crash window honestly: If a sender crashes after the ESP accepts the HTTP call before writing SENT, the next worker after lease expiry retries with the exact same digest:{owner_id}:{week_key} key so a modern ESP drops the duplicate; if an ESP lacks idempotency keys, query the ESP's message-activity API by custom header X-Digest-Id before resending (narrowing, though never mathematically eliminating, the duplicate window).
  10. Scaling, failure recovery, and summary of trade-offs

    Bottlenecks & scaling levers

    • Hot viral posts: Because comment-events partitions by post_id, one consumer handles a viral post lock-free in memory, flushing post_week_stats counters once per second instead of writing per comment.
    • Predictable Monday pre-scaling: Bucket sizes (active_owner counts) are known hours ahead of Monday 09:00, so Digest Builders, Email Senders, and comment-DB read replicas (~11k reads/s) scale out on schedule rather than reacting to lag.

    Failure recovery matrix

    Failure scenario System behavior & recovery
    ML 429 spike or multi-hour outage AIMD cuts rate; score-b pauses automatically; 9h Monday buffer + up to 3h build delay absorbs outages, then proxy fallback fills missing slots (ranking_complete = false)
    Poison comment crashes scorer Batch bisected -> 3 retries -> routed to DLQ as unscorable; never blocks neighbours
    Builder or Scheduler crash Expired lease_until / saved shard_cursors allow seamless takeover; digest row deduplicates duplicate jobs
    Sender crashes post-ESP call Expired SENDING lease picked up by reconciliation sweep; digest:{owner_id}:{week_key} idempotency key prevents duplicate inbox delivery
    Deleted comment or bounce/complaint Live comments visibility re-checked at build time; ESP bounce/complaint webhooks update suppression list checked prior to SENDING

    Summary of key trade-offs

    • Continuous selective scoring vs. end-of-week batch: Trades streaming state (post_week_stats, post_week_scores) for feasible ML throughput (~116/s guaranteed vs impossible 7.7-day batch) and zero Monday ML latency.
    • Lazy N + 1 trigger + 50 Tier-A cap + round-robin Tier B vs. scoring every comment: Bounds ML spend at 43% of safe quota in exchange for tiny, audited recall loss on mega-viral threads.
    • Full scored-partition sort at build time vs. incremental top-N heap: Spends a few kilobytes per post-week so comment deletions, edits, and deterministic tie-breaking stay trivial and bug-free.
    • Absolute bucket_utc local weeks + leased state machine vs. single UTC cron: Manages ~40 weekly buckets and explicit leases so every user worldwide gets a timely Monday 09:00 email with near-zero duplicate risk.

Intuition & how it works

Imagine running a weekly national baking contest where 200 million entries arrive throughout the week, winners must be announced at 9:00 AM Monday in every baker's local timezone, and your external panel of celebrity judges (the ML scoring service) can taste at most 300 dishes per second. If you wait until Sunday midnight to wheel out all 200 million dishes at once, judging takes 200,000,000 / 300 ≈ 7.7 days — Tuesday of next week! Even judging nonstop 24/7 all week covers at most 181.4 million dishes (163.3 million at a safe 270/s operating pace). The secret is continuous, selective judging all week: skip tables with 5 or fewer entries (everyone wins a top-5 ribbon automatically without bothering a judge), toss burnt entries at the door, guarantee judging for the first 50 real entries per table, and use crowd applause (likes and replies) during quiet hours to pick which overflow entries from mega-popular tables get tasted next.

A naive Monday cron job that queries comments, calls the ML API inline, and sends emails in a single loop breaks in three places at once. First, it instantly hits HTTP 429 Too Many Requests against the rate-limited ML service and falls days behind schedule. Second, scanning tens of millions of users and posts in one batch hammers primary databases and spikes outbound email servers. Third, when a worker inevitably crashes halfway through sending, rerunning the cron job sends embarrassing duplicate digests to thousands of post owners.

Walk through one concrete week for post owner Alice in New York (UTC-5, N = 5 top comments) across two active posts:

  1. Quiet post (Post A, 3 comments all week): Comments c1, c2, c3 arrive; because 3 <= 5, the selector records first_ids = {c1, c2, c3} and makes zero ML calls.
  2. Busy post (Post B, 80 comments): Comments c1..c5 wait silently until c6 arrives, flipping scoring_started = true and sending c1..c6 (and subsequent comments up to c50) to high-priority queue score-a, where workers claim 50 tokens at a time from a shared 270/s Redis token bucket (a global rate-limiting counter refilled at a steady rate). Overflow comments c51..c80 are ranked hourly by likes/replies into low-priority score-b and scored whenever score-a has spare headroom.
  3. Monday grace window (00:00 -> 09:00 EST): Alice's week 2026-W48 closes at Monday 00:00 EST, giving workers 9 hours to finish any late Sunday-night comments with zero ML calls left on the Monday send path.
  4. Build & single-send (09:00 EST = 2026-11-30T14:00Z): A Digest Builder reads Post A's 3 IDs and Post B's scored rows, verifies in comments that none were deleted (c12 was deleted Friday, so #6 moves up cleanly), freezes the rendered email snapshot (READY), and an Email Sender atomically claims READY -> SENDING and calls the email provider with idempotency key digest:alice:2026-W48 before marking SENT.

Key trade-offs

  • Continuous stream scoring vs. end-of-week batch scoring. End-of-week batching is operationally simpler (no edits or deletions mid-week), but 200M comments at 300/s takes ~7.7 days. Streaming via Change Data Capture (CDC) / transactional outbox (reliably publishing database commits into Kafka in per-post order) spreads ML work across all 168 hours of the week and removes the ML service from Monday morning's critical path, in exchange for handling mid-week edits, removals, and model versions.
  • Lazy N + 1 trigger + Tier-A cap vs. scoring every comment. Skipping posts with <= N eligible comments, prefiltering noise, and capping guaranteed score-a work at 50 active comments per post keeps required load at ~116/s (43% of our 270/s budget), leaving ~154/s headroom for daytime peaks and outages. The trade-off is a tiny risk that an unliked gem arriving at comment #500 on a viral post misses Tier B — mitigated by round-robin hourly proxy ranking across posts and measured continuously on a 1% fully-scored audit sample.
  • Storing all scored candidates per post-week vs. maintaining an incremental top-N heap. Keeping only a 5-item min-heap per post saves a few kilobytes of disk, but breaks whenever one of those 5 comments is deleted, moderated, or edited down in score. Because per-post scoring is capped (<= 3,410 rows max, usually 10–50), storing every scored candidate in a wide-column partition (rows grouped on disk by (post_id, week_key) for a single sequential read) makes build-time deletion filtering and tie-breaking trivial.
  • Strict two-tier priority with expiring Tier-B rounds vs. one FIFO queue. A single first-in-first-out queue lets one 500,000-comment viral thread delay guaranteed top-5 scoring for thousands of normal posts. Separating score-a (strict priority) from score-b (drained only when score-a is empty, skipping prior hours' stale entries) bounds tail latency and prevents unbounded low-value backlogs.
  • Local weeks keyed by absolute bucket_utc vs. one global UTC schedule. A single global Monday 09:00 UTC send arrives in the middle of the night for half the globe, while keying buckets only by time-of-day ("19:00 UTC") confuses UTC+14 (Monday 09:00 local = Sunday 19:00 UTC) with UTC-10 (Monday 09:00 local = Monday 19:00 UTC). Scheduling ~40 weekly absolute-UTC buckets gives every user worldwide a 9-hour post-week scoring buffer and a local Monday-morning email.
  • Lease-guarded state machine + idempotency keys vs. queue-only retries. Relying solely on Kafka at-least-once redelivery duplicates emails on worker crashes, whereas committing offsets early silently drops digests. Persisting BUILDING -> READY -> SENDING -> SENT with expiring leases (time-bounded worker locks), compare-and-swap (CAS) updates (atomic conditional writes that succeed only if the row still holds the expected status), periodic reconciliation sweeps, and provider idempotency keys (unique tokens telling the email service to ignore duplicate retries of the same send) prevents lost digests and eliminates duplicates whenever the provider supports key deduplication.

Common mistakes

  • Calling the ML scorer inside the Monday digest builder, turning a fast read-and-render job into a multi-day 429 bottleneck.
  • Enforcing a global rate limit with independent per-worker sleeps instead of a shared Redis token bucket plus AIMD (Additive Increase, Multiplicative Decrease) — halving send rate immediately upon HTTP 429 and ramping back slowly — so adding worker pods accidentally multiplies outbound QPS past 300/s.
  • Sizing weekly capacity at 100% of 300/s, leaving zero margin for 3x daytime traffic peaks, retries, or recovering from a multi-hour ML outage.
  • Scoring comments on posts with <= N comments, wasting tens of millions of ML calls where every eligible comment is guaranteed to appear anyway.
  • Emitting viral Tier-B candidates post-by-post rather than round-robin, starving posts later in the batch whenever spare ML capacity runs out mid-hour.
  • Trusting Tuesday's cached ML score on Monday without re-checking live comment visibility, leaking deleted, moderated, or user-redacted text into owner emails.
  • Scanning the entire users or posts table every Monday instead of maintaining a sharded active_owner index populated only for owners whose posts actually received comments in that bucket_utc.
  • Ignoring the crash window between ESP HTTP 200 and DB status = SENT, which is the exact fault boundary that produces duplicate customer emails unless protected by an idempotency key and frozen payload snapshot.

Follow-up questions

  • How would your system handle a single mega-viral post receiving 1 million comments in a week? On the ingest path, comment-events partitions by post_id, so a single stream consumer processes that post's events sequentially in memory without distributed lock contention, batch-flushing post_week_stats once per second (1 write/s instead of 1,000 writes/s). On the ML path, the 50-comment Tier-A cap plus 20/hour Tier-B cap strictly bounds total ML calls for that post to at most 50 + 168 * 20 = 3,410 scores across the entire week (< 0.003% of weekly quota), so one viral post can never starve the rest of the platform. To keep top-5 quality high among the remaining 996k comments, upgrade the free Tier-B proxy from simple like/reply counts to a tiny CPU-resident logistic/distilled ranker we run internally with no external rate limit.
  • What happens if the external ML provider upgrades its scoring model mid-week and scores shift scale? Mixing raw scores from v6 (say mean 0.45) and v7 (say mean 0.72) inside the same post-week biases Monday's top N toward whichever days ran on the higher-scoring version. Whenever possible, pin an explicit model_version parameter per week_key and cut over cleanly at weekly boundaries. If the vendor forcibly retires the old version mid-week, re-scoring even the top 10 candidates across 8M scored posts would burn ~80M calls (~3.4 days at 270/s); instead, dual-score a 100,000-comment calibration sample on both versions, fit a monotone quantile mapping (matching percentiles, e.g., mapping v6's 90th-percentile score to v7's 90th-percentile score), and transform earlier v6 rows at build time for that transition week.
  • How would you measure whether the weekly digest is actually useful, and how would you A/B test improvements? Instrument funnel metrics beyond raw email opens (which privacy proxies inflate): digest click-through rate to comments, owner replies/reactions triggered within 24 hours of clicking, share of digests degraded by fallback (ranking_complete == false), and guardrail rates (one-click unsubscribes and spam complaints, which directly affect domain deliverability reputation). Run A/B experiments hashed deterministically by owner_id (testing N = 3 vs N = 5, pure ML score vs ML score blended with recency/unseen status, or subject lines) over at least 4 full weekly cycles so novelty effects settle and weekly periodicity cancels out.

Follow-up questions

Similar questions

More Clickup interview questions

All 2 Clickup questions →