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
Ncomments 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-
Nrankings 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
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
Ncomments (defaultN = 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:00in the owner's local timezone).
Key assumptions confirmed upfront
- One consolidated email per owner per week (containing up to
10post 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:00to Monday00:00window (excluding the post owner's own comments). That leaves a clean 9-hour grace window before Monday09:00delivery. - External ML limit: Assumed global ceiling of
300 comments/s, batched up to50 comments/request. We target90%(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
Nneed scoring; posts with<= Neligible comments need zero ML calls!
- Published posts accumulate reader comments around the clock. Every week, authors whose posts received eligible activity get a summary email showcasing the highest-ranked
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)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: 23. 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 eventsData 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_atThree data-modeling traps this schema avoids:
bucket_utcis an absolute UTC timestamp, never a time-of-day string. For example, New York (UTC-5in November) closes ISO week2026-W48on Monday2026-11-30 00:00 ESTand sends at09:00 EST=2026-11-30T14:00Z. Why mustbucket_utcinclude 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 absolutebucket_utcprevents sending Hawaii's email on Sunday morning while their week still has 15 hours left. -active_owneris sharded 64 ways per bucket (~2Mowners /64=~31kowners and~80kpost entries per partition) so the scheduler never scans the globaluserstable or creates a giant hot partition. -post_week_scoresstores all scored candidates per(post_id, week_key)rather than a fragile top-Nheap. Because scoring is capped per post (<= 3,410rows even on a mega-viral post, typically10–50), reading the partition and sorting at Monday build time handles late comment deletions and edits cleanly with zero heap-repair bugs.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 -> ESPThe 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 Monday09:00arrives, the rate-limited ML service is completely off the critical path.Deep dive 1: selecting which comments to score
How do we turn
200Mraw weekly comments into~70Mguaranteed scores without ruining digest quality? Apply five rules in order:- 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. - Lazy
N + 1trigger: While a post has<= N(5) eligible comments, save their IDs inpost_week_stats.first_idsand call the ML service zero times — if no 6th comment arrives, all<= 5comments automatically make the top5! Only when comment6arrives do we flipscoring_started = trueand enqueue all6comments toscore-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- Tier-A cap of
50active comments per post: Up to50non-removed eligible comments per(post_id, week_key)enter high-priorityscore-a(if moderators delete early spam,active_tier_a_countdecrements so legitimate later comments can still fill the50guaranteed slots). Without a per-post cap, one celebrity thread with100,000comments would starve thousands of normal posts. - Proxy-ranked Tier B for viral overflow: Comments beyond
50wait 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 to20top candidates per post into low-priorityscore-b, tagged withround_hour. Workers readscore-bonly whenscore-ais empty, and automatically drop entries from olderround_hours soscore-bnever accumulates an infinite backlog. - Round-robin emission across viral posts: If
200,000viral posts each offer20Tier-B comments (4Mcandidates) during an hour that only has500kspare ML tokens, emitting[Post1_#1..Post1_#20, Post2_#1..]would score all20onPost 1and0onPost 50,000. Instead, emit rank-by-rank across posts so every viral post gets its#1candidate 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 ifsha256(text)changed (score-aif currently in top2N, elsescore-b). ForCommentRemoved, markremoved = trueinpost_week_scoresand remove fromfirst_ids. Audit recall continuously by scoring all comments on a random0.5–1%sample of viral posts and measuring top-Noverlap.- Zero-cost prefilter: Immediately ignore the post owner's own comments, spam/moderated items, emoji-only or
Deep dive 2: respecting the global ML rate limit and surviving outages
Because dozens of scoring workers share one
300 comments/svendor limit, local per-worker sleeps drift and trigger429storms. 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 burst270). Before callingPOST /v1/scorewith50comments, a worker atomically claims50tokens via a single Redis Lua script. Batching50items per HTTP request turns270 comments/sinto just5.4 HTTP requests/sacross the entire fleet. - AIMD (Additive Increase, Multiplicative Decrease) on HTTP
429: If the vendor returns429 Too Many Requests, honorRetry-Afterand immediately cut the token refill rate in half (270 -> 135/s); for every full minute with zero429s, nudge the rate back up by+5/sup to270/s. - Circuit breaker & strict queue priority: If 5xx errors or timeouts exceed
20%over30 seconds, a circuit breaker pauses outbound ML calls for15 secondsand probes with one batch while events buffer safely in Kafka. Workers always drainscore-abefore touchingscore-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 of50fails repeatedly due to one malformed string, bisect the batch, retry the offending comment3times, and route it to a dead-letter queue (DLQ) markedunscorable. Meanwhile, the9-hourgap between Monday00:00week-close and Monday09:00delivery provides9 * 3,600 * 270/s = ~8.7Mscores of catch-up capacity before a single email is built.
- Shared Redis token bucket + full batching: A token bucket is a shared counter refilled at
Deep dive 3: deterministic final ranking and graceful fallbacks
At Monday
09:00local, a Digest Builder processes oneowner_idusing zero ML calls:- Small posts (
scoring_started == false): Readfirst_ids, batch-fetch those<= Nrows fromcommentsto confirmstatus == "visible"and fetch fresh text/author names, and sort by(like_count DESC, created_at ASC, comment_id ASC). - Scored posts (
scoring_started == true): Read the(post_id, week_key)partition frompost_week_scores, discardremoved == true, take the top2N(10) candidates, and batch-fetch those10IDs from the authoritativecommentstable. Re-checking live visibility catches any deletion whose Kafka event was delayed, while fetching2NleavesNvalid winners even if several top comments were just deleted. - 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 topN. - Fallback when
< Nvisible 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 fromcomments, fill any remaining slots up toNusing the engagement proxy, and tagranking_complete = falsefor observability. - Model-version consistency: Pin one
model_versionper weekly cycle so a post never mixes uncalibratedv6andv7scores; if the vendor forcibly retiresv6mid-week, align old scores using a monotone quantile mapping fitted on100kdual-scored comments rather than burning80Mcalls re-scoring everything. - Payload snapshot: Render the owner's top
<= 10active post sections (skipping and markingSKIPPEDifdigest_enabled == false, email is on the bounce/complaint suppression list, or zero visible comments remain) and write the frozen payload to object storage underpayload_refbefore enqueueing delivery.
- Small posts (
Deep dive 4: scheduling and delivering without duplicate or lost emails
1. Fault-tolerant timezone scheduling
- Roughly
40activebucket_utcslots fire per week (UTC offsets fromUTC+14toUTC-12, including30- and45-minute offsets). - A single leader-elected Scheduler wakes every minute, checks
schedule_runfor due buckets not yetDONE, pages all64active_ownershards in parallel (1,000owners/page), emits onedigest-jobsmessage per distinctowner_idwith a deterministic delivery delayhash(owner_id) % 3600s(smoothing the2M-owner peak to~556/s), and checkpoints each shard's cursor. - Reconciliation sweeps: Queue redelivery alone misses edge cases (e.g., a builder wrote
READYand crashed before publishing tosend-jobs). At+2h,+6h, and+12hafter each bucket's slot (up to a hard24hstaleness cutoff), the scheduler sweepsactive_ownerand re-enqueues any owner whosedigestrow is notSENT,SKIPPED, orFAILED.
2. Lease-guarded state machine & idempotent ESP delivery
Every
(owner_id, week_key)row indigestprogresses forward through atomic conditional updates with expiring leases (temporary ownership timestamps such asnow + 10 minso 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 EXISTSwithstatus = BUILDING, lease_until = now + 10m. If a row already exists inSENT/SKIPPED/FAILED, exit immediately; ifREADY, re-publishsend-jobs; ifBUILDINGwith 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 readspayload_refand calls the ESP (Email Service Provider) passing idempotency keydigest:{owner_id}:{week_key}(an identifier telling the ESP to deduplicate retries of the same logical send within 24–72 hours), then recordsstatus = SENTandesp_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 samedigest:{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 headerX-Digest-Idbefore resending (narrowing, though never mathematically eliminating, the duplicate window).
- Roughly
Scaling, failure recovery, and summary of trade-offs
Bottlenecks & scaling levers
- Hot viral posts: Because
comment-eventspartitions bypost_id, one consumer handles a viral post lock-free in memory, flushingpost_week_statscounters once per second instead of writing per comment. - Predictable Monday pre-scaling: Bucket sizes (
active_ownercounts) are known hours ahead of Monday09: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 429spike or multi-hour outageAIMD cuts rate; score-bpauses automatically;9hMonday buffer + up to3hbuild 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 neighboursBuilder or Scheduler crash Expired lease_until/ savedshard_cursorsallow seamless takeover;digestrow deduplicates duplicate jobsSender crashes post-ESP call Expired SENDINGlease picked up by reconciliation sweep;digest:{owner_id}:{week_key}idempotency key prevents duplicate inbox deliveryDeleted comment or bounce/complaint Live commentsvisibility re-checked at build time; ESP bounce/complaint webhooks update suppression list checked prior toSENDINGSummary 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/sguaranteed vs impossible7.7-daybatch) and zero Monday ML latency. - Lazy
N + 1trigger +50Tier-A cap + round-robin Tier B vs. scoring every comment: Bounds ML spend at43%of safe quota in exchange for tiny, audited recall loss on mega-viral threads. - Full scored-partition sort at build time vs. incremental top-
Nheap: Spends a few kilobytes per post-week so comment deletions, edits, and deterministic tie-breaking stay trivial and bug-free. - Absolute
bucket_utclocal weeks + leased state machine vs. single UTC cron: Manages ~40 weekly buckets and explicit leases so every user worldwide gets a timely Monday09:00email with near-zero duplicate risk.
- Hot viral posts: Because
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:
- Quiet post (
Post A,3comments all week): Commentsc1, c2, c3arrive; because3 <= 5, the selector recordsfirst_ids = {c1, c2, c3}and makes zero ML calls. - Busy post (
Post B,80comments): Commentsc1..c5wait silently untilc6arrives, flippingscoring_started = trueand sendingc1..c6(and subsequent comments up toc50) to high-priority queuescore-a, where workers claim50tokens at a time from a shared270/sRedis token bucket (a global rate-limiting counter refilled at a steady rate). Overflow commentsc51..c80are ranked hourly by likes/replies into low-priorityscore-band scored wheneverscore-ahas spare headroom. - Monday grace window (
00:00 -> 09:00 EST): Alice's week2026-W48closes at Monday00:00 EST, giving workers9 hoursto finish any late Sunday-night comments with zero ML calls left on the Monday send path. - Build & single-send (
09:00 EST=2026-11-30T14:00Z): A Digest Builder readsPost A's3IDs andPost B's scored rows, verifies incommentsthat none were deleted (c12was deleted Friday, so#6moves up cleanly), freezes the rendered email snapshot (READY), and an Email Sender atomically claimsREADY -> SENDINGand calls the email provider with idempotency keydigest:alice:2026-W48before markingSENT.
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
200Mcomments at300/stakes~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 all168hours 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 + 1trigger + Tier-A cap vs. scoring every comment. Skipping posts with<= Neligible comments, prefiltering noise, and capping guaranteedscore-awork at50active comments per post keeps required load at~116/s(43%of our270/sbudget), leaving~154/sheadroom for daytime peaks and outages. The trade-off is a tiny risk that an unliked gem arriving at comment#500on a viral post misses Tier B — mitigated by round-robin hourly proxy ranking across posts and measured continuously on a1%fully-scored audit sample. - Storing all scored candidates per post-week vs. maintaining an incremental top-
Nheap. Keeping only a5-item min-heap per post saves a few kilobytes of disk, but breaks whenever one of those5comments is deleted, moderated, or edited down in score. Because per-post scoring is capped (<= 3,410rows max, usually10–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-5scoring for thousands of normal posts. Separatingscore-a(strict priority) fromscore-b(drained only whenscore-ais empty, skipping prior hours' stale entries) bounds tail latency and prevents unbounded low-value backlogs. - Local weeks keyed by absolute
bucket_utcvs. one global UTC schedule. A single global Monday09:00 UTCsend arrives in the middle of the night for half the globe, while keying buckets only by time-of-day ("19:00 UTC") confusesUTC+14(Monday09:00local = Sunday19:00 UTC) withUTC-10(Monday09:00local = Monday19:00 UTC). Scheduling ~40weekly absolute-UTC buckets gives every user worldwide a9-hourpost-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 -> SENTwith 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
429bottleneck. - 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
429and ramping back slowly — so adding worker pods accidentally multiplies outbound QPS past300/s. - Sizing weekly capacity at
100%of300/s, leaving zero margin for3xdaytime traffic peaks, retries, or recovering from a multi-hour ML outage. - Scoring comments on posts with
<= Ncomments, 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
usersorpoststable every Monday instead of maintaining a shardedactive_ownerindex populated only for owners whose posts actually received comments in thatbucket_utc. - Ignoring the crash window between
ESP HTTP 200andDB 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-eventspartitions bypost_id, so a single stream consumer processes that post's events sequentially in memory without distributed lock contention, batch-flushingpost_week_statsonce per second (1 write/sinstead of1,000 writes/s). On the ML path, the50-comment Tier-A cap plus20/hourTier-B cap strictly bounds total ML calls for that post to at most50 + 168 * 20 = 3,410scores across the entire week (< 0.003%of weekly quota), so one viral post can never starve the rest of the platform. To keep top-5quality high among the remaining996kcomments, 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 mean0.45) andv7(say mean0.72) inside the same post-week biases Monday's topNtoward whichever days ran on the higher-scoring version. Whenever possible, pin an explicitmodel_versionparameter perweek_keyand cut over cleanly at weekly boundaries. If the vendor forcibly retires the old version mid-week, re-scoring even the top10candidates across8Mscored posts would burn~80Mcalls (~3.4 daysat270/s); instead, dual-score a100,000-comment calibration sample on both versions, fit a monotone quantile mapping (matching percentiles, e.g., mappingv6's 90th-percentile score tov7's 90th-percentile score), and transform earlierv6rows 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 byowner_id(testingN = 3vsN = 5, pure ML score vs ML score blended with recency/unseen status, or subject lines) over at least4full weekly cycles so novelty effects settle and weekly periodicity cancels out.
Follow-up questions
- How would your system handle a single mega-viral post receiving 1 million comments in a week?
- What happens if the external ML provider upgrades its scoring model mid-week and scores shift scale?
- How would you measure whether the weekly digest is actually useful, and how would you A/B test improvements?
Similar questions
- Apply Sequential Document Line Edits
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency