Skip to content

Design a News Aggregator (Google News)

Intermediate 76 min read Part 17 of 18

Design Google News: ingest RSS and sitemaps, dedupe and cluster stories, categorise, rank per region, cache at the CDN, paginate infinitely, stay fresh.

The Problem#

Design a news aggregator like Google News, Apple News or Yahoo News. The service collects articles from tens of thousands of publishers around the world, groups articles about the same event into stories, sorts them into categories (World, Business, Technology, Sports, Local), and shows each reader a ranked feed they can scroll through endlessly. Clicking an article sends the reader to the publisher's website to read it.

Google News started in 2002 (its first version was built by Krishna Bharat, a Google researcher who wanted a way to follow coverage of the September 11 attacks across many sources). Its core idea is still the core of this design: no human editors choose the front page; algorithms collect, cluster and rank.

At first glance this looks like the social news feed problem, but it is different in an important way. In a social feed every user's feed is different because everyone follows different people, so the system must build millions of personalised feeds. In a news aggregator, most readers in the same region and category see nearly the same feed. The "Top stories in Technology for UK readers in English" feed is shared by millions of people. That makes this a scaling reads problem: compute a modest number of feeds well, then serve them to an enormous audience from caches and CDNs.

The interesting problems are:

  • Ingesting articles from tens of thousands of publishers within minutes of publication, using RSS and Atom feeds, sitemaps and push protocols, without overloading publishers or ourselves.
  • De-duplicating and clustering: the same wire-service story appears on hundreds of sites with small edits; dozens of different articles cover the same event. Readers want one story card with many sources, not 200 copies.
  • Categorising each article (Sports? Politics? Both?) and placing it in the right regions and languages.
  • Ranking stories per region and category by importance, freshness, source quality and diversity.
  • Serving feeds in under 200 ms to tens of millions of users, surviving 10× traffic spikes when big news breaks.
  • Infinite scroll that does not show duplicates or skip items while the ranking changes underneath.
  • Freshness: a new article should be in feeds within about 30 minutes (ideally a few minutes) of publication.

Analogy. A news aggregator is like a newsstand manager at a busy train station who receives bundles from thousands of newspapers every hour. Assistants open the bundles (ingestion), throw away duplicate copies of the same agency report (de-duplication), staple together all papers covering the same event (clustering), and sort the stacks onto shelves: Sports, Business, Local (categorisation). The manager decides which stacks go in the front window (ranking), and because every commuter sees the same window, the window is arranged once and seen by everyone (caching). When a huge story breaks, crowds surge; the window does not need to be rearranged for each person, it just has to be visible to more people at once (the CDN). Commuters who keep walking along the display (infinite scroll) should not see the same stack twice, even while the assistants are moving stacks around.

Background: a few terms used in this design#

  • Publisher (source): a news organisation or website whose articles we include.
  • RSS and Atom: XML formats in which websites publish a list of their latest items (title, link, summary, publication date). RSS 2.0 is the most common; Atom is standardised as RFC 4287.
  • Sitemap and news sitemap: XML files listing a site's URLs. Google's news sitemap extension lists recent articles (Google's guidance is articles from roughly the last two days, up to 1,000 URLs per sitemap) with publication date and title.
  • WebSub (formerly PubSubHubbub): a W3C recommendation for push notifications of feed updates: publishers ping a hub, and the hub notifies subscribers.
  • Canonical URL: the publisher's declared preferred URL for an article (<link rel="canonical">), used to collapse URL variants.
  • Near-duplicate: two documents that are almost identical (same text with small edits). Detected with fingerprints such as SimHash or MinHash.
  • Story (cluster): a group of articles about the same event.
  • Feed: a ranked list of stories for a particular audience: region, language and category (and optionally a user).
  • Cursor: an opaque token telling the server where the previous page ended, used for pagination.
  • CDN (content delivery network): a network of edge servers that cache responses close to users.

Clarifying Questions#

QuestionWhy it mattersAssumed answer
How many publishers and articles per day?Ingestion scaleAbout 50,000 sources; around 1 million new articles per day
How many readers?Read scale, caching100 million daily active users, global
Do we host full articles or link out?Storage, copyright, renderingLink out; we show headline, snippet, thumbnail and source
Personalised feeds or the same for everyone?Whether feeds can be shared and cachedCore: per region, language and category. Personalisation is an extension
Freshness requirement?Polling frequency, pipeline latencyNew articles visible within 30 minutes; breaking news faster
Feed latency target?Caching designUnder 200 ms p99
How far can users scroll?Pagination and feed length"Infinitely" in practice; we keep a few hundred to a thousand stories per feed
Do we cluster stories or list articles?Processing pipelineCluster into stories with multiple sources
Which categories?Classification designFixed top-level set (World, Business, Technology, Science, Health, Sports, Entertainment, Local) plus topics
Images and video?Media pipeline and CDNThumbnails we generate and serve from our CDN; videos link out
Logged-in users?Personalisation, saved articlesOptional; anonymous users get regional feeds
Consistency versus availability?Trade-off for failuresAvailability first: a slightly stale feed is better than no feed

Requirements#

Functional requirements#

  1. View an aggregated feed of news from thousands of publishers worldwide, by region, language and category.
  2. Scroll infinitely through the feed without duplicates or gaps.
  3. Click through to the publisher's site to read the full article.
  4. See stories as clusters: one card per event with several sources ("Full coverage").
  5. Browse categories (Sports, Politics, Technology and so on) and local news.

Below the line (extensions): personalised "For you" feeds based on interests and reading history; following topics or sources; saving articles; sharing to social media; search over news (similar to Design Post Search (Facebook Search)).

Non-functional requirements#

  • Availability over consistency. If parts of the system fail, show a slightly stale feed rather than an error. 99.9 % or better for feed reads.
  • Low latency: feed pages in under 200 ms at p99.
  • Freshness: articles appear in feeds within 30 minutes of publication, typically within a few minutes for frequently updated sources.
  • Scale: 100 million daily users, traffic spikes of 10× or more during breaking news.
  • Politeness: never overload publishers; respect robots.txt, rate limits and agreements.
  • Quality: no duplicate stories in a feed; diverse sources; low-quality or misleading sources demoted.

Capacity Estimation#

These are design targets, not any company's real figures. See Back-of-the-Envelope Estimation.

Ingestion.

  • 50,000 sources. Large publishers post hundreds of articles a day; most small sources post a few.
  • About 1 million new articles per day ≈ 12 per second average, with peaks of perhaps 50–100 per second during busy news hours. Updates to existing articles (corrected headlines, live blogs) add a similar number of re-fetches.
  • Feed polling: if the median source is polled every 5 minutes and busy ones every minute, 50,000 sources produce about 50,000 / 300 ≈ 170 feed fetches per second on average, a few hundred per second at most. Each fetch is a few KB to a few hundred KB of XML, and conditional requests (ETags) mean most return "304 Not Modified" with no body.
  • Article page fetches: about 12–25 per second (new articles plus updates), each about 100 KB–2 MB of HTML. That is under 50 MB/s of ingest bandwidth, which is small.

Ingestion is not the hard part for raw throughput; it is hard for politeness, freshness and parsing messy HTML.

Storage.

  • Per article: metadata (URL, title, snippet, source, times, language, categories, cluster ID, entities) ≈ 2–5 KB; extracted text ≈ 5–20 KB (kept for clustering and classification); embeddings (a 384- to 768-dimension float vector) ≈ 1.5–3 KB; thumbnail images in 3 sizes ≈ 50–150 KB.
  • 1 million articles a day × ~25 KB of text and metadata ≈ 25 GB per day, about 9 TB per year.
  • Thumbnails: 1 million × 100 KB ≈ 100 GB per day, about 36 TB per year in object storage.
  • Feeds rarely need anything older than a few days, so the hot working set is small: the last 48–72 hours, about 3 million articles and their clusters, fits comfortably in memory on a handful of servers.

Reads.

  • 100 million daily active users, each opening the app or site about 3 times a day and loading about 3 pages per visit (initial page plus two scrolls): 100 million × 9 ≈ 900 million feed page requests per day ≈ 10,000 per second average.
  • Peak-to-average around 3× in daily cycles (mornings in large time zones) gives 30,000 per second, and breaking news can multiply that by 5–10×: plan for 200,000–300,000 feed requests per second at peak.
  • Click-throughs: perhaps 2 per visit ≈ 600 million per day ≈ 7,000 per second average.
  • Thumbnail requests: each feed page shows about 20 images: 18 billion image requests per day ≈ 200,000 per second, almost all from the CDN.

Number of distinct feeds. Suppose 60 region-language editions × 12 categories (plus Top Stories and Local) ≈ 1,000 distinct non-personalised feeds, plus a few thousand topic feeds ("Climate change", "Premier League"). Local feeds by city add maybe tens of thousands more. Each feed holds the top 500–1,000 stories. 1,000 feeds × 1,000 stories × 200 bytes per entry (story ID plus score) ≈ 200 MB: trivially cacheable.

Read-to-write ratio. About 10,000 feed reads per second against about 12 article writes per second: roughly 1,000:1. And because feeds are shared, the effective ratio per cached object is far higher. This is the defining property of the design.

QuantityEstimate
New articles~1M/day, ~12/s average
Feed fetches from publishers~200/s
Feed page requests~10k/s average, 200–300k/s breaking-news peak
Click-throughs~7k/s average
Thumbnail requests~200k/s, nearly all CDN hits
Hot article setlast 72 hours, ~3M articles, a few tens of GB
Distinct shared feeds~1,000 editions × categories, plus topics and local

Core Entities#

  • Source (publisher): name, home URL, feeds and sitemaps, country, language, quality and authority scores, crawl policy.
  • Feed endpoint: an RSS/Atom URL or sitemap of a source, with polling schedule, ETag, last-modified and observed publishing rate.
  • Article: canonical URL, title, snippet, author, publication and update times, language, extracted text, thumbnail reference, categories, entities, fingerprints, embedding, cluster ID.
  • Story (cluster): a group of articles about one event: representative headline, member articles, first-seen time, last-updated time, categories, regions, score.
  • Category / topic: a node in the taxonomy (Sports → Football → Premier League).
  • Feed (edition): a ranked list of story IDs for a (region, language, category) key, with a version number and generation time.
  • Click event: user or session, article, feed, position, time; used for ranking signals and analytics.
  • User (optional): preferences, followed topics and sources, reading history for personalisation.

API Design#

Readers use a simple read API; everything else is internal. See API Design Best Practices.

GET /v1/feed?edition=en-GB&category=technology&cursor=<opaque>&limit=20
    → 200 {
        stories: [ { storyId, headline, thumbnailUrl, topArticle: { articleId, source, title, url, publishedAt },
                     moreSources: 37, updatedAt } ... ],
        nextCursor: "eyJ2IjoxNzMzMjAwMDYwLCJvIjo0MH0",   # feed version + position
        feedVersion: 1733200060
      }
    Cache-Control: public, max-age=30, stale-while-revalidate=60, stale-if-error=600
 
GET /v1/stories/{storyId}?edition=en-GB        → full coverage: all articles in the cluster, grouped
GET /v1/categories?edition=en-GB              → category list and local options
GET /r/{articleId}?f=<feed>&p=<position>      → 302 Location: https://publisher.example/article (logs the click)
 
# Optional, logged-in
GET  /v1/feed/for-you?cursor=...               → personalised, Cache-Control: private
POST /v1/me/follows   { topicId | sourceId }

Design notes:

  • Edition combines region and language, because "UK English" and "India English" have different top stories.
  • The cursor encodes the feed version and position (Deep Dive 6). It is opaque so we can change its format freely.
  • Responses are public and cacheable for non-personalised feeds: the same URL gives the same bytes to everyone in that edition, so a CDN can serve them. A short max-age keeps them fresh; stale-while-revalidate lets the CDN serve the old copy while fetching a new one; stale-if-error keeps serving if the origin fails.
  • The click redirect (/r/{articleId}) gives us reliable click measurement and lets us change destination URLs (for example to an updated canonical URL). The cost is an extra round trip (tens of milliseconds) before the publisher's page loads. An alternative is linking directly to the publisher and logging clicks with a navigator.sendBeacon call or the HTML ping attribute, which is faster for the reader but less reliable (ad blockers, browser support). Deep Dive 9 discusses the trade-off.
  • No write API for readers in the core design; personal actions (follows) are an extension.

High-Level Design#

The system has two halves joined by a small, hot dataset. The write side (ingestion and processing) turns publisher feeds into clustered, categorised, ranked stories. The read side serves precomputed feeds from caches and CDNs. We build it one requirement at a time.

1) Ingest articles from thousands of publishers#

