Topic-Based Article Aggregator: Crawling, Dedup, and Feed Serving
System DesignModel answerLast updated
Design a service that polls tens of thousands of external publishers, stores articles without duplicates, and serves topic timelines with stable pagination under 50ms p99.
Problem
You are asked to design a content aggregation backend. It regularly fetches articles from outside publishers (RSS/Atom feeds and news APIs), assigns each article to one or more topics, keeps them durably, and lets clients read a per-topic timeline, newest first.
Functional requirements
- Polling: Pull from tens of thousands of sources, each on its own cadence (roughly every 5 to 60 minutes), without exceeding what each source permits.
- Safe re-ingestion: Retried jobs and publishers that re-emit old items must never create duplicate articles.
- Topics: An article can belong to several topics out of a fixed catalog (for example
payroll,benefits,compliance). - Timeline reads: Clients fetch a topic's articles in reverse chronological order, with pagination that neither repeats nor skips items while new articles keep arriving.
Non-functional requirements
- p99 latency below 50 ms for topic reads.
- No loss of an article once it has been accepted. Reads must be highly available.
- A slow or broken publisher must not be able to consume the capacity needed by healthy ones.
Scale
| Dimension | Value |
|---|---|
| Registered sources | 50,000 |
| New articles | about 5M/day (about 60/s average, about 300/s peak) |
| Retained data | about 100M articles over 12 months |
| Topic read traffic | 10,000 QPS |
| Topics | about 500; the top 20 take about 80% of reads |
What to cover
- The read API, including pagination.
- How fetches are scheduled, dispatched, and rate-limited across many workers.
- Storage schema, indexes, and the keys used to make writes idempotent.
- How the read path meets 10k QPS and the latency target, including the cache layout and cursor design.
- The main trade-offs: freshness against latency, write amplification from per-topic indexing, and cursor versus offset pagination.
Hints
Hint 1
Do the arithmetic first: 50k feeds at about 15 minute intervals is only about 55 fetches/s, and 5M articles/day is a small write rate. The hard parts are unreliable third parties, idempotency, and a skewed read load, not raw throughput.
Hint 2
For dedup, think in layers: a canonical URL hash, a per-source GUID, and a content hash to tell a real edit from a harmless re-publish. Make the write an upsert so at-least-once delivery is safe everywhere upstream.
Hint 3
For pagination, use a cursor made of (published_at, article_id) so the order is total and ties are broken deterministically. Use the same ordering in the cache (a sorted set per topic) and in the database fallback query so both give identical pages.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
There are three loosely coupled subsystems: a scheduler that fetches from unreliable third parties, an idempotent storage layer, and a latency-sensitive timeline read path. Keeping them decoupled through a durable queue lets each scale and fail independently.
1. Sizing
- Fetch rate: 50k feeds at about 15 min average is about 55 fetches/s. Without jitter, interval boundaries can burst 5-10x higher.
- Writes: 60/s average and 300/s peak is easy for a sharded relational store.
- Storage: about 2 KB metadata per article means about 200 GB for 100M rows. Raw bodies at about 10 KB are about 1 TB in object storage.
- Topic index: with 2-3 topics per article, about 250M index rows and roughly 175 index writes/s.
- Reads: 10k QPS, with the hot set (top 20 topics) tiny and very cacheable.
Clarify: is ordering by publish time or ingest time, is about 30 s staleness on page one acceptable, and must edits/retractions propagate (assume yes).
2. API
GET /v1/topics/{slug}/articles?limit=20&cursor=...
-> { items: [{id,title,summary,url,source,published_at,topics}], next_cursor, has_more }
GET /v1/articles/{id}
The cursor is an opaque, HMAC-signed encoding of (published_at_ms, article_id). Opacity lets us change internals later. Cap limit at 100.
3. Data model and idempotency
- feeds: id, url, domain, interval, next_fetch_at, etag, last_modified, failure count, lease owner/expiry, status.
- articles (sharded by id, time-sortable IDs like ULID):
url_hash(SHA-256 of canonical URL, UNIQUE),(source_id, source_guid)UNIQUE,content_hash, title, summary,body_ref(object-store key), published_at, ingested_at, version, status. - topic_articles: primary key
(topic_id, published_at DESC, article_id DESC), with summary fields denormalized so a page is one range scan.
Canonical URL: lowercase host, strip www., drop fragments and tracking params (utm_*, fbclid), sort remaining params, honor rel=canonical.
Upsert: insert on conflict of url_hash; update only when content_hash differs, bumping version and emitting an update event. A retry or re-publish carries identical content, so it is a no-op. A real edit is applied once.
Near-duplicates (wire stories across outlets) are found with SimHash and grouped under a story_id rather than deleted.
Clamp published_at to min(published_at, ingested_at) so a future-dated item cannot sit at the top forever.
4. Pipeline
- Scheduler hands due feeds to a queue (Kafka/SQS).
- Fetch workers acquire a per-domain token, send a conditional GET (ETag / If-Modified-Since), store the raw payload, and publish parsed items to Kafka with
acks=all. - Ingestion service canonicalizes, upserts, classifies topics (source defaults, keyword rules, a light ML model), and writes
articles,topic_articles, and an outbox row in one transaction. - Timeline updater consumes the outbox via CDC and updates Redis.
- Read API goes CDN/local cache, then Redis, then database.
Durability: replicated Kafka, then a database with a synchronous replica and PITR, with raw payloads replayable from object storage. Nothing is acknowledged before it is durable. Redis only holds derived data and is rebuildable.
5. Scheduler
- Hash-partition feeds into shards, each owned by one scheduler instance (leader election through etcd/ZooKeeper leases).
- Each owner polls: select due rows (
next_fetch_at <= now()) withFOR UPDATE SKIP LOCKED, set a lease (about 2 min), advancenext_fetch_atby interval plus jitter, and enqueue. - A crashed worker's lease expires and the feed is re-dispatched. At-least-once is safe because ingestion is idempotent.
- Rate limiting: a per-domain token bucket in Redis (Lua for atomicity). With no token, re-delay the job instead of blocking a thread.
- Isolation: per-domain concurrency caps, timeouts, and circuit breakers with exponential backoff on
consecutive_failures. Slow sources go to a separate queue or pool so they cannot starve others. - Adaptive intervals: back off toward 60 min on 304s or empty results; tighten toward 5 min for active feeds.
6. Read path
Redis sorted set per topic: key topic:{id}, score published_at_ms, member a fixed-width article_id. After each ZADD, trim to the newest about 5,000 entries. Memory: 500 x 5k x about 100 B is about 250 MB. Replicate hot keys across read replicas. Summaries are cached separately and fetched with a pipelined multi-get.
Keyset pagination with cursor (t, id): query scores <= t in descending order, then discard entries where score == t and id is not strictly before the cursor. Equal scores sort lexicographically in Redis, giving a deterministic total order. The database fallback for deep pages uses the same order:
SELECT ... FROM topic_articles
WHERE topic_id = ? AND (published_at, article_id) < (?, ?)
ORDER BY published_at DESC, article_id DESC LIMIT ?;
Why not OFFSET: inserts at the head shift every item down, so the next page repeats items; deletions cause skips; and large offsets scan and discard rows. A cursor anchors to a position in the ordering, so head inserts cannot disturb later pages.
Latency: page one of the top 20 topics comes from CDN or an in-process cache with a 5-15 s TTL, which absorbs most of the 10k QPS. Misses go to Redis (about 1-3 ms plus a pipelined fetch). Only deep pages touch the database. Coalesce concurrent misses (single-flight) to prevent stampedes.
7. Trade-offs
- Freshness vs latency: short TTLs on page one give about 5-15 s staleness for a large cut in load. Cache invalidation on publish can tighten this for breaking topics.
- Write amplification: each article becomes 2-3 topic index rows plus cache updates (about 175 index writes/s here). That is cheap, and it buys single-scan reads. Fan-out on write beats computing joins at read time.
- Cursor vs offset: cursors give stability and constant cost but no "jump to page N". For a news feed this is the right choice.
- Edits/retractions: a status or version change emits an event that updates or removes the Redis entry and invalidates caches.
Common mistakes
- Using
OFFSETpagination, or a cursor on timestamp alone (ties cause skips). - Different sort orders in cache and database, so page boundaries disagree.
- Treating scheduler dispatch as exactly-once instead of making ingestion idempotent.
- No per-domain isolation, so one slow publisher ties up the worker pool.
- Using Redis as the source of truth.