Everyone who has ever built a feed reader thinks this is a weekend project. Pull some RSS, store the articles, show them newest first. Then you turn it on against ten thousand feeds and the cracks appear in a specific order. First, the same story shows up nineteen times because Reuters wrote it, the AP rewrote it, and forty blogs copy-pasted it with a new headline. Then the feed feels like noise because a user who only cares about cricket and Kubernetes is drowning in celebrity gossip. Then one feed starts returning 50MB of garbage every poll and your crawler falls over.
The actual problem is three problems wearing a trench coat: crawl thousands of feeds politely and efficiently, collapse near-identical articles into one canonical story before anyone sees them, and rank the surviving stories per user. The hard part - the part the whole pipeline is built around - is near-duplicate detection at ingestion time, because it has to happen once, before fan-out, not per user per read. If you dedup after fan-out you do the same work a million times. Let me do it properly.
Functional Requirements (FR)
In scope:
- Ingest feeds. Crawl a large, growing registry of RSS and Atom feeds on a schedule, parse entries, and extract article text, title, author, publish time, and canonical URL.
- Near-duplicate detection. Before a story reaches any user, detect that an incoming article is a near-duplicate of one already ingested (same event, reworded, syndicated, or lightly edited) and collapse them into a single canonical story with a list of sources.
- Per-user personalized feed. Given a user, return a ranked list of recent canonical stories ordered by a blend of freshness, source authority, and the user’s inferred interests.
- Interest inference. Build and update a per-user interest vector from explicit signals (follows, topic subscriptions) and implicit signals (clicks, dwell time, saves, hides).
- Feedback loop. A user can hide a story, hide a source, or mark not-interested, and that shapes future ranking.
Explicitly out of scope (say it out loud so you own the scope):
- Writing or hosting original content. We aggregate other people’s feeds; we are not a CMS.
- Full-text article hosting and reader-mode rendering. We store enough text for dedup and a snippet; the click goes to the publisher. Fetching and storing complete article bodies for offline reading is a separate concern.
- Comments, social graph, sharing. Each is its own system.
- A trained deep recommendation model from scratch. I will design the ranking pipeline and feature store; the model itself is a pluggable scorer.
- Paywalls, auth with publishers, and licensing. Assume we ingest public feeds.
The one decision that drives everything: dedup is an ingestion-time, write-side operation, done once per incoming article, before fan-out. Ranking is a read-side operation, done per user. Confuse the two and you either dedup a million times or rank garbage. Keep them on opposite sides of the pipeline.
Non-Functional Requirements (NFR)
- Scale: ~50,000 active feeds, growing. ~5M new articles ingested per day across all feeds (many are duplicates of each other). ~20M daily active users reading feeds.
- Latency: feed read p99 under 200ms - this is what the user feels. Ingestion is a background pipeline; an article appearing in feeds within a couple of minutes of publication is the freshness target, not milliseconds.
- Availability: 99.95% on the read path. A blank feed is the most visible failure. The crawler can be down for minutes without a user noticing, as long as the read path keeps serving the already-ingested corpus.
- Consistency: eventual everywhere. It is fine if a brand-new story takes 60-120 seconds to appear, and fine if two users see slightly different ordering. Nobody needs read-after-write across the corpus.
- Durability: the canonical story store is durable and replicated. Raw crawl payloads are transient and can be re-fetched. The interest vectors are rebuildable from the event log, so they are a derived cache, not a system of record.
- Politeness: we must respect
robots.txt, conditional requests, and per-host rate limits. Hammering a publisher gets us blocked, which is a correctness failure, not just etiquette.
Back-of-the-Envelope Estimation (BoE)
Real numbers with the arithmetic, because the architecture falls out of them.
Crawl volume:
50,000 feeds, polled on average every 5 minutes
= 50,000 / 300 seconds
≈ 167 feed polls/sec average
Peak (hot feeds polled more often, 3x) ≈ 500 polls/sec
Each poll is a conditional HTTP GET. Most return 304 Not Modified (no new content). Say 10% of polls yield new entries, and a yielding poll brings ~3 new entries:
167 polls/sec * 10% yielding * 3 entries ≈ 50 new raw entries/sec average
Over a day: 50 * 86,400 ≈ 4.3M raw entries/day (call it ~5M)
Dedup workload (the core):
Every one of those ~5M daily entries must be fingerprinted and checked against recent history.
5M articles/day / 86,400 ≈ 58 articles/sec average dedup throughput
Peak (3x) ≈ 175 articles/sec
That is not a huge QPS, which is good, because MinHash fingerprinting plus an LSH lookup is non-trivial per article. The expensive part is the candidate comparison, and the whole design below exists to keep that from becoming an all-pairs blowup.
Dedup collapse ratio: syndicated news is massively redundant. Assume ~5M raw articles collapse to ~1M canonical stories/day (a 5:1 collapse). That ratio is the entire reason dedup is worth doing - it cuts the corpus every user sees by 80%.
5M raw/day -> ~1M canonical stories/day
Reads (feed loads):
20M DAU, each loading/refreshing ~10 times/day
20M * 10 = 200M feed reads/day
= 200M / 86,400 ≈ 2,300 reads/sec average
Peak (3x) ≈ 7,000 feed reads/sec
Storage:
Per canonical story, the durable row:
story_id 8 bytes
title ~120 bytes
snippet ~400 bytes
canonical_url ~120 bytes
source_ids[] ~80 bytes (list of contributing sources)
simhash/minhash ~128 bytes (signature, stored for re-check)
topic_vector ~256 bytes (float16 x 128 dims)
published_at 8 bytes
authority_score 4 bytes
metadata ~76 bytes
------------------------------------------------
≈ 1.3 KB/canonical story
1M canonical stories/day * 1.3 KB ≈ 1.3 GB/day
* 365 ≈ 475 GB/year of canonical stories
We keep a rolling window hot (news goes stale fast). The last 30 days of canonical stories:
30M stories * 1.3 KB ≈ 40 GB (trivially cacheable, more below)
Raw crawl payloads are far larger but transient - we keep them only long enough to parse and dedup, then drop the body and keep the signature. Say 5M * 30KB raw HTML = 150GB/day of transient payload, which never hits durable storage.
MinHash LSH index size:
The dedup index holds signatures only for the recent window (an article from last year is not a duplicate candidate for today’s news). Keep ~7 days:
7 days * 5M raw/day = 35M signatures in the dedup window
Each MinHash signature: 128 hashes * 4 bytes = 512 bytes
35M * 512 bytes ≈ 18 GB of signatures
Plus LSH band buckets (hash tables) - a few GB more.
~20-25GB of in-memory LSH index. Fits comfortably in a sharded Redis/in-memory store.
Per-user feed cache:
A user’s feed is a list of ~500 ranked story_ids (8 bytes each):
Per feed: 500 * 8 bytes ≈ 4 KB (round to ~6KB with scores + overhead)
Cache only DAU: 20M * 6KB ≈ 120 GB of feed cache
~120GB of precomputed feed cache across a Redis cluster - standard. Store IDs, not stories; hydrate at read time from the shared canonical store.
Bandwidth:
A feed page = ~30 stories * ~0.5 KB hydrated ≈ 15 KB.
Read bandwidth at peak: 7,000 reads/sec * 15KB ≈ 105 MB/sec served.
Crawl ingress: 500 polls/sec, mostly 304s; yielding polls ~30KB each ≈ a few MB/sec.
Bandwidth is comfortable. The hard constraints are the dedup comparison cost and the per-user ranking, not raw bytes.
High-Level Design (HLD)
Three stages, cleanly separated by queues: the crawl/ingest path (polite, scheduled, bursty), the dedup/canonicalize path (the core, runs once per article), and the rank/read path (high-QPS, latency-critical). A new article flows left to right through dedup exactly once, then is fanned out to candidate feeds; a user read is a cheap lookup on the right.
┌───────────────────────────┐
│ Feed Registry │
│ (feed_url, etag, schedule) │
└─────────────┬──────────────┘
│ due feeds
┌─────────────▼──────────────┐
│ Scheduler / Frontier │
│ (priority queue by due-time)│
└─────────────┬──────────────┘
│ poll jobs
┌─────────────▼──────────────┐
│ Crawler Workers │
│ (conditional GET, robots, │
│ per-host rate limit) │
└──────┬───────────────┬──────┘
304 / no │ │ new entries
change ──┘ ┌──────▼───────────┐
│ Parse Queue │
│ (Kafka) │
└──────┬───────────┘
│
┌─────────────▼──────────────┐
│ Parser / Normalizer │
│ (extract title, text, url, │
│ shingle, MinHash signature)│
└─────────────┬──────────────┘
│ {article + signature}
┌─────────────▼──────────────┐
│ Dedup Service (LSH) │
│ query band buckets -> │
│ candidates -> verify -> │
│ attach-or-create canonical │
└───┬────────────────────┬────┘
attach to existing │ │ new canonical story
(add source, no fan) │ ┌────────▼───────────┐
┌──────────────▼──┐ │ Canonical Store │
│ LSH Index │ │ (story + topic vec) │
│ (band -> story) │ └────────┬───────────┘
└──────────────────┘ │ emit "new story"
┌─────────▼──────────┐
│ Fan-out / Indexer │
│ (topic -> candidate │
│ feeds; recency idx)│
└─────────┬──────────┘
│
┌──────────────┐ ┌──────────────────┐ ┌─────────▼──────────┐
│ Clients │───▶│ Feed Service │──────▶│ Feed Cache / Index │
│ (app, web) │◀───│ (stateless) │ │ (per-user story IDs)│
└──────────────┘ └────────┬──────────┘ └────────────────────┘
│ score candidates
┌────────▼──────────┐ ┌────────────────────┐
│ Ranking Service │◀──▶│ Interest Store │
│ (freshness+auth+ │ │ (per-user vectors) │
│ interest dot-prod)│ └────────────────────┘
└───────────┘
Ingest flow (crawl a feed):
- The Scheduler pulls feeds whose
next_duetime has passed from the Feed Registry and enqueues poll jobs into the frontier. - A Crawler Worker issues a conditional GET (
If-None-Matchwith the stored ETag,If-Modified-Sincewith last-seen). If the response is304, record the poll and reschedule - done, no further work. - On
200, parse the feed XML, diff against the last-seen entry set (by entry GUID/link), and emit only genuinely new entries to the Parse Queue. - The Scheduler updates
next_dueusing an adaptive interval (feeds that publish often get polled more often).
Dedup flow (the core, once per new article):
- The Parser normalizes an entry: strip HTML, extract clean title and body text, resolve the canonical URL, parse publish time.
- It computes a MinHash signature over the article’s text shingles (details in the deep dive).
- The Dedup Service queries the LSH index: hash the signature into bands, look up each band’s bucket for articles that collide in at least one band. Those are candidates.
- For each candidate, compute the estimated Jaccard similarity from the signatures; if any candidate exceeds the duplicate threshold, attach the new article to that existing canonical story (add it as a contributing source, possibly bump authority) and stop - no new story, no fan-out.
- If no candidate passes, create a new canonical story, write it to the Canonical Store, insert its signature into the LSH index, and emit a “new story” event.
Fan-out flow (new canonical story):
- The Indexer computes the story’s topic vector and writes it to the recency index and topic index.
- Candidate feeds are determined by topic: the story is a candidate for users whose interest vector overlaps its topics. We do not push the story into 20M feed caches eagerly (deep dive on why). We index it for pull-based candidate generation and only eagerly push into the feeds of users with a strong, narrow interest match.
Read flow (load personalized feed) - the hot path:
- Client
GET /feed. The Feed Service generates candidates: recent canonical stories matching the user’s interest topics (from the topic/recency index), unioned with any pre-pushed story IDs in the user’s feed cache. - The Ranking Service scores each candidate:
score = freshness x source_authority x interest_match, hydrating lightweight features. - Sort by score, apply diversity rules (not five stories from one source in a row, demote already-seen), take the top N.
- Hydrate the top N
story_ids into full story objects with a batched read from the Canonical Store/cache. - Return the page. Cache misses fall through to the Canonical Store.
The key insight: dedup happened once at ingestion, so every user is ranking over a clean, 5x-smaller set of canonical stories. The read path never re-detects duplicates; it only scores and orders. That separation is the whole design.
Component Deep Dive
The hard parts, naive-first then evolved: (1) near-duplicate detection with MinHash LSH, (2) the crawl scheduler and politeness, (3) fan-out vs pull for candidate generation, (4) per-user ranking and interest vectors.
1. Near-duplicate detection with MinHash LSH
This is the heart of the problem. The same news event spawns dozens of articles: the original wire story, syndicated copies, rewrites with a fresh headline, and aggregator blogs that lightly edit. They are not byte-identical, so a hash of the raw text does nothing. We need near-duplicate detection: “are these two articles about the same thing, with mostly the same words?”
Approach A: pairwise similarity (the naive version)
For each incoming article, compare it against every article in the recent window and compute text similarity (say Jaccard over word sets, or cosine over TF-IDF vectors).
for incoming in new_articles:
for existing in window: # 35M articles in a 7-day window
if jaccard(incoming, existing) > 0.8:
attach(incoming, existing.canonical)
break
Where it breaks:
- It is
O(N)comparisons per article against a 35M-article window. At ~58 incoming articles/sec, that is ~2 billion full-text similarity computations per second. This is a non-starter. The window is also growing. - Each comparison is itself expensive (set intersection over hundreds of words). You cannot afford even one full pass, let alone one per incoming article.
- It does not shard cleanly: any article could be a duplicate of any other, so you cannot partition the window without missing cross-partition duplicates.
Pairwise comparison is O(N^2) over the corpus. It is correct and completely unusable at scale.
Approach B: exact fingerprint (too strict)
Hash the whole article text (SHA-256) and dedup on exact match. Now it is an O(1) lookup.
Where it breaks: it only catches byte-identical copies. The AP rewrite with a different headline, a different lede, and a trailing “additional reporting by” line is not byte-identical, so it sails through as a new story. Exact hashing catches maybe 10% of the duplicates and misses the entire long tail of rewrites, which is most of the redundancy. Too strict to be useful.
Approach C: MinHash signatures + LSH banding (the answer)
Two ideas stacked. First, MinHash turns each article into a small fixed-size signature such that the probability two signatures’ entries match equals the Jaccard similarity of the original word sets. Second, LSH banding turns “find similar signatures” into a cheap hash-bucket lookup instead of a pairwise scan.
Step 1 - shingling. Represent the article as a set of overlapping k-word shingles (k=3 to 5). Shingling captures word order locally, so “dog bites man” and “man bites dog” differ. Each article becomes a set of shingle hashes.
text: "the central bank raised rates by fifty basis points today"
3-grams: {"the central bank", "central bank raised",
"bank raised rates", "raised rates by", ...}
hashed: {h1, h2, h3, h4, ...} # a set of 32-bit integers
Step 2 - MinHash signature. Apply P independent hash functions (P=128) to the shingle set. For each hash function, keep the minimum hashed value over all shingles. The result is a 128-element signature. The crucial property:
P(minhash_i(A) == minhash_i(B)) = Jaccard(A, B)
So the fraction of the 128 positions where two signatures agree is an unbiased estimate of the Jaccard similarity of the two articles. A 512-byte signature replaces the full article for similarity purposes.
signature(A) = [min over shingles of h_1(s), min of h_2(s), ..., min of h_128(s)]
= [0x3a1f, 0x9c02, 0x0011, ...] # 128 values, 512 bytes
Step 3 - LSH banding (this is what kills the O(N) scan). Split the 128-element signature into b bands of r rows each (e.g. b=32 bands of r=4 rows). Hash each band to a bucket. Two articles are candidates if they land in the same bucket for at least one band.
signature (128 values) split into 32 bands of 4:
band 1: [v1..v4] -> hash -> bucket B1
band 2: [v5..v8] -> hash -> bucket B2
...
band 32: [v125..v128] -> hash -> bucket B32
Insert: for each band, store story_id in LSH_index[band_i][bucket]
Query: for each band, look up LSH_index[band_i][bucket] -> union = candidates
The math: two articles with Jaccard similarity s agree on all r rows of a given band with probability s^r, so they collide in at least one of b bands with probability 1 - (1 - s^r)^b. This is an S-curve with a sharp threshold around s ≈ (1/b)^(1/r). With b=32, r=4, the threshold sits near 0.42, and the curve is steep: articles above ~0.7 similarity almost always become candidates, articles below ~0.3 almost never do. Tune b and r to move the threshold.
Step 4 - verify. LSH gives candidates, not answers (it has false positives by design - that is the price of cheap lookup). For each candidate, compute the exact signature agreement (cheap: compare two 128-element arrays) and attach only if it exceeds the duplicate threshold (say 0.8).
on ingest(article):
sig = minhash(shingle(article.text))
candidates = set()
for i, band in enumerate(split(sig, b=32, r=4)):
candidates |= LSH_index[i].get(hash(band), [])
best = None
for c in candidates: # candidates is tiny, not 35M
sim = signature_agreement(sig, c.sig) # cheap array compare
if sim >= DUP_THRESHOLD and sim > best_sim:
best, best_sim = c, sim
if best:
attach_source(article, best.canonical_story) # no new story, no fan-out
else:
story = create_canonical(article, sig)
for i, band in enumerate(split(sig, b=32, r=4)):
LSH_index[i].setdefault(hash(band), []).append(story)
emit_new_story(story)
Why this is the right call:
- The LSH lookup is
O(b)band hashes and a small union of buckets - effectively constant per article, independent of the 35M-article window. We replaced a 2-billion-comparisons-per-second scan with a few dozen hash lookups per article. - MinHash catches rewrites and partial overlaps, not just exact copies, so it collapses the long tail that exact hashing misses.
- The verify step cleans up LSH’s false positives cheaply, because it only runs on the handful of candidates, not the whole window.
- It shards: the LSH index partitions by band-bucket. Query fans out to the shards owning the relevant buckets.
| Approach | Per-article cost | Catches rewrites? | Breaks on | Verdict |
|---|---|---|---|---|
| Pairwise Jaccard | O(N) over 35M window | Yes | Compute: billions of ops/sec | Unusable |
| Exact hash | O(1) | No, exact only | Any reword | Too strict |
| MinHash + LSH | O(b) band lookups + small verify | Yes | Nothing at this scale | The answer |
The duplicate window and canonical choice. Signatures live in the LSH index for ~7 days then expire - yesterday’s news is not a duplicate candidate for a fresh event, and expiry keeps the index bounded (~20GB). When an article attaches to a canonical story, we pick the canonical representative by source authority and earliest publish time (we prefer to credit the original wire source, and we keep all contributing source IDs so the UI can show “also reported by 18 sources”).
Why dedup must be at ingestion, before fan-out. If we deduped at read time, every user’s feed read would re-run near-duplicate detection over its candidate set - the same duplicates collapsed millions of times per day. By collapsing once at ingestion, the ~5M daily raw articles become ~1M canonical stories that every downstream stage (indexing, fan-out, ranking, reading) operates on. Dedup once, benefit everywhere.
2. The crawl scheduler and politeness
The naive version: a cron job that loops over all 50,000 feeds every 5 minutes and GETs each one.
Where it breaks:
- Wasted work. Most feeds have no new content most of the time. Unconditionally GETting the full feed body every 5 minutes burns bandwidth and parsing on unchanged data. A feed that publishes twice a day is fetched 288 times a day for nothing.
- Politeness violations. A naive loop can hit the same publisher’s host repeatedly in a burst (multiple feeds on one domain), ignore
robots.txt, and get the crawler IP-banned. A banned crawler silently stops ingesting that source - a correctness failure that looks like “that publisher just stopped posting.” - Stragglers block the batch. One slow or hanging feed stalls a synchronous loop. A dead host with a 30-second timeout, times a few hundred such hosts, wrecks the cycle.
Evolved design: an adaptive priority frontier with per-host rate limiting.
- Conditional requests. Store each feed’s
ETagandLast-Modified. SendIf-None-Match/If-Modified-Since. A304 Not Modifiedcosts almost nothing and means skip parsing entirely. This alone removes the bulk of wasted work. - Adaptive polling interval. Track each feed’s observed publish rate. A feed that posts every few minutes (breaking-news wire) gets a short interval; a feed that posts weekly gets a long one. Back off on errors with exponential backoff, and cap the interval. Store
next_dueper feed; the Scheduler is a priority queue ordered bynext_due.
Feed Registry row:
feed_id, url, etag, last_modified,
poll_interval (adaptive), next_due,
consecutive_errors, avg_entries_per_day, host
- Per-host politeness. Partition the frontier by host, not just by feed. A token-bucket rate limiter per host caps concurrent and per-second requests to one publisher, regardless of how many feeds they own. Respect
robots.txtcrawl-delay. This is what keeps us from getting banned. - Stateless async workers. Crawler Workers pull jobs from the frontier, fetch with a strict timeout, and are horizontally scaled. A hung host times out and the worker moves on; the slow feed gets backed off, it does not block anyone.
- Dedup of feed entries at the source. Within a feed, track seen entry GUIDs so a re-fetch of an unchanged feed (that returned 200 anyway) does not re-emit old entries. This is cheap, feed-local dedup, distinct from the cross-source MinHash dedup downstream.
The combination - conditional GETs, adaptive intervals, per-host rate limits, async workers with timeouts - turns a crawl that would melt both us and the publishers into a steady, polite ~167 polls/sec that mostly returns 304s.
3. Fan-out vs pull for candidate generation
Once a new canonical story exists, which users’ feeds should it appear in? This mirrors the social-feed fan-out problem, but the matching is by topic interest, not a follow graph.
Approach A: eager fan-out (push to every matching user)
When a story is created, find every user whose interest vector matches its topics and push the story_id into each of their feed caches, like fan-out-on-write.
Where it breaks: a big breaking-news story (an election, a major outage) matches a huge fraction of users. One story can fan out to millions of feed caches. And unlike a social follow, interest is fuzzy and broad - “technology” might match 5M users. Eager fan-out of a broadly-matching story is a write storm, and it eagerly materializes feed entries for users who may not open the app today. It is the celebrity hot-key problem wearing a topic hat.
Approach B: pure pull (compute candidates at read time)
Store nothing per user. On read, query the recency+topic index for recent stories matching the user’s interest vector, then rank.
Where it breaks (partially): this is actually fine for latency if the index is good, because the candidate set is bounded (recent stories matching a few topics is maybe a few hundred, not millions). The weakness is that a narrow-interest user (follows one niche topic) might have their one relevant story buried, and purely read-time candidate generation does extra index work on every read. But it never explodes. Pull is the safe default.
Approach C: hybrid - pull by default, push for narrow strong matches (the answer)
- Default: pull. On read, generate candidates from the topic+recency index intersected with the user’s interest vector. Bounded candidate set, no write amplification. This handles broad interests and breaking news without fanning anything out.
- Push selectively: for users with a narrow, strong interest (an explicit topic follow, a specific source subscription), eagerly push matching new stories into their feed cache at story-creation time. This set is small per story (narrow interests match few users), so no write storm, and it guarantees niche users do not miss their one relevant story.
on new_story(story):
index_by_topic_and_recency(story) # always; powers pull
narrow_matchers = users_with_explicit_follow(story.topics, story.source)
if len(narrow_matchers) < PUSH_THRESHOLD: # small, specific audiences only
for u in narrow_matchers:
feed_cache.push(u, story.story_id)
# broad-interest users get it via pull at read time
on load_feed(user):
pulled = topic_recency_index.candidates(user.interest_vector, window="48h")
pushed = feed_cache.get(user) # narrow pre-pushed stories
candidates = union(pulled, pushed)
return rank_and_hydrate(candidates, user)
This mirrors the social-feed hybrid: broad/popular content is pulled at read time (never fanned out, so no storm), narrow/specific content is pushed so it is not lost. The threshold between them is the key tuning knob, exactly as the celebrity follower threshold is in a social feed.
4. Per-user ranking and interest vectors
The naive version: sort candidate stories by publish time, newest first.
Where it falls short (not “breaks” - it works, it is just worse): reverse-chronological means a user who cares about two niche topics drowns under high-volume general news, and the single story they would have loved scrolls past. The feed feels generic. Personalization is the product.
Evolved design: a scoring layer over the candidate set, kept off the write path.
The score blends three signals the assignment calls out - freshness, source authority, inferred interest:
score(story, user) = freshness(story)
* authority(story.source)
* interest_match(story.topic_vector, user.interest_vector)
- Freshness. News decays fast. Use exponential time decay:
freshness = exp(-lambda * age_hours). A 2-hour-old story outranks a 2-day-old one of equal relevance.lambdais tuned per section (breaking news decays faster than a long-read). - Source authority. A precomputed per-source score from signals like historical click-through, how often this source is the original in a dedup cluster (wire services are usually first), and editorial trust lists. Authority is slow-changing; recompute it offline daily, store it on the source, and read it at rank time. When articles collapse in dedup, the canonical story inherits the max authority of its contributing sources.
- Interest match. The dot product (cosine) of the story’s topic vector and the user’s interest vector, both in the same ~128-dim topic embedding space.
Building the interest vector. The user vector is an exponentially-weighted moving average of the topic vectors of stories they engage with, with sign:
on event(user, story, kind):
w = {click:+1.0, dwell_long:+2.0, save:+3.0,
hide:-3.0, not_interested:-5.0}[kind]
user.vector = (1 - alpha) * user.vector + alpha * w * story.topic_vector
normalize(user.vector)
Explicit topic follows pin components of the vector high; hides and not-interested push them negative. This is content-based personalization. On top of it, a collaborative-filtering signal complements the cold-start and discovery case: users who engaged with the same stories as you form a neighborhood, and stories popular in your neighborhood but outside your current vector get a boost. Content-based handles “more of what you like”; collaborative handles “things like-minded people liked that you have not seen.” Blend both into interest_match.
The pipeline, read-time:
candidates -> hydrate features (age, authority, topic_vec)
-> score(freshness * authority * interest_match)
-> reorder + diversity rules
-> page
Keep ranking out of the write path entirely, same discipline as any feed system. We do not precompute per-user scores at story-creation time because freshness changes by the minute and interest vectors drift; scoring a few hundred candidates at read time is cheap (sub-10ms) and always fresh. Candidate generation (the expensive part) is indexed; scoring (the freshness-sensitive part) is per read. A strict time budget protects latency: if the scorer is slow or the model service is down, fall back to freshness * authority without the interest term. The feed degrades to “recent and reputable”; it never blanks.
API Design & Data Schema
API
GET /api/v1/feed?limit=30&cursor=<opaque>
Response 200:
{
"stories": [
{ "story_id": "...", "title": "...", "snippet": "...",
"canonical_url": "https://publisher.com/...",
"sources": [ {"name": "Reuters", "url": "..."}, ... ],
"source_count": 19,
"published_at": "2026-11-22T08:12:00Z",
"score": 0.87 },
...
],
"next_cursor": "<opaque>"
}
Latency target: p99 < 200ms
Errors: 401 not authenticated
POST /api/v1/feedback
Body: { "story_id": "...", "action": "hide" | "save" | "not_interested"
| "hide_source", "source_id": "..." }
Response 202 Accepted // async; updates interest vector
POST /api/v1/subscriptions { "topic": "kubernetes" } -> 202
DELETE /api/v1/subscriptions { "topic": "kubernetes" } -> 202
GET /api/v1/topics -> list of topics
# Internal / admin
POST /internal/feeds { "url": "https://x.com/rss" } -> register a feed
GET /internal/feeds/{id}/health -> crawl stats
Pagination is cursor-based, not offset-based. Offsets break when new stories arrive between pages (duplicates or gaps). The cursor encodes (score, story_id) of the last item so the next page is a stable continuation of the ranked list.
Data store choices
Several stores because the access patterns genuinely differ. Be explicit about each.
1. Canonical Story Store - NoSQL wide-column (Cassandra / DynamoDB). Access is point-lookup by story_id and range-scan of recent stories by topic/time. No joins, no cross-row transactions, append-heavy, needs horizontal scale and a rolling TTL. Wide-column fits; a single relational DB does not.
Table: stories
story_id BIGINT PARTITION KEY -- Snowflake: time-sortable
title STRING
snippet STRING
canonical_url STRING
source_ids LIST<BIGINT> -- all contributing sources
minhash_sig BLOB -- 512 bytes, kept for re-check
topic_vector BLOB -- 128-dim float16
authority FLOAT -- inherited max of sources
published_at TIMESTAMP
ttl 30 days
Shard by: story_id (uniform, single-key reads land on one shard)
Table: stories_by_topic -- powers pull-based candidate generation
topic_id INT PARTITION KEY
published_at TIMESTAMP CLUSTERING KEY DESC
story_id BIGINT
Read pattern: "recent stories in topic T" = single-partition range scan
Shard by: topic_id
2. LSH Index - in-memory, sharded (Redis / custom). Maps (band_index, bucket_hash) -> [story_id], 7-day TTL on entries. Sharded by band bucket. ~20GB, in memory for the band-lookup latency the dedup path needs.
Key: lsh:{band_index}:{bucket_hash} -> SET of story_id
TTL: 7 days (rolling duplicate window)
Shard by: hash(band_index, bucket_hash)
3. Feed Registry - SQL (Postgres). This is the one place a relational store earns its keep: it is small (50K rows), low write rate, and benefits from indexed queries like “feeds due now” and per-host grouping. The scheduler reads it constantly with ordered queries; a B-tree index on next_due is exactly right.
Table: feeds (Postgres)
feed_id BIGSERIAL PK
url TEXT UNIQUE
host TEXT INDEX (per-host rate limiting)
etag TEXT
last_modified TIMESTAMP
poll_interval INT -- adaptive, seconds
next_due TIMESTAMP INDEX (scheduler reads "WHERE next_due < now ORDER BY next_due")
consecutive_errors INT
avg_entries_per_day FLOAT
4. Interest Store - key-value (Redis + durable backing). user_id -> interest_vector (512 bytes). Updated async from the feedback event stream; rebuildable by replaying the event log, so it is a derived cache. Sharded by user_id.
5. Feed Cache - Redis. user_id -> [story_id] for pre-pushed narrow-match stories, and a short-TTL cache of the last rendered page. Sharded by user_id.
6. Event log - Kafka + cold storage. Every click/dwell/hide is appended. It is the system of record for behavior, the source for rebuilding interest vectors, and the training data for the ranker and authority scores.
Why NoSQL for stories, SQL for the registry. The story corpus is high-volume, key-scoped, transaction-free, TTL-bounded, needing horizontal scale to hundreds of GB - wide-column territory. The feed registry is small, relational, and queried with ordered range scans by a single consumer - a classic Postgres job. Match the store to the access pattern instead of forcing one everywhere.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. Dedup comparison cost (breaks first without LSH). A pairwise scan is billions of comparisons/sec.
Fix: MinHash + LSH banding turns it into O(b) band-bucket lookups per article plus a tiny verify. The LSH index is sharded by band bucket and holds only a 7-day window, keeping it ~20GB and bounded. This is the single decision that makes ingestion possible.
2. Hot LSH bucket on a mega-event. A giant breaking story spawns thousands of near-duplicates in minutes, all landing in the same band buckets - one bucket’s SET grows huge and the verify step compares against hundreds of candidates. Fix: cap bucket size and, once a canonical story has absorbed N duplicates, mark it “saturated” so further matches attach by cheap signature check against the canonical only, not an all-candidates scan. The hot event collapses to one canonical fast.
3. Crawl politeness / getting banned. Bursting a publisher’s host gets the crawler IP-blocked, silently killing a source.
Fix: per-host token-bucket rate limits, robots.txt crawl-delay, conditional GETs so most polls are cheap 304s, exponential backoff on errors, and a rotating pool of egress IPs with per-host caps. Partition the frontier by host so no host is ever hammered.
4. Feed read QPS (7K/sec) with per-user ranking. Cannot scan the whole corpus per read. Fix: bounded candidate generation from the topic+recency index (recent stories matching a few interest topics is a few hundred, not millions), then cheap read-time scoring. Cache the rendered page for a short TTL so rapid refreshes hit cache. Store story IDs, hydrate with one batched read.
5. Fan-out write amplification on broad stories. A story matching millions of users would storm the feed caches if pushed eagerly. Fix: the pull-by-default hybrid. Broad/popular stories are pulled at read time (never fanned out); only narrow, strong-match stories are pushed. The push threshold bounds per-story write cost.
6. Interest vector update throughput. 200M+ engagement events/day each mutating a user vector. Fix: updates are async off the Kafka event stream, batched per user (coalesce a user’s events in a short window into one vector update), and the vector is a derived cache rebuildable from the log. No synchronous write on the read path.
7. Canonical store growth and stale news.
Fix: 30-day TTL on stories (news goes cold); the hot working set is ~40GB, fully cacheable. Shard by story_id (Snowflake, uniform) so writes spread with no hot shard. Never shard by published_at - that concentrates all current writes on the “now” shard, a permanent hot spot, the classic mistake.
Shard keys, stated plainly: Canonical store -> story_id (single-key reads). stories_by_topic -> topic_id (range scan of a topic). LSH index -> (band_index, bucket_hash). Feed registry -> indexed on next_due and host. Interest + feed cache -> user_id.
8. Ranking service as a latency/availability risk on the read path.
Fix: strict scoring time budget and a freshness * authority fallback if the model/interest service is slow or down. The feed degrades to recent-and-reputable, never blank.
9. Single points of failure. Crawler Workers, Parser, Dedup Service, Feed Service, and Ranking Service are all stateless and horizontally scaled behind load balancers or as Kafka consumer groups. Kafka, Redis, and the stores are replicated. The Scheduler is the one coordinator - run it as a small leader-elected HA pair, and because next_due lives durably in Postgres, a failover just resumes from the registry with no lost state.
10. Multi-region. Deploy Feed Service, caches, and read replicas per region, routed by GeoDNS. Ingestion and dedup can run centrally (or in one primary region) since freshness tolerates seconds of cross-region replication lag; the read path is what must be local and fast.
Wrap-Up
The trade-offs that define this design:
- MinHash + LSH over pairwise comparison. We trade exactness (LSH has tunable false positives, cleaned up by a cheap verify) for turning an
O(N^2)corpus scan into near-constant band lookups. Without it, ingestion is impossible; with it, dedup is a few hash lookups per article. - Dedup once at ingestion, before fan-out. We collapse ~5M daily raw articles into ~1M canonical stories one time, so every downstream stage operates on a clean, 5x-smaller set. Deduping at read time would redo the same work millions of times a day.
- Pull-by-default hybrid fan-out. Broad and breaking stories are pulled at read time so nothing storms the feed caches; narrow, strong-match stories are pushed so niche users do not miss them. The push threshold is the key knob.
- Ranking at read time, off the write path. Candidate generation is indexed; the freshness-sensitive scoring (freshness x authority x interest) runs per read in under 10ms with a degrade-to-recency fallback, blending content-based and collaborative signals.
- Store matched to access pattern. Wide-column NoSQL for the TTL-bounded story corpus, in-memory sharded LSH for dedup, and plain Postgres for the small, ordered-query feed registry. No single store forced everywhere.
One-line summary: a crawl-dedup-rank pipeline where thousands of RSS/Atom feeds are polled politely with conditional requests, incoming articles are collapsed into canonical stories once at ingestion via MinHash LSH near-duplicate detection, and a pull-by-default candidate set is ranked per user by freshness, source authority, and an inferred interest vector in under 200ms at thousands of feed reads per second.
Comments