A source registry holds every publisher and its feed URLs. A crawl scheduler decides when each feed is next due, based on how often that source publishes. Feed fetchers download feeds with conditional requests, parse new items, and push article URLs onto a queue. Article fetchers download each article page (respecting robots.txt and per-host rate limits), and an extractor pulls out the headline, main text, publication time, canonical URL and lead image. Publishers that support WebSub push notifications to a callback endpoint so we can fetch immediately instead of waiting for the next poll.

2) Deduplicate, cluster and categorise#

Each extracted article flows through a processing pipeline: normalise and de-duplicate (exact URL and content matches, then near-duplicates by fingerprint), compute an embedding, classify categories and detect locations and entities, then assign the article to a story cluster (an existing one if it is about the same event, otherwise a new one). The results are written to the article and story store.

3) Build ranked feeds per region and category#

A feed builder runs continuously (for example every 30–60 seconds per feed, and immediately for breaking stories). For each edition and category, it scores recent stories (freshness, number and quality of sources covering it, local relevance, diversity), selects the top several hundred, and writes a feed snapshot with a version number to a fast feed cache (Redis or Memcached) and to a durable store.

4) Serve the feed with infinite scroll#

The feed API reads the requested snapshot from the feed cache, slices out the requested page using the cursor, hydrates story IDs with headline, thumbnail and source from a story cache, and returns JSON. The response is cacheable, so a CDN in front serves most requests without touching the origin. Thumbnails come straight from the CDN backed by object storage.

5) Click through to the publisher#

Clicking a story hits a lightweight redirect service that logs a click event (asynchronously, to a log or stream) and returns 302 to the publisher's URL. Click events feed ranking signals and analytics through a stream processor.

The full high-level design#

Components:

  • Source registry and crawl scheduler: the list of publishers and feeds, and an adaptive schedule that polls busy sources often and quiet ones rarely.
  • Feed and article fetchers: polite HTTP clients with per-host concurrency limits, conditional requests, robots.txt caching and retry handling. Similar machinery to Design a Web Crawler, but far smaller in scope.
  • Extractor: parses HTML into clean article fields; handles messy markup, structured data (schema.org NewsArticle, Open Graph tags) and canonical URLs.
  • Media pipeline: downloads lead images, makes thumbnails in several sizes and formats, and stores them in object storage.
  • Dedupe and clustering: fingerprints for duplicates, embeddings and entities for grouping articles into stories.
  • Classifiers: category, language and location models.
  • Feed builder: scores and ranks stories per edition and category and writes versioned snapshots.
  • Article and story store: durable metadata for articles and stories (a relational database or wide-column store), plus a search index if search is in scope.
  • Feed and story caches: in-memory caches holding snapshots and hydrated story cards.
  • Feed API and redirect service: stateless read services behind the CDN.
  • Event log and warehouse: click and impression events for ranking signals and analytics.

Key Flows#

Flow 1: a publisher posts an article#

For a publisher without WebSub, the first two steps are replaced by the crawl scheduler triggering a conditional GET of the feed. With a 5-minute polling interval, the average extra delay is about 2.5 minutes.

Flow 2: a reader opens the Technology feed and scrolls#

The second page is read from the same snapshot version as the first, even if a newer version has been built since. That is what makes pagination consistent (Deep Dive 6). Cursor pages are also cacheable: everyone who scrolls from the same version gets byte-identical pages.

Flow 3: breaking news#

A major event happens. Within minutes, dozens of publishers post articles. The ingestion pipeline sees a burst of new articles that cluster into one story whose source count grows rapidly; the feed builder detects velocity (sources added per minute) and rebuilds affected feeds immediately instead of waiting for the next cycle. Readers flood in. The CDN absorbs the surge because feed pages are identical for everyone in an edition, and the origin sees roughly one request per edition, category and CDN point of presence every 30 seconds rather than one per reader. Deep Dive 11 covers the spike in detail.

Data Model#

CREATE TABLE article (
  article_id     BIGINT PRIMARY KEY,            -- time-ordered ID
  source_id      BIGINT NOT NULL REFERENCES source(source_id),
  story_id       BIGINT,                        -- cluster, set by clustering
  canonical_url  TEXT NOT NULL,
  url_hash       BYTEA NOT NULL UNIQUE,         -- SHA-256 of normalised canonical URL
  content_hash   BYTEA NOT NULL,                -- exact duplicate detection
  simhash        BIGINT NOT NULL,               -- near-duplicate fingerprint
  title          TEXT NOT NULL,
  snippet        TEXT,
  language       TEXT NOT NULL,
  published_at   TIMESTAMPTZ NOT NULL,
  updated_at     TIMESTAMPTZ NOT NULL,
  thumbnail_key  TEXT
);
CREATE INDEX article_story_idx   ON article (story_id, published_at DESC);
CREATE INDEX article_recent_idx  ON article (published_at DESC);
CREATE INDEX article_content_idx ON article (content_hash);
 
-- Versioned feed snapshot: one row per (feed, version); story IDs packed in order.
CREATE TABLE feed_snapshot (
  feed_key     TEXT   NOT NULL,                 -- e.g. 'en-GB:technology'
  version      BIGINT NOT NULL,                 -- build time in seconds
  story_ids    BIGINT[] NOT NULL,               -- ranked, up to ~1000
  PRIMARY KEY (feed_key, version)
);
DataStoreWhy
Sources and feed endpointsRelational database (PostgreSQL)Small (tens of thousands of rows), relational, edited by tools
Articles and storiesRelational database partitioned by time, or a wide-column storeAbout 1M rows a day; queries by recency and by story; old partitions archived
Article text and embeddingsObject storage plus a vector index for recent articlesText is large and read only by processing; vectors for nearest-neighbour clustering
Fingerprints for dedupeIn-memory index (Redis or a custom service) over the last few daysVery fast lookup on every new article
Feed snapshotsRedis (hot versions) plus durable copyRead on every uncached feed request
Story cardsRedis or MemcachedHydration of feed pages
ThumbnailsObject storage behind the CDNImmutable, high read rate
Click and impression eventsKafka, then a warehouseHigh-volume append-only events

Why a relational database is enough here. Write volume is tiny (tens of rows per second), the data is relational (source → article → story → category), and the hot dataset is small. Time-based partitioning (one partition per day) keeps indexes small and lets old partitions be dropped or archived cheaply. A wide-column store would work too but brings no real benefit at this scale. See Choosing a Database: A Decision Guide.

Why snapshots are stored as arrays. A feed is read as a unit, ranked by the builder, and never queried by individual fields. Packing story IDs into one value per version (an array in PostgreSQL, a list or a serialised blob in Redis) makes a page read a single key lookup and a slice, which is as cheap as a read can be.

Deep Dives#

1. Crawling and ingesting publisher feeds: RSS, Atom, sitemaps and WebSub#

Discovery channels. We learn about new articles in four ways, in rough order of preference:

  1. Push (WebSub). The publisher's feed declares a hub (<link rel="hub" href="...">). We subscribe with a callback URL; when the publisher updates its feed, it pings the hub and the hub POSTs the new content to us within seconds. Lowest latency, lowest load on both sides. Adoption among publishers is partial, so it complements polling rather than replacing it.
  2. RSS and Atom feeds. Most news sites publish one or more feeds (often per section). Each item has a title, link, publication date, summary and sometimes categories and images (Media RSS). We poll these on an adaptive schedule.
  3. News sitemaps. Many publishers maintain a news sitemap listing recent articles with publication dates, intended for search engines. It is often more complete than RSS (which may list only the latest 10–50 items).
  4. Homepage and section-page crawling. For sources with no feed, fetch the homepage and section pages and extract article links. More expensive and error-prone; used as a fallback.

Large aggregators may also have direct publisher integrations (APIs or content partnerships), which are outside this design's core but fit the same pipeline.

Conditional requests save almost everything. Each poll sends If-None-Match with the last ETag and If-Modified-Since with the last Last-Modified. If nothing changed, the server replies 304 Not Modified with no body. Since most polls find nothing new, this cuts bandwidth and publisher load by an order of magnitude. Not every server supports these headers correctly, so we also hash the feed body and skip parsing when it is unchanged.

Adaptive polling. A fixed interval is wasteful: polling a blog that posts weekly every minute is 10,000 wasted requests a week, while polling a wire service every 30 minutes misses the freshness target. Instead, estimate each feed's publishing rate and set the interval accordingly:

on each fetch of feed f:
    new_items = items not seen before
    # exponentially weighted estimate of items per hour
    f.rate = 0.8 * f.rate + 0.2 * (len(new_items) / hours_since_last_fetch)
    # target: expect about 1 new item per fetch, clamped
    interval = clamp(1 / max(f.rate, 0.01) hours, min = 1 minute, max = 6 hours)
    if f.source.priority == HIGH:              # major outlets, wire services
        interval = min(interval, 2 minutes)
    if fetch failed: interval = backoff(f.failures)   # 1m, 2m, 4m ... capped
    f.next_fetch_at = now + interval * random(0.9, 1.1)   # jitter avoids synchronised bursts

If publishing follows roughly a Poisson process with rate λ items per hour, then polling every T hours means an item waits on average T/2 before we see it. To keep the average delay under 5 minutes, poll at least every 10 minutes; to keep the maximum under 30 minutes, poll at least every 30 minutes. Time-of-day patterns (publishers post more in business hours) can be modelled per source to poll faster in busy hours.

The scheduler. With 50,000+ feeds and next-fetch times, the scheduler is a priority queue keyed by next_fetch_at: a sorted set in Redis, a time-indexed table, or a timer wheel in memory, partitioned across scheduler instances by feed ID. Workers pull due feeds, fetch, update the estimate and reschedule. This is a small version of the problem in Design a Distributed Job Scheduler.

Politeness. We fetch from publishers' servers, so we must not harm them:

  • Respect robots.txt (now standardised as RFC 9309), cached per host for up to a day, and identify ourselves with a clear User-Agent and contact URL.
  • Per-host concurrency limits: at most a couple of simultaneous connections per host and a minimum delay between requests. A single scheduler shard owns each host so limits are enforced in one place.
  • Back off on errors: 429 and 503 with Retry-After must be honoured; repeated 5xx errors increase the interval exponentially.
  • Burst control: when a big story breaks, many feeds update at once; per-host limits still apply, so a publisher's 50 new live-blog updates are fetched at a polite pace.

Article fetching. Feed items give us a URL and a little metadata. For clustering and classification we need the full text, so an article fetcher downloads the page itself. It follows redirects (feeds often link through tracking redirects), records the final URL, and stores the raw HTML (compressed) in object storage for reprocessing if extraction logic improves.

Update handling. Articles change: headlines are rewritten, live blogs grow, corrections appear. Feeds may republish items with a new updated time. We re-fetch an article when its feed entry changes, and for live and breaking stories, re-fetch periodically for a few hours. The article's updated_at changes, and the story's representative headline can change too.

Failure isolation. Parsing untrusted XML and HTML from the internet is risky: malformed documents, enormous pages, decompression bombs, and XML entity expansion attacks. Fetchers enforce size limits (for example 10 MB per page), timeouts (for example 10 seconds), disable external entity resolution in XML parsers, and run parsing in isolated worker processes so that a poison document cannot take down the pipeline. Documents that fail repeatedly go to a dead-letter queue for inspection.

Throughput reality check. A few hundred feed fetches and a few dozen article fetches per second need perhaps 10–20 fetcher instances with asynchronous I/O, mostly waiting on the network. Ingestion is cheap. What matters is the latency from publication to visibility, and that depends on discovery (push or polling interval), queueing and processing, which Deep Dive 8 budgets end to end.

2. Extracting and normalising articles#

Main-content extraction. A news page contains the article plus navigation, ads, related links, comments and cookie banners. We want only the headline, body text, author, publication time and lead image. Sources of truth, in order of reliability:

  1. Structured data: schema.org NewsArticle in JSON-LD (headline, datePublished, dateModified, author, image), widely used by publishers because search engines reward it.
  2. Open Graph and Twitter card tags (og:title, og:image, article:published_time).
  3. Feed item fields (title, pubDate, description).
  4. Heuristic extraction of the main text block: algorithms in the family of Readability and boilerplate-removal research score DOM blocks by text density, link density and position, keeping the dense, low-link blocks.

When sources disagree (a feed says 09:00 and JSON-LD says 08:45), prefer structured data, but sanity-check: a publication time in the future or years in the past is a known publisher bug or manipulation tactic ("freshness spam", republishing old articles with new dates to rank higher). Cap how much an updated time can boost ranking.

URL normalisation and canonicalisation. The same article appears under many URLs: with tracking parameters (?utm_source=rss), AMP versions, mobile subdomains, trailing slashes, http versus https. Steps:

  • Use the page's <link rel="canonical"> when present and on the same site.
  • Strip known tracking parameters (utm_*, fbclid, gclid), lowercase the host, remove default ports and fragments.
  • Hash the normalised URL (url_hash) and enforce uniqueness: an article we already have is an update, not a new article.

Language detection. Feed metadata and HTML lang attributes are often missing or wrong. A fast character n-gram classifier (fastText-style language identification or Compact Language Detector) on the extracted text determines language reliably for anything over a sentence or two. Language decides which editions the article can appear in.

Text normalisation for downstream models. Unicode normalisation (NFC), whitespace and quote normalisation, removal of boilerplate sentences that publishers append to every article ("Sign up for our newsletter"). Per-source boilerplate can be learned automatically: sentences appearing in more than, say, 30 % of a source's articles are boilerplate.

Paywalls. Many publishers paywall content. They often provide full text to crawlers they trust, or only a teaser. We need enough text to cluster and classify, but we only display headline, a short snippet and a thumbnail, and we link readers to the publisher. Labelling paywalled articles ("Subscriber only") avoids frustrating readers.

Copyright and legal context. Aggregators sit in a contested legal area. In the EU, the 2019 copyright directive created a press publishers' right covering online use of news snippets, and Google stopped operating Google News in Spain from 2014 to 2022 after a Spanish law required payment for snippets. In practice, the design must support per-country and per-publisher display rules: headline only, no snippet, no thumbnail, or excluded entirely. Store these rules in the source registry and apply them at serving time, so changes take effect without reprocessing articles.

Output. The extractor emits a normalised article record (canonical URL, title, text, snippet, times, language, image URL, author, source) to the processing queue. Raw HTML stays in object storage so improvements to extraction can be re-run on recent articles.

3. De-duplication and clustering of similar stories#

Two different problems hide under "duplicates":

  • Duplicates: the same text in several places. A Reuters or AP wire story republished by 300 newspapers with small edits; the same article under different URLs; syndication networks. Readers should see it once.
  • Same story, different articles: fifty publishers each write their own article about the same event. Readers want them grouped into one story card with a choice of sources ("Full coverage"), not fifty cards.

We solve the first with fingerprints and the second with clustering.

Exact duplicates. A hash of the normalised URL catches URL variants; a hash (SHA-256) of the normalised body text catches identical content on different URLs. Both are O(1) lookups in a recent-hashes index.

Near-duplicates with SimHash. Moses Charikar's 2002 paper on similarity estimation from rounding algorithms introduced the technique now called SimHash, and Manku, Jain and Das Sarma's paper "Detecting Near-Duplicates for Web Crawling" (WWW 2007) described using 64-bit SimHash fingerprints at Google scale, treating documents whose fingerprints differ in at most 3 bits as near-duplicates. The idea:

simhash(text):
    v = [0] * 64
    for each feature f in shingles(text, k=3 words), with weight w (e.g. TF-IDF):
        h = hash64(f)
        for bit i in 0..63:
            v[i] += w if bit i of h is 1 else -w
    return bits where v[i] > 0          # 64-bit fingerprint
 
near_duplicate(a, b) = popcount(simhash(a) XOR simhash(b)) <= 3

Similar documents share most features, so most bit positions get the same sign, and their fingerprints differ in few bits. Finding all fingerprints within Hamming distance 3 of a new one, among millions, uses a neat trick from the same paper: split the 64 bits into blocks; any fingerprint within distance 3 must match exactly on at least some blocks (by the pigeonhole principle), so keep several tables each sorted or hashed on a different block permutation and probe each.

MinHash and LSH as an alternative. Andrei Broder's work on resemblance and containment of documents (1997) introduced MinHash: estimate the Jaccard similarity of two documents' shingle sets from the fraction of matching minimum hash values. Locality-sensitive hashing (LSH) groups MinHash signatures into bands so that similar documents collide in at least one band with high probability. MinHash estimates Jaccard similarity directly and is tunable (for example "flag pairs above 0.8 similarity"); SimHash is more compact (64 bits per document). Either works for wire-story detection. See Probabilistic Data Structures for Big Data.

What to do with duplicates. Keep them all as articles (each publisher deserves attribution, and readers may prefer a local outlet), but mark one as the original (earliest publication, or the wire service itself) and collapse the rest under it. In the story card, show the original or the most authoritative copy, and count duplicates once when scoring coverage, so 300 copies of one wire story do not look like 300 independent sources.

Clustering articles into stories. Here similarity is semantic, not textual: "Central bank raises rates by a quarter point" and "Interest rates up again as inflation persists" share few words but describe the same event. Signals:

  • Text embeddings from a sentence-embedding model (for example a multilingual transformer encoder), compared by cosine similarity. Multilingual models let a French and an English article about the same event cluster together if desired.
  • Named entities: people, organisations, places (extracted with a named-entity recogniser). Two articles both mentioning the same central bank, the same rate and the same day are very likely the same story.
  • Time proximity: same-event articles are published within hours of each other. A strong prior: only compare against clusters active in the last 24–72 hours.
  • Links and quotes: articles linking to the same source document or quoting the same sentence.

Online clustering. Articles arrive one at a time, and stories must update within minutes, so we cluster incrementally rather than re-running batch clustering:

assign_story(article):
    candidates = ann_search(article.embedding, index = recent_story_centroids,
                            k = 20, filter = language-compatible, active in last 72h)
    best, score = None, 0
    for story in candidates:
        s = 0.6 * cosine(article.embedding, story.centroid)
          + 0.3 * jaccard(article.entities, story.top_entities)
          + 0.1 * time_decay(article.published_at - story.last_updated)
        if s > score: best, score = story, s
    if score >= THRESHOLD:                     # tuned on labelled pairs, e.g. 0.75
        add article to best; update centroid (running mean) and top entities
    else:
        create new story with this article as its first member

The approximate-nearest-neighbour index (HNSW in a vector database or library such as FAISS) holds only recent story centroids (tens of thousands to a few hundred thousand vectors), so lookups take a few milliseconds. See Vector Databases and Similarity Search.

Fixing incremental mistakes. Online clustering makes greedy decisions. Two clusters about the same event can form in parallel (both started before either was indexed), or one cluster can drift to cover two related events ("earthquake" and "aftershock relief effort"). A periodic batch reconciliation job (every few minutes over the last day's articles) runs a better algorithm, such as agglomerative clustering on pairwise similarities or community detection on a similarity graph, then merges clusters that should be one and splits clusters with two dense sub-groups. Merges keep the older story ID (so links and cached cards remain valid) and redirect the absorbed ID.

Choosing the threshold. Too low: unrelated stories merge ("two different football matches"). Too high: the same event appears as several cards. Tune on human-labelled pairs and measure precision (articles in a cluster really belong together) and recall (articles about the same event end up together). For a news front page, merging mistakes are more visible and embarrassing than splits, so favour precision.

Representative headline and image. Each story needs a title: choose the headline of the most authoritative, recent, non-duplicate article, or the article closest to the cluster centroid. Do not generate headlines with a model by default: an invented headline that misstates facts is a serious trust failure. Choose the representative image similarly, preferring high-resolution images from reputable sources.

Story lifecycle. Stories have a natural life: they appear, grow as coverage builds, peak, then decay. Some develop for days (an election, a war), with sub-events. Long-running topics are better modelled as topics that contain many stories (Deep Dive 4), rather than one ever-growing cluster.

4. Categorisation, topics and locality#

Taxonomy. A small fixed set of top-level sections (World, Nation, Business, Technology, Entertainment, Sports, Science, Health) plus a deeper tree of topics (Sports → Football → Premier League → a specific club). Standards such as the IPTC Media Topics vocabulary, used across the news industry, are a good starting point and help map publishers' own categories.

Signals for categories.

  • Publisher hints: RSS <category> tags, section in the URL (/sport/, /business/), and which section feed the article came from. Cheap and fairly accurate, but inconsistent between publishers ("Lifestyle" versus "Life & Style" versus "Features").
  • Text classifier: a multi-label model over the article's text or embedding. Multi-label matters: a story about a football club's financial collapse is both Sports and Business.
  • Entities: an article mentioning a known footballer and a known club is very likely Sports.
  • Cluster-level voting: categorise the story, not just the article: if most of 40 articles in a cluster are Technology, the story is Technology even if one outlier article was filed under Business.

A practical approach: classify each article with a model that takes the text embedding plus publisher-hint features, then aggregate per cluster by confidence-weighted vote. Assign a story to every category whose aggregated confidence exceeds a threshold (for example 0.5), capped at two or three categories.

Locality. Local news is a large share of what people want ("news near me"):

  • Source location: a city newspaper's articles are local to its city by default.
  • Content geotagging: extract place names and resolve them to locations (disambiguating "Paris, France" from "Paris, Texas" by context and other entities), then attach the story to the matching places.
  • Edition relevance: a story can be relevant to several editions with different weights: a UK election story is top news in en-GB, important in en-US World, and minor in en-IN.

Stories are then indexed by (edition, category) and by (place) for local feeds. Local feeds are many (one per city or region), each with low traffic, so they are built on demand and cached briefly rather than precomputed every minute. See Geospatial Indexing and Proximity Search for location lookups.

Category feeds. Each category feed is just another precomputed feed key, such as en-GB:sports, built by the same feed builder from stories tagged with that category. This is the elegant consequence of the design: adding categories adds feed keys, not new systems. The cost grows linearly with the number of keys: 60 editions × 15 categories is 900 builds every minute, each cheap (scoring a few thousand candidate stories). Very fine-grained topics (individual clubs, companies) are built on demand when requested and cached for a few minutes.

Quality control. Classifiers make mistakes, and some mistakes are sensitive (a tragedy filed under Entertainment). Monitor category confidence, sample stories for human review, and allow editorial overrides for top stories in major editions (an override table the feed builder consults). Many aggregators combine algorithmic ranking with a small human editorial team for exactly this reason.

5. Ranking stories per edition and category#

The feed builder turns thousands of active stories into an ordered list for each feed key. There is no single correct formula, but good news ranking combines a handful of understandable signals.

Signals.

  • Freshness. News value decays quickly. Model it with an exponential decay with a half-life: freshness = 0.5 ^ (age_hours / half_life). A half-life of about 6 hours for Top Stories means a 12-hour-old story keeps 25% of its freshness weight. Sports scores may use 2–3 hours; long-form science stories 24 hours or more. Measure age from the story's last significant update (new articles arriving), not just its first appearance, so a developing story stays up.
  • Coverage (breadth). How many independent sources cover the story (duplicates and wire copies count once, Deep Dive 3). Twenty newsrooms independently reporting an event is strong evidence it matters. Use a log scale (log(1 + sources)) so 200 sources is not ten times better than 20.
  • Velocity. The rate of new coverage in the last hour versus the hour before. A story going from 2 to 40 articles in an hour is breaking. Velocity is what lets breaking news jump to the top within minutes (Deep Dive 8).
  • Source authority. A per-source score based on original reporting (how often the source is first, how often others cite it), editorial standards, corrections policy, and reader trust signals. Authority boosts stories covered by reputable outlets and picks which article represents a story.
  • Locality and relevance to the edition. Stories about the edition's country or region score higher in that edition (Deep Dive 4).
  • Engagement. Clicks and dwell time, corrected for position bias (stories at the top get more clicks simply because they are at the top; see Deep Dive 9). Engagement must be a modest weight: pure engagement ranking rewards sensational content.
  • Originality and quality. Prefer original reporting over aggregation, penalise clickbait headlines (a classifier) and sources with poor track records.

A simple, explainable formula.

score(story, edition) =
      (w_cov * log(1 + independent_sources)
     + w_vel * log(1 + articles_last_hour)
     + w_auth * mean_top3_authority
     + w_loc * locality(story, edition)
     + w_eng * debiased_ctr(story, edition))
    * 0.5 ^ (hours_since_last_update / half_life(category))

Hacker News's well-known ranking divides points by a power of age, (points − 1) / (age + 2)^1.8; Reddit's "hot" algorithm adds a logarithm of votes to a linear term in time. Both express the same idea: importance grows slowly with evidence and decays steadily with time. Exponential decay with a half-life is easier to tune per category. As the system matures, replace hand weights with a learning-to-rank model (gradient-boosted trees such as LambdaMART) trained on debiased engagement and human quality ratings, but keep the hand formula as a fallback and as an interpretable baseline.

Diversity and constraints after scoring. A purely score-sorted list can look terrible: five stories about the same election in the top six, or three stories in a row from one publisher. The builder applies re-ranking rules:

  • At most one story per topic in the top N positions (sub-stories of the same event collapse or spread out).
  • At most K stories per source as representative article in the top 20 (spread attribution).
  • A mix of categories in Top Stories (not all politics).
  • Pinned stories from editorial overrides (Deep Dive 4).

A greedy pass does this well: walk the score-sorted list and take the next story unless it violates a constraint, in which case defer it a few positions. Maximal marginal relevance (MMR, Carbonell and Goldstein, SIGIR 1998) formalises the same idea: each pick maximises λ × relevance − (1 − λ) × similarity to already picked items.

The feed builder job.

Builds are cheap: scoring 5,000 candidates with a formula takes milliseconds; 1,000 feed keys take a few seconds on one worker, so the whole set can be rebuilt every minute with plenty of headroom. Scores and features for each story are precomputed by the story-scoring stream job; the feed builder only combines them per edition.

6. Infinite scroll and consistent pagination#

Readers scroll; the client asks for the next 20 stories. Meanwhile the feed is rebuilt every minute, and the ranking changes. Naïve pagination breaks in visible ways.

Why offset pagination fails here. GET /feed?offset=20&limit=20 returns positions 20–39 of the current ranking. If three new stories were inserted at the top since the reader loaded page 1, the old positions 17–19 are now 20–22: the reader sees three stories again. If stories moved up, the reader skips some. On a fast-changing news feed this happens on almost every scroll during busy times.

Why a score cursor also fails. For a static data set, keyset pagination ("give me items with (score, id) less than the last one I saw") is the right answer (see API Design Best Practices). But news scores are not stable: they decay with time and jump with velocity. A story the reader has not seen yet can rise above the cursor and be skipped forever, and a seen story can fall below the cursor and appear again.

The fix: versioned feed snapshots. Every build produces an immutable snapshot with a version number. The first page returns feedVersion and a cursor encoding (version, offset). Later pages read the same snapshot at the next offset. Because the snapshot never changes, offsets are perfectly consistent: no duplicates, no skips.

GET /v1/feed?edition=en-GB&category=top               → version 1733200060, items 0..19, cursor = enc(v=1733200060, o=20)
GET /v1/feed?edition=en-GB&category=top&cursor=...    → server decodes v and o
    snapshot = cache.get("feed:en-GB:top:v1733200060")
    if snapshot exists: return snapshot[o : o+20], cursor = enc(v, o+20)
    else:               fall back (below)

Retention. Readers rarely scroll for more than 10–20 minutes. Keep the last 30–60 minutes of snapshots per key: 60 versions × 1,000 keys × 200 KB (1,000 story IDs plus small metadata) ≈ 12 GB in Redis, cheaper still if consecutive snapshots are stored as deltas. Story details (headline, thumbnail, sources) are fetched by ID from a story cache, so they can update (a corrected headline) without changing the snapshot.

Expired snapshots. If the reader returns to a tab after two hours and scrolls, the snapshot is gone. Options: serve the current snapshot from roughly the same position and ask the client to dedupe; or tell the client to refresh ("New stories available, tap to update"). The client already keeps the set of story IDs it has shown and filters duplicates as a safety net.

New stories while reading. The client can poll a cheap endpoint (or receive a push) with the latest feed version every minute or two. If newer, show a "New stories" pill at the top; tapping it reloads page 1 from the new version. This mirrors how social feeds handle new posts without disturbing the reader's position. See Polling, Long Polling, SSE, WebSockets and Webhooks.

Cacheability. With versions in the cursor, a page URL like /v1/feed?edition=en-GB&category=top&cursor=enc(v,40) names immutable content: it can be cached at the CDN for a long time (max-age of the snapshot's retention). Page 1 (no cursor) is the only mutable URL, cached for 30 seconds. This makes deep pages almost free.

Efficiency. Avoid sending all 1,000 IDs to the client up front (wasted bytes on mobile) and avoid recomputing anything per page. The server work per page is: decode cursor, slice a cached list, multi-get 20 story cards (cached), serialise. Typical server time is 2–5 ms.

7. Serving the feed under 200 ms: scaling reads#

The feed API is a textbook read-heavy system: about 1,000 reads per write, and most reads ask for the same few hundred objects (page 1 of each popular edition). The standard progression for scaling reads applies, in order, and it is worth walking through it in an interview because each step answers "why not just…?". See Pattern: Scaling Reads.

Step 1: optimise the database. If feeds were computed per request with SQL ("stories in edition X, category Y, last 72 hours, order by score"), you would need an index on (edition, category, score DESC) and the query would still sort thousands of rows per request. Good indexing, enough memory for the working set, and denormalising the story card (headline, thumbnail, source name copied into the story row) can make this fast for thousands of requests per second. Physical limits hit soon: a well-tuned relational node serves perhaps 10,000–50,000 simple indexed reads per second. We need 300,000 at peak, and requests concentrate on the same rows. Database optimisation is necessary for the builders, but it is not how readers are served. See Database Performance and SQL Tuning.

Step 2: scale horizontally. Read replicas multiply read throughput (each replica serves a share) at the cost of replication lag of milliseconds to seconds, which news can tolerate. Sharding by edition spreads data, but it does not help a hot key: everyone reading en-US Top Stories hits the same shard. See Database Replication.

Step 3: precompute and cache. The decisive step: the feed builder already computes each feed; store the result as a ready-to-serve snapshot in Redis, and story cards as separate keys. A feed request becomes two Redis operations (read the version pointer, read a slice) plus a multi-get of 20 cards, about 1 ms of Redis time. A Redis node handles around 100,000+ simple operations per second; a small cluster with replicas handles the load with room to spare. See Distributed Caching with Redis and Memcached.

Step 4: in-process cache. Each API server keeps the current snapshot for popular keys in local memory (a few MB) with a 5–10 second TTL. This removes Redis round trips for 95% of requests and protects Redis from hot keys.

Step 5: CDN and edge. Non-personalised feed responses are identical for every reader of an edition, so the CDN caches them. With a 30-second max-age, each CDN point of presence asks the origin for page 1 of en-US Top Stories at most twice a minute, no matter how many millions of readers ask. CDN hit ratios of 95–99% are realistic for this traffic. The origin then sees thousands, not hundreds of thousands, of requests per second. See Content Delivery Networks (CDN).

The latency budget for under 200 ms (p99 at the client, excluding the device's rendering):

StepCDN hitCDN miss
DNS + TCP/TLS (connection reused after first request)0–40 ms0–40 ms
Client to edge round trip10–40 ms10–40 ms
Edge to origin region—20–80 ms
API server: cursor decode, local or Redis reads, serialise—2–10 ms
Response transfer (~10–20 KB compressed JSON)5–20 ms5–20 ms
Total~20–100 ms~40–190 ms

Images are loaded after the JSON, lazily, and do not count toward the feed latency target.

The common read-scaling problems, and their answers here.

  • Queries slowing as data grows. The builder only queries the last 72 hours of stories, via a time-partitioned table or a dedicated "active stories" store, so its working set stays constant as the archive grows. Old articles move to cheaper storage (see Data Lifecycle, Tiering and Retention).
  • Millions of reads of the same key. The CDN and in-process caches absorb hot keys; Redis keys can be replicated (read from replicas, or write the same snapshot to several key names like feed:en-US:top:v123:{0..7} and choose one at random).
  • Cache stampede. When page 1 of a popular feed expires at the CDN, many requests can miss at once. stale-while-revalidate lets the CDN keep serving the old copy while one request refreshes it; CDN request collapsing (coalescing) merges simultaneous misses into one origin fetch; at the origin, a single-flight lock per key does the same. Because snapshots are pushed by the builder rather than computed on a miss, a miss at the origin never triggers expensive recomputation anyway. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
  • Invalidation for updates that must be visible immediately. Most feed changes tolerate 30–60 seconds of staleness. Two kinds do not: takedowns (a legal removal, a story that turned out to be false, a source blocked for spreading misinformation) and major corrections to a headline. For these, the builder publishes a new version immediately and calls the CDN's purge API for page 1 of affected keys (purges propagate globally in seconds on modern CDNs); story cards carry a short TTL and are purged by ID; and the API filters removed story IDs against a small blocklist on every request, so even a stale cached snapshot never shows removed content from the origin.

Why not compute feeds per request? It would let every request be personalised and perfectly fresh, but it costs a sort over thousands of candidates per request at 300,000 requests per second, and it throws away the main property of this workload: the answer is shared. Shared precomputation plus caching is the right default; personalisation is layered on top (Deep Dive 12).

8. Freshness: from publication to feed within 30 minutes#

The requirement: a new article should appear in the relevant feeds within 30 minutes of publication, and big breaking stories much faster. Treat it as a latency budget across the pipeline:

StageTypicalWorst case allowed
Discovery (WebSub push, or polling interval for the source)seconds (push) to 1–5 min (poll)15 min for low-priority sources
Queue wait before fetchunder 5 s1–2 min under backlog
Fetch and extract article1–3 s30 s with retries
Dedupe and clusteringunder 1 s10 s
Categorise and score (stream job)seconds1 min
Next feed build0–60 s60 s
CDN cache expiry for page 10–30 s30 s plus stale window
End to end~2–8 min~20 min

Where the time goes, and how to cut it.

  • Discovery dominates. Polling interval is the largest term. Use WebSub push where publishers support it, adapt polling to each source's posting rate (Deep Dive 1), and give important sources short intervals. Monitoring discovery lag per source (article's published_time versus when we first saw it) shows which sources need more frequent polling.
  • Priority queues. Separate queues (or Kafka topics with separate consumer pools) for high-priority sources and for re-fetches of updated articles, so a flood of low-value updates cannot delay a major outlet's breaking story. See Asynchronous Processing and Message Queues.
  • Event-driven builds. Besides the regular 60-second schedule, the scoring job emits a "velocity spike" event when a story's coverage jumps; the builder rebuilds affected feeds immediately and purges page 1 at the CDN.
  • Streaming, not batch. All processing between fetch and feed build is streaming (Kafka plus stream workers or Flink). Batch jobs exist only for reconciliation (cluster merges, model retraining).

Measuring it. Freshness needs its own metric, not just "the pipeline is up": for a sample of articles, record publication time, discovery time, ingestion time, clustering time, and first time present in a served feed. Track the distribution per stage and per source tier, and alert on the p95 time-to-feed. A synthetic "canary publisher" that you control, publishing a test article every few minutes into a hidden test edition, gives a direct end-to-end probe. See Observability: Logs, Metrics and Traces.

Publisher timestamps lie sometimes. Some sites put a future date or update the timestamp without changes to look fresh. Use our own first-seen time as a bound: effective_published = min(claimed_published, first_seen) within reason, and ignore "updated" times without a meaningful content change (content hash unchanged).

The third functional requirement is that clicking a story takes the reader to the publisher's site. That sounds trivial, but it is where the aggregator learns what readers find useful, and it has a latency and privacy cost.

Option A: redirect through our server. The link is https://news.example/r/{articleId}?f=en-GB:top&p=3. Our redirect service logs the click (article, feed, position, session, time) to Kafka and returns 302 Location: <publisher URL>.

  • Pros: reliable, complete click logging (works without JavaScript, can't be blocked without breaking the link); lets us update destination URLs centrally (canonical changes, AMP versus non-AMP); a single place to add safety checks (a source that turned malicious can be blocked instantly).
  • Cons: an extra round trip before the publisher page starts loading, typically 20–80 ms at the edge; the redirect service is now on the critical path and must be highly available; privacy concerns about tracking each click.

Option B: direct link plus beacon. The link points straight at the publisher; the client calls navigator.sendBeacon("/v1/clicks", payload) or uses the HTML ping attribute when the link is clicked. The beacon is sent asynchronously and does not delay navigation.

  • Pros: zero added latency; the publisher URL is visible to the user (trust) and to the browser (prefetching, security indicators).
  • Cons: some clicks are lost (ad and tracker blockers, browsers that disable ping, app crashes); lists of URLs must be kept fresh in cached feeds.

Choice: native apps can use direct links with a reliable in-app click log (the app controls the network), and the web can use direct links with a beacon. Keep a redirect endpoint for shared links, email digests and clients that cannot beacon. Make the redirect service tiny and edge-deployed: a lookup of articleId → URL from a cache, a fire-and-forget log write, and a 302. If logging fails, redirect anyway; a lost click event is acceptable, a broken link is not.

Using click data correctly.

  • Position bias. Stories in position 1 get many times the clicks of position 10 regardless of quality. Raw click-through rate (CTR) is therefore a biased signal. Estimate a per-position examination probability (from experiments that occasionally shuffle positions slightly, or from models like the position-based click model) and use debiased CTR = clicks / expected clicks at the positions where the story was shown.
  • Dwell time. A click followed by a quick return to the feed suggests the headline promised more than the article delivered (clickbait). Apps can measure return time; web beacons can use visibilitychange events. Long dwell is a better quality signal than clicks alone.
  • Bots and fraud. Click signals invite manipulation (publishers inflating their own stories). Filter by rate limits per client, known bot signatures, and anomaly detection on sudden click bursts from narrow sources. See Rate Limiting and Throttling.
  • Aggregation. Click events flow through Kafka into a stream job that maintains per-story, per-edition counters over sliding windows (last 15 minutes, last hour), feeding the ranking signals; and into the data lake for offline analysis and model training. See Pub/Sub and Event Streaming.

Publisher relationship. Click-through is the value the aggregator gives publishers: referral traffic. Measure and report it (publisher dashboards), and never wrap or frame publisher pages in a way that strips their ads or analytics without agreement. Some regions now regulate this relationship (Deep Dive 2).

10. Media: thumbnails, images and video#

Each story card has a thumbnail; the full-coverage page shows larger images; some stories have video. At 200,000 image requests per second, media is the largest share of bytes served, even though it is the simplest part conceptually. See Pattern: Handling Large Files and Blobs.

Picking the image. Use the article's declared image (og:image, JSON-LD image, or media:content in RSS). Reject images that are too small (under about 400 px wide), logos, tracking pixels and generic placeholders (detect via perceptual hash matching against known placeholders per source). For a story, prefer a high-quality image from an authoritative article, avoiding repeated use of the same stock photo across different stories.

Never hotlink. Loading images directly from publisher servers would hand them our traffic spikes (a breaking story could send millions of image requests to a small local newspaper), leak readers' IPs to every publisher on the page, and break when publishers change URLs. Instead the media service fetches once, stores, and serves from our CDN:

  1. On ingest, enqueue an image job: fetch the image URL (respecting robots rules and timeouts), verify it is a real image (decode it; reject over-size files and decompression bombs).
  2. Compute a perceptual hash (to dedupe identical images across wire copies) and a content hash (the storage key).
  3. Generate renditions: for example 120 px, 360 px and 720 px wide; encode as AVIF and WebP with JPEG fallback. AVIF typically saves around 30–50% over JPEG at similar quality.
  4. Store renditions in object storage under the content hash: img/{hash}/{width}.{format}. Content-addressed keys are immutable, so they are cached with max-age=1 year, immutable.
  5. The story card's thumbnailUrl is a CDN URL; the client picks the rendition with srcset and the format with the Accept header (or explicit format in the URL).

Storage is modest (100 GB a day per the estimate) and can expire images of old stories after a year, keeping only thumbnails for the archive. See Object Storage and Blob Storage.

On-the-fly resizing at the edge (an image CDN or edge function that resizes on request and caches the result) is the alternative: fewer stored renditions and flexible sizes, but the first request for each size pays the resize cost, and resize workers must be protected from cache-miss storms. Precomputing three sizes is simpler for a fixed set of layouts.

Copyright and licensing. Showing publisher thumbnails is a licensing question in some jurisdictions; some publishers opt out via max-image-preview robots directives (max-image-preview:none or standard versus large). Respect those directives per source, falling back to a text-only card or a generic category image.

Video. Do not host or transcode publisher videos; that is their content. Embed their player (YouTube or the publisher's own) on the full coverage page, using lazy loading with a static poster image (our own thumbnail) and loading the player only when the reader taps. Autoplaying many embedded players would destroy page performance.

Client performance. Lazy-load images below the fold; reserve their space (fixed aspect ratio) so the layout does not jump; use a tiny blurred placeholder or the dominant colour while loading. On slow networks, the app can request smaller renditions (Save-Data header or the app's own network quality estimate). See Client, Mobile and Frontend Considerations.

11. Breaking-news traffic spikes and availability#

When a major event breaks (an election result, a disaster, a celebrity death), traffic can jump 5–10× within minutes, concentrated on one story and page 1 of a few editions. At the same moment, ingestion floods: hundreds of publishers post and update articles about the same event. The system must stay up and fresh precisely when it matters most.

Why the design already absorbs most of it. The surge is for shared, cacheable content. If the CDN hit ratio stays at 98%, a jump from 30,000 to 300,000 requests per second adds only about 5,000 requests per second at the origin. The risk is not average load; it is cache misses at the worst moment:

  • The breaking story triggers an event-driven rebuild and a purge of page 1 (Deep Dive 8). Every CDN point of presence then misses at once: hundreds of edge nodes each sending a request to the origin. Request collapsing at the CDN and a CDN origin shield (a mid-tier cache that all edges ask first) reduce that to a handful of origin requests per key.
  • The full-coverage page of the breaking story (/v1/stories/{id}) suddenly becomes the hottest key. Its card updates every minute as articles arrive. Cache it for 15–30 seconds with stale-while-revalidate, precompute it in the story job, and serve from in-process caches at the API tier.
  • Clients retrying on slow responses multiply load. Clients use exponential backoff with jitter; the server returns cached or slightly stale data rather than errors. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

Prefer staleness over failure. The NFR said availability beats consistency: a feed 2 minutes stale is fine, an error page is not. Concretely:

  • CDN: stale-if-error=600 serves the last good copy for 10 minutes if the origin fails.
  • API: if Redis is slow, serve the in-process copy, even if it is older than its TTL.
  • Builder: if the builder fails, the last snapshot simply stays current (the version pointer is not moved); readers see a slightly older feed, and an alert fires.
  • Ingestion: if ingestion lags, the feed is less fresh but fully available.

Load shedding and graceful degradation. Define what to drop first when overloaded:

  1. Personalised re-ranking (fall back to the edition feed, Deep Dive 12).
  2. Non-essential widgets (weather, "more on this topic").
  3. Deep-page snapshot reads for expired versions (return "please refresh").
  4. Low-priority ingestion (re-fetch of old article updates, low-tier sources), so breaking-story articles flow quickly.

Feature flags controlled at runtime let operators switch these off in seconds.

Ingestion surge. Hundreds of publishers updating live blogs every minute can multiply fetch load. Priority queues protect top sources; per-source caps stop one live blog consuming the pipeline; clustering handles the burst because each new article only does an ANN lookup among recent stories. Kafka absorbs bursts in its log so stream workers can catch up rather than drop work.

Autoscaling and pre-warming. API servers and redirect services are stateless and autoscale on CPU and request rate, but autoscaling takes minutes, and breaking news arrives in seconds. Keep headroom (run at about 40–50% of capacity), and pre-scale for scheduled big events (elections, major sports finals, product launches). Load-test the full path (CDN miss storms included) before big events. See Capacity Planning and Load Testing.

Multi-region. Run the serving tier (API, Redis caches, redirect) in several regions, each with a full copy of all snapshots (they are small, so replicate them everywhere via a pub/sub fan-out from the builder). The CDN routes each reader to the nearest healthy origin. Ingestion and processing can run active-passive in two regions: a processing outage only reduces freshness, it does not take the product down. The archive database replicates asynchronously across regions. See Multi-Region and Global Data and Designing for High Availability.

12. Personalised feeds#

The core design serves shared feeds. Many readers also want "For you": stories matching their interests, local area and favourite sources. This is an extension, but a common follow-up question.

Historical note. Das, Datar, Garg and Rajaram's paper "Google News Personalization: Scalable Online Collaborative Filtering" (WWW 2007) described recommending stories from users' click histories by combining MinHash clustering of users, probabilistic latent semantic indexing, and item co-visitation counts, computed with MapReduce. The key challenges it addressed remain the core of the problem: items (stories) are short-lived and constantly new, so classic collaborative filtering that needs many ratings per item struggles; and the system must scale to millions of users.

Signals for interests.

  • Explicit: followed topics, sources and places; "show fewer stories like this"; hidden sources.
  • Implicit: clicks and dwell time (debiased), categories and entities of read stories, time of day patterns.
  • Context: location (for local news, with consent), language, device.

Build a user interest profile: decayed weights over topics, entities and sources, for example "Football 0.8, Premier League club X 0.9, Technology 0.5, source Y 0.3", updated by a stream job when clicks arrive. Stories have the same representation (categories, entities, embedding), so matching is a dot product or a weighted overlap. An alternative is a user embedding (mean of embeddings of recently read stories, or a learned two-tower model) compared with story embeddings by cosine similarity. See ML System Design and Feature Stores.

Two-stage serving: candidates, then re-rank. Never score every story for every user. Instead:

  1. Candidate generation from cheap, shared sources: the user's edition Top Stories feed (already built), category feeds for their strongest interests, followed topic and local feeds, and stories co-visited by similar readers. A few hundred candidates total, all already scored for global importance.
  2. Re-rank per user: final = α × global_score + β × interest_match + γ × source_preference, then apply the same diversity rules as Deep Dive 5, plus a quota of top global stories so the reader never misses major news because of their interests.

The re-rank of a few hundred candidates takes a few milliseconds, so it can run on request. Cache the resulting personal feed per user for a few minutes (in Redis, keyed by user ID and edition) and treat it as a snapshot for pagination exactly like shared feeds. Responses are Cache-Control: private and never cached by the CDN.

Cost. Personalisation moves work from "one feed per edition" to "one feed per active user". At 100 million users with a 5-minute cache, about 10,000 personalised builds per second at peak would be needed for active sessions only. Each build is cheap, but this is the first thing to drop under load (Deep Dive 11): fall back to the shared edition feed.

Cold start. New users have no history: start from the edition feed plus location-based local news, ask for a few topics at onboarding, and learn quickly from the first few clicks (higher learning rate for new profiles). New stories have no clicks: content features (categories, entities, embedding) let a brand-new story match interested users immediately, which collaborative filtering alone cannot do.

Filter bubbles and editorial responsibility. Pure interest-matching narrows what people see. A news product has reasons to show important stories regardless of interest, and to show different perspectives on contested stories. Keep top global stories in every personal feed, use the full-coverage page to show sources from across the spectrum, and measure diversity (topics and sources per user per week) as a health metric, not only engagement.

Privacy. Reading history is sensitive (it can reveal political views, health concerns, religion). Let users view and delete their history, pause personalisation, and use the product signed out with no profile. Keep raw click logs with limited retention, and avoid inferring sensitive categories for targeting. See Security Fundamentals for System Design.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Breaking news purge causes a CDN miss stormOrigin overloaded at the worst moment; slow or failed page 1Origin shield, request collapsing, stale-while-revalidate, single-flight per key, pushed snapshots so misses never recompute
Hot key: page 1 of a major edition in RedisOne Redis shard saturatedIn-process cache with 5–10 s TTL, replicate the key under several names, read from replicas
Feed builder crashes or produces a bad snapshotStale feed, or broken ordering for millionsKeep the previous version pointer until the new snapshot validates (size, diversity, no blocked IDs); instant rollback by moving the pointer back
Publisher feed broken or malformedMissed articles from that sourceParser isolation per source, fallback to sitemap or homepage crawl, alert on sources with zero new articles versus their normal rate
Polling falls behind (scheduler backlog)Freshness SLO missedPriority tiers, autoscaling fetchers, WebSub push, discovery-lag metric per source
Wire story republished 300 timesCoverage counts inflated; feed full of duplicatesContent hash plus SimHash collapse; count independent sources only
Clustering merges two different eventsWrong articles under a headline; trust damageConservative threshold, entity checks, periodic split job, human review for top stories
Clustering splits one event into many cardsRepetitive feedPeriodic merge job; diversity rule of one story per topic in the top N
Snapshot expired during a long scrollDuplicates or skips on deep pages30–60 min retention, fallback to current version with client-side dedupe by story ID, "refresh" prompt
Click redirect service slow or downClicks fail to reach publishersEdge-deployed redirect, fire-and-forget logging, direct links plus beacon in apps, fallback to direct URL
Image fetch overloads small publishers or failsMissing thumbnails; publisher complaintsFetch once and store, per-host rate limits, text-only card fallback
Spam or misinformation source games rankingLow-quality or false stories at the topSource authority, freshness-spam detection, takedown blocklist checked on every request, editorial override

What Interviewers Expect#

Mid-level. Cover the three functional requirements: an aggregated feed by region and category, infinite scroll, and click-through to publishers. Explain ingestion by polling RSS feeds, storing articles in a database, and serving feeds through an API with a cache. Know that the system is read-heavy and that a CDN helps, and that offset pagination has problems on a changing list. Estimate the read QPS roughly.

Senior. Make the key insight early: feeds are shared per edition and category, so precompute them and serve them from caches and the CDN; the read-to-write ratio is about 1,000:1. Explain ingestion as a scheduled, polite, adaptive crawler with conditional GETs and WebSub. Describe de-duplication (hashes and SimHash) and clustering of articles into stories. Propose versioned snapshots for consistent pagination. Give a ranking formula with freshness decay, coverage and authority, plus diversity. Walk through the freshness budget to meet the 30-minute requirement, and the stale-if-error and degradation plan for breaking-news spikes.

Staff and above. Treat freshness and quality as first-class SLOs with measurement (canary publisher, per-stage time-to-feed). Discuss the precision versus recall trade-off in clustering and how mistakes are detected and repaired (merge and split, stable IDs). Debias click signals for position, guard against manipulation, and argue why engagement must not dominate news ranking. Explain the CDN purge and blocklist strategy for takedowns, multi-region serving with replicated snapshots, and graceful degradation order. Cover personalisation as a two-stage candidate-plus-re-rank layer on shared feeds, with cost estimates, cold start, filter-bubble mitigation and privacy. Raise the publisher relationship and legal context (licensing, snippet rules) as product constraints that shape the architecture.

Deep Dive: Source quality, trust and misinformationShow

A news aggregator is judged less on its latency than on whether its top stories are true and important. Several mechanisms work together.

Source authority as a slowly changing score. Authority should be earned over months, not minutes. Inputs that can be measured without inventing facts about any outlet:

  • Originality: how often the source is the first to report a story that later gets broad coverage (from our own clustering timestamps), and how often other outlets link to or cite it.
  • Editorial transparency: whether the site publishes bylines, a corrections policy, contact details, ownership information. These can be checked by crawling "About" pages and structured data, then verified by human raters for important sources.
  • Track record: how often its stories are later contradicted, corrected or taken down; human quality ratings on samples.
  • Behavioural red flags: freshness spam (re-dating old articles), keyword stuffing, plagiarism (SimHash matches to earlier articles from other sources), heavy clickbait headline scores.

Combine these into a score per source and per (source, topic): a respected sports outlet is not automatically authoritative on medicine. Authority influences ranking and which article represents a story, but no single score should be able to push a story to the top alone; coverage breadth from independent sources is the main signal of importance.

Breaking-news uncertainty. In the first hour of an event, early reports are often wrong (casualty numbers, suspect identities). Ranking that rewards velocity can surface those errors at the top. Mitigations: when a story is very young and its velocity is high, prefer articles from high-authority sources as the representative, label the story as "developing", and avoid pulling details from low-authority sources into the headline. Some aggregators show fact-check articles alongside stories when they exist; the schema.org ClaimReview markup that fact-checkers publish makes those articles machine-detectable.

Coordinated manipulation. Networks of low-quality sites can publish the same story to fake broad coverage. Defences: count independent sources (SimHash and shared ownership collapse networks into one), weight coverage by authority, and watch for sudden bursts of new sources all covering one story.

Takedowns and legal requests. Legal removal orders (court orders, data-protection right-to-be-forgotten requests in some jurisdictions), publisher withdrawals, and policy removals must propagate fast. The path: a removal service writes the article or story ID to a blocklist (replicated to every API server's memory within seconds), triggers a feed rebuild excluding it, and purges CDN entries for page 1 of affected feeds and the story page. Because every API response filters against the blocklist, even cached snapshots never resurface removed items from the origin; CDN purges handle the edge. Keep an audit log of removals with reasons.

Human oversight. Fully algorithmic news front pages are rare among major products; many combine algorithmic ranking with editorial teams for top stories or sensitive events. Design for that: an editorial console that can pin, demote or block stories per edition, with changes taking effect in the next build (under a minute) and recorded for accountability.

Measuring quality. Engagement metrics are not enough. Use human rater programmes with written guidelines (is this the most important story? is the headline accurate? is the source reputable?) and track rated quality of top positions per edition as a key metric, alongside freshness and latency SLOs.

Deep Dive: How real news products differShow

The same core problem has been solved in different ways. Only well-documented facts are given here; details of each company's internals are not public.

  • Google News launched in 2002 (developed by Krishna Bharat) as an algorithmic aggregator that clusters stories from thousands of sources. Its 2007 personalisation paper (Das et al.) is one of the few detailed public descriptions of an aggregator's recommendation system. It shows headlines and snippets and sends readers to the publishers' sites.
  • Apple News combines algorithmic selection with a human editorial team that curates top stories, and offers a paid subscription tier with publisher content inside the app.
  • Social feeds that carry news (for example Facebook's News Feed in earlier years) rank posts mainly by engagement within a social graph, a very different objective from importance and breadth of coverage. Concerns about engagement-driven ranking amplifying low-quality news are part of why dedicated news products emphasise authority and editorial oversight.
  • Community aggregators like Hacker News and Reddit rank user-submitted links by votes with time decay, and do not cluster duplicates the way a news aggregator does. Their simple, public ranking formulas are useful teaching examples for freshness decay.
  • RSS readers (for example Feedly) let users choose sources and show everything chronologically, with optional filtering and ranking on top. They have the same ingestion problem (polling many feeds efficiently, often sharing fetches across all subscribers of a feed) but much less ranking.

Design implications. If the product is a reader that shows only chosen sources, ingestion and per-user fan-out dominate. If it is an algorithmic front page, clustering, ranking and quality dominate, and feeds are shared. If it is a social news product, the graph and engagement signals dominate. Asking which one the interviewer means is one of the most useful clarifying questions.

Deep Dive: Sizing every tier with worked numbersShow

Rough sizing helps check that the design hangs together. All figures are design assumptions, consistent with the Capacity Estimation section.

CDN. Peak 300,000 feed requests per second at about 15 KB each (compressed JSON) is about 4.5 GB/s, or 36 Gbit/s, plus images: 200,000 per second average and perhaps 1 million per second at peak, at about 20 KB each for small thumbnails, which is 20 GB/s or 160 Gbit/s at peak. That is normal traffic for a major commercial CDN spread over hundreds of points of presence, and it is why images must never come from origin.

Origin feed API. With a 98% CDN hit ratio at peak, the origin sees 6,000 requests per second, plus deep-page and personalised requests that miss more often, say 20,000 per second in total. A stateless API server doing cache reads and JSON serialisation handles several thousand requests per second per core-heavy instance; 10–20 instances per region with 2× headroom is enough. Without the CDN it would be 300,000 per second and hundreds of instances, which shows the CDN's value in one number.

Redis. Snapshots: 1,000 shared feed keys × 60 retained versions × 200 KB ≈ 12 GB; topic and local feeds add a few GB more. Story cards: 300,000 active stories × 2 KB ≈ 600 MB. Personal feeds: 10 million concurrently active users × 20 KB ≈ 200 GB if fully materialised, which is the main reason to cache personal feeds briefly and only for active sessions. A cluster of 6–12 shards with replicas per region covers this; operations are at most tens of thousands per second because in-process caches absorb most reads.

Ingestion fetchers. About 200 feed fetches per second plus about 25 article fetches per second plus image fetches (about 12 per second). Each fetch waits on remote servers for 100 ms to several seconds, so concurrency matters more than CPU: with async I/O, a handful of fetcher instances each with a few hundred concurrent connections is enough. Extraction (HTML parsing) costs perhaps 20–100 ms of CPU per article: 25 per second × 100 ms = 2.5 cores. Cheap.

Kafka. Article events: about 25 per second × 20 KB ≈ 0.5 MB/s. Click events: 7,000 per second average, 50,000 at peak, × 300 bytes ≈ 15 MB/s at peak. Small for Kafka: a 3–6 broker cluster with replication factor 3 and 7-day retention (a few TB) is plenty. See Apache Kafka in Practice.

Clustering and embeddings. Computing an embedding for each article with a small transformer encoder on a GPU takes a few milliseconds per article in batches; 25 per second is a fraction of one GPU, or a few CPU cores with a distilled model. ANN lookups over about 300,000 recent story centroids with HNSW take 1–5 ms each.

Feed builders. 1,000 shared keys × 5,000 candidates × a few microseconds per score ≈ 15–25 s of CPU per full rebuild; done every 60 s, that is under one core continuously. Several workers give redundancy and speed (all keys rebuilt within 5 s).

Storage. Metadata and text: 25 GB a day, 9 TB a year in the article store (sharded relational database or a wide-column store), plus search indexes of similar size. Thumbnails: 36 TB a year in object storage. Click logs in the data lake: 600 million events a day × 300 bytes ≈ 180 GB a day raw, about 30–50 GB compressed in columnar format.

What this tells us. Every tier except the CDN is small. The design's difficulty is not raw scale but freshness, quality and spikes: the interviewer will spend time on those, and the estimate shows why.

Deep Dive: Archive, search and the story pageShow

Feeds use the last 72 hours, but readers also search ("articles about the city budget last March") and follow topics over time. This is a different workload from the feed: low QPS, large data, full-text queries.

Search index. Index articles in a search engine such as Elasticsearch or OpenSearch: title, snippet, extracted text (for matching, not for display), source, publication time, language, categories, entities, cluster ID. Partition indices by time (one index per week or month) so old indices can be merged, moved to cheaper nodes, made read-only, and eventually deleted or shrunk. Queries typically combine full-text relevance with recency boosting (BM25 score multiplied by a time decay) and filters for language and edition. Group results by cluster ID so one event does not fill the first page. See Elasticsearch and Search Systems.

Indexing path. The same article events that feed clustering also feed an indexer consumer, which writes to the search engine in bulk batches every few seconds. Search freshness of under a minute is easy to achieve. Corrections and takedowns update or delete the document by article ID.

The story page (full coverage). For a story, show all member articles grouped: top coverage from authoritative sources, local coverage, opinion pieces, fact checks, a timeline of the event's development, and related stories. Precompute it in the story job and cache it like a feed, with a short TTL while the story is active and a long TTL once it goes quiet. The article list for a story can be thousands long for huge events, so paginate it with the same snapshot idea.

Topic pages. Long-running topics (a war, an election campaign, climate change) are built from entities and categories: stories whose top entities include the topic's entity. Topic feeds use the same builder, with a longer freshness half-life because readers expect a history.

Retention. Keep article metadata indefinitely (it is small and supports search and history), but drop extracted full text after some months unless licensing permits keeping it, and age images out of hot storage. Archived click logs feed model training under a defined retention period. See Data Lifecycle, Tiering and Retention.

Deep Dive: Languages, editions and cross-lingual storiesShow

Editions are product decisions. An edition combines a region and a language (en-US, en-GB, en-IN, fr-FR, fr-CA, es-MX, and so on). Countries with several languages have several editions (India has editions in many languages; Switzerland in German, French and Italian). Each edition has its own sources, top stories, categories and local news, though sources and stories overlap.

Language detection on each article (Deep Dive 2) decides which editions can show it. Feeds for an edition normally include only articles in its language. A story cluster can contain articles in many languages; each edition shows the story only if it has enough coverage in that edition's language, and with the representative headline chosen from those articles.

Cross-lingual clustering. Multilingual embedding models map sentences with the same meaning in different languages to nearby vectors, so a French and an English article about the same summit can join the same cluster. This enables "Coverage in other languages" on the story page and better coverage counts for global stories. The risk is over-merging: local stories in two countries that share entity names. Use entity resolution to canonical IDs (a knowledge-base ID for each person, organisation, place) so "Paris" the city in France and "Paris" in another country are different entities.

Time zones. Freshness decay uses absolute time, but the daily cycle of reading and publishing is local. Morning in an edition's main time zone is peak reading time; feed builds can use slightly longer half-lives overnight when fewer stories are published, so the morning page is not dominated by whatever came out at 3 a.m. Show times to readers in their local time zone with relative phrasing ("2 hours ago"), and parse publisher timestamps carefully: many feeds omit time zone offsets or use local times incorrectly, so compare them with our first-seen time.

Localisation of the interface. Category names, dates and number formats vary per locale; right-to-left languages such as Arabic and Hebrew need mirrored layouts. See Internationalization and Localization.

Deep Dive: Evaluating ranking changes safelyShow

Ranking and clustering change often, and a bad change is visible to millions within a minute. A disciplined evaluation loop matters.

Offline evaluation. Before shipping a ranking change, replay recent days: rebuild historical feeds with the new scoring and compare against human-rated "ideal" orderings using metrics such as NDCG (normalised discounted cumulative gain, which rewards putting the most important stories near the top). For clustering, measure precision and recall on labelled article pairs, and check for over-merges on a list of known-tricky cases.

Online experiments. Randomly assign a small share of readers (per edition) to the new ranking and compare: click-through, dwell time, return visits, and quality metrics such as rated accuracy of top stories, source diversity, and the share of high-authority sources in the top 10. Engagement alone can be gamed by sensational stories, so guardrail metrics must not regress.

Interleaving is a more sensitive technique for ranking comparisons: show each reader a list that merges results from the old and new rankers, and see which ranker's stories get more clicks. It detects differences with much less traffic than A/B tests, though it measures preference, not long-term effects.

Shadow builds and safety checks. Run new builders in shadow mode, producing snapshots that are not served, and diff them against production: how many top-10 stories changed, any blocked IDs present, diversity constraints satisfied. Production snapshots pass the same automatic checks before the version pointer moves; if a check fails, keep the old version and alert.

Rollouts. Ship by edition (small editions first), behind a flag that can switch back to the old ranker in seconds. Because snapshots are versioned, rollback is just moving the pointer to a snapshot from the old builder.

Deep Dive: Inside the story-scoring stream jobShow

The feed builder is cheap because a stream job keeps every active story's features up to date as events arrive. Its design is a small but complete stream-processing problem. See Batch vs Stream Processing and Apache Flink and Stream Processing.

Inputs. Two Kafka topics: article-clustered (article ID, story ID, source ID, authority, published time, categories, editions) and clicks (story ID, edition, position, time). A third, low-volume topic carries editorial actions and takedowns.

State per story. Keyed by story ID (so all events for a story go to one worker partition):

  • Set of independent sources (after duplicate collapse) and top-3 authority values.
  • Article counts in sliding windows: last 15 minutes, last hour, previous hour, for velocity.
  • Click and expected-click counters per edition in sliding windows, for debiased CTR.
  • Category and edition weights (aggregated from article votes, Deep Dive 4).
  • Last significant update time.

300,000 active stories × about 2 KB of state ≈ 600 MB in total, spread across workers; a stream engine keeps it in a local state store (for example RocksDB in Flink) with periodic checkpoints to object storage, so a failed worker restores its state and replays Kafka from the checkpointed offsets.

Windows and event time. Use event time (when the article was published or the click happened), not processing time, so a backlog after an outage does not look like a sudden velocity spike. Watermarks tolerate events arriving a minute or two late; anything later updates totals but does not trigger spike alerts. Sliding windows can be implemented as small buckets (one per minute) summed over the window, which keeps updates O(1).

Outputs. Every few seconds, emit changed story features to a compact "story features" table (in Redis or a key-value store) that the builder reads. When velocity crosses a threshold (for example more than 20 independent sources in 30 minutes, or 5× the previous hour), emit a story-spike event that triggers an immediate rebuild of the affected editions' feeds (Deep Dive 8).

Correctness level. Ranking features tolerate small errors: an article counted twice after a replay changes a score by a fraction of a percent. At-least-once processing with idempotent updates where cheap (sets of source IDs are naturally idempotent; counters are not) is sufficient here; exactly-once mode can be enabled in engines that support it, at a modest cost in latency. This is a good example of matching delivery guarantees to the business need rather than demanding exactly-once everywhere.

Expiry. Stories with no new articles for 72 hours leave the active set: their state is dropped (timers in the stream job), their final features are written to the archive, and they disappear from candidate lists.

Deep Dive: Breaking-news push alertsShow

Many news apps send push notifications for major stories. That turns a pull-based system into a fan-out problem for a few seconds at a time.

Choosing what to alert. Alerts are rare and costly to readers' attention. Typical policy: an alert candidate is a story with an extreme velocity spike in an edition, from high-authority sources, above a quality score; for top editions, an editor approves or writes the alert text. Per-user caps (for example at most a few alerts a day) and quiet hours in the reader's local time are enforced at send time. Followed topics can produce personal alerts with stricter caps.

Fan-out. An alert for a large edition targets tens of millions of devices. The sender does not loop over users synchronously: it splits the audience into segments (by edition, topic and time zone), enqueues batches of device tokens, and many workers call the platform push services (APNs for Apple devices, FCM for Android) in parallel, respecting their rate limits and handling invalid tokens. Sending to 50 million devices over about 5 minutes is roughly 170,000 sends per second across workers. See the separate case study Design a Notification System for the delivery pipeline.

The thundering herd after the alert. Millions of readers tap the alert within a minute or two, all opening the same story page. Mitigations: pre-warm the CDN by requesting the story page and page 1 of the relevant feeds from each region before sending; stagger sends over a few minutes; deep-link the alert to the cached story page rather than a personalised endpoint. Without pre-warming, the alert is effectively a self-inflicted load test.

Measurement. Track open rate, time to open, uninstall and opt-out rates after alerts, and the origin load generated. Alert quality is as important as alert speed.

Deep Dive: SLOs and what to monitorShow

Define a small number of service level objectives (SLOs) that match the requirements, then monitor the pipeline stages that feed them.

SLOIndicator (SLI)Example target
Feed availabilityShare of feed requests answered with 2xx (including stale-served) at the CDN99.95% per month
Feed latencyp99 time to first byte at the edge for feed responsesunder 200 ms
Freshnessp95 time from publication to first appearance in a served feed, for top-tier sourcesunder 10 min; all sources under 30 min
Redirect availabilityShare of clicks redirected successfully99.99%
Clustering qualityRated precision of top-50 stories per major editionabove an agreed threshold, reviewed weekly

Pipeline health signals. Feeds fetched per second and 304 ratio; fetch error rates per source and per host; discovery lag per source tier; Kafka consumer lag per stage; articles per hour versus expected per source (silent-source detector); cluster creation rate and average cluster size (a sudden drop in size suggests the clustering model broke); builder duration and age of current snapshot per key (alert if any key's snapshot is older than 5 minutes); CDN hit ratio per path; Redis latency and memory; blocklist propagation time.

Alerting philosophy. Page a human for user-visible SLO burn (availability, latency, snapshot age, freshness), not for every component metric. A snapshot age alert is the single most useful signal: it fires whether the cause is ingestion, clustering, scoring or the builder. See Observability: Logs, Metrics and Traces and Incident Management and Postmortems.

Deep Dive: Consistency choices per data pathShow

The NFR "availability over consistency" is not a single switch. Each data path gets the weakest consistency that is still correct for its purpose. See Consistency Models.

  • Feed snapshots: eventually consistent across regions and caches; a reader may see a feed up to a minute or two old. Within a reader's scroll session, the snapshot gives monotonic, consistent pagination: a stronger guarantee for the one thing readers notice.
  • Story cards: eventually consistent with short TTLs; a corrected headline appears within about a minute.
  • Takedowns: need fast, near-certain propagation. The blocklist is replicated to every server with acknowledgements and checked on every response; CDN purges are confirmed. This is the one path where the system pays for stronger guarantees.
  • User follows and preferences (personalised mode): read-your-writes for the user who changed them: after following a topic, their next request should reflect it. Route the user's next personal-feed build through the primary region, or include a preference version in the request so a stale cache is bypassed.
  • Click counters: approximate is fine; at-least-once counting with small errors is acceptable.
  • Article store: single-writer per article (keyed by URL hash) so concurrent updates from feed and sitemap discoveries do not conflict; the latest content hash wins.

Making this explicit in an interview shows you understand that consistency is a per-use-case decision, not a global property of the system.

Deep Dive: Security of a system that fetches the open webShow

An aggregator fetches and parses untrusted content from tens of thousands of hosts and puts links on a trusted page. That creates specific attack surfaces. See Security Fundamentals for System Design.

Server-side request forgery (SSRF). Feeds and articles contain URLs (images, canonical links, redirects) that our fetchers will request. A malicious feed could point at http://169.254.169.254/ (a cloud metadata service) or internal hostnames. Defences: resolve DNS and reject private, loopback and link-local address ranges after resolution and on every redirect hop (attackers use DNS rebinding and redirects to bypass naive checks); run fetchers in an isolated network segment with egress only to the internet; and never send internal credentials with fetches.

Hostile documents. XML parsers must disable external entities and limit entity expansion (the "billion laughs" attack expands a few KB into gigabytes). HTML parsing runs with memory and time limits per document in sandboxed workers (Deep Dive 1's parser isolation). Image decoding enforces maximum pixel dimensions before decoding fully, to stop decompression bombs, and uses up-to-date, memory-safe or sandboxed decoders, since image libraries have a long history of vulnerabilities.

Output safety. Titles and snippets are untrusted text: escape them when rendering (never insert as raw HTML) to prevent cross-site scripting, and strip control characters and bidirectional override characters that can disguise text. Only allow http and https destination URLs (no javascript: links).

Open redirect. The /r/{articleId} endpoint takes an article ID, not a destination URL, precisely so it cannot be abused to redirect users to arbitrary phishing sites under our domain. If a URL parameter were ever needed, it would have to be signed.

Malicious or compromised publishers. A legitimate site can be hacked and start serving malware. Check destination URLs against a safe-browsing style reputation list when ingesting and periodically afterwards; a flagged source goes on the blocklist immediately (Deep Dive: source quality), removing its links from all feeds within a minute.

Denial of service through ingestion. A feed with millions of entries, an endless chunked response, or a slow-drip server can tie up fetchers. Cap response sizes (for example 10 MB per feed), total time per fetch (for example 30 s), and entries processed per feed fetch; per-source queues keep one bad source from starving others.

Deep Dive: A 45-minute interview planShow
MinutesWhat to do
0–5Clarify: shared front page or personalised? Editions and categories? Freshness target (30 min)? Latency target (200 ms)? Click-through to publishers. Agree that availability beats consistency.
5–10Estimate: 50,000 sources, 1M articles a day, 10,000 feed reads per second average, 300,000 at peak, read:write about 1,000:1, about 1,000 shared feeds. State the insight: feeds are shared and cacheable.
10–15Entities and API: feed with cursor and version, story page, redirect. Cache-Control headers.
15–25High-level design: scheduler and fetchers, extraction, dedupe and clustering, categorisation, story scoring, feed builder writing snapshots to Redis, feed API behind the CDN, click redirect logging to Kafka, image pipeline to object storage.
25–40Deep dives the interviewer picks, usually two or three of: pagination with versioned snapshots; under-200 ms via precompute plus CDN plus stale-while-revalidate; 30-minute freshness budget with WebSub and adaptive polling; dedupe and clustering; breaking-news spikes; personalisation.
40–45Failure modes and trade-offs: stale over error, degradation order, takedown purge path, clustering errors, what you would build next.

Common mistakes. Computing the feed per request with a database query; offset pagination without noticing duplicates; hotlinking publisher images; ignoring duplicates from wire stories; treating freshness as "poll every minute" without a budget; making personalisation the core design rather than a layer on shared feeds.

Deep Dive: Follow-up questions and strong answersShow

"How do you get from 30 minutes to under 5 minutes for major sources?" Discovery dominates: WebSub push or 30–60 s polling for top sources (with conditional GETs, cheap for both sides), a dedicated priority queue, event-driven feed rebuilds on velocity spikes, and page-1 purges. The rest of the pipeline already takes under 2 minutes.

"Why not a push model to each reader like a social feed?" Social feeds fan out because each user's feed is unique. Here, most readers of an edition see the same feed, so fan-out on write to 100 million users would copy the same list millions of times. Fan-out happens per edition (about 1,000 keys), not per user.

"What if two snapshots disagree across regions?" Readers stick to one region per session in normal operation (CDN routing). If a reader fails over mid-scroll and the snapshot version is missing in the new region, the fallback is the same as an expired snapshot: current version plus client-side dedupe. Snapshots are replicated to all regions within seconds, so this is rare.

"How do you handle a story that is updated constantly, like a live blog?" Treat repeated updates to one URL as updates to one article (URL hash), throttle re-fetches per URL (for example at most once every 2 minutes), and refresh the story's "last updated" time only when the content hash changes meaningfully, so a live blog does not stay at the top just by changing a timestamp.

"How would you rank local news for a small town?" Few sources, low volume: use a longer half-life (local stories stay relevant for a day or two), include the local paper's sections, geotag articles from regional outlets, and build the local feed on request with a few minutes of caching, since each local key has little traffic.

"How do you prevent the feed from showing the same story twice?" At build time, the diversity pass enforces one card per story and per topic in the top N; at serving time, snapshots guarantee consistent pagination; at the client, a set of seen story IDs filters any duplicates from fallback paths.

"What database stores articles?" The hot set (72 hours) lives in the processing state and caches. The article store can be a sharded relational database (good for joins between sources, articles, stories and categories, and for the moderate write rate of tens per second) or a wide-column store keyed by article ID if the archive grows very large. Search goes to a search engine; feeds to Redis; images to object storage. Each store matches one access pattern.

"What changes if you must show full article text in-app?" It becomes a licensing and publishing product: agreements with publishers, a content ingestion API or feeds with full content, paywall integration, and far larger storage and CDN bytes for article bodies. Architecturally, add a content store and renderer, but the feed design does not change.

"How would you detect that a source stopped publishing because its feed broke, not because it has no news?" Model each source's normal publishing rate per hour of the week; alert when observed articles fall far below the expected count (for example a Poisson tail probability under 0.1%) while the source's homepage still changes. Then fall back to sitemap or homepage discovery automatically.

"How do you make clustering decisions explainable?" Store the similarity components (cosine, entity overlap, time) with each assignment, so reviewers can see why an article joined a story, and log merges and splits with their reasons.

Key Takeaways#

  • A news aggregator is read-dominated and shared: about 1,000 reads per write, and most readers of an edition see the same feed. Precompute feeds per edition and category and serve them from Redis and the CDN.
  • Ingestion is a polite, adaptive crawler: WebSub where available, conditional GETs, polling intervals that follow each source's publishing rate, priority tiers, and isolated parsers for messy HTML.
  • De-duplicate with URL and content hashes and SimHash, then cluster articles into stories incrementally with embeddings, entities and time, repairing mistakes with periodic merge and split jobs.
  • Ranking combines freshness decay with a half-life, independent coverage, velocity, source authority, locality and debiased engagement, followed by diversity rules and editorial overrides.
  • Infinite scroll needs versioned, immutable snapshots: the cursor carries version and offset, so pages never duplicate or skip, and deep pages are cacheable forever.
  • Under 200 ms comes from precomputation plus in-process caches plus the CDN with stale-while-revalidate; under 30 minutes freshness comes from a measured, per-stage latency budget dominated by discovery.
  • Availability beats consistency: serve stale rather than fail, degrade personalisation first, and use purges plus a blocklist for takedowns that must be immediate.
  • Personalisation is a layer: candidates from shared feeds, a cheap per-user re-rank, brief per-user caching, cold-start handling, diversity guarantees and privacy controls.