Twitter Search
Full-text search over a firehose of tweets — an inverted index, sharded and scatter-gathered — worked through the TOGAF ADM.
Twitter search, the ADM way, in 30 seconds
- A (Vision): search a firehose of tweets quickly and keep results fresh; principles — fast queries, fresh enough results, scale with volume.
- B (Business): two capabilities — index new tweets (continuous write) and search terms (fast read); plus ranking of what comes back.
- C (Data/App): an inverted index mapping terms → tweet IDs on the read side; an indexing pipeline consuming the tweet stream on the write side.
- D (Technology): build an inverted index, shard it, feed it from a tweet stream pipeline, and answer queries by scatter-gather across shards then merge + rank.
- E–H: ship a single-shard index, add the streaming pipeline, then shard and tune freshness; govern with query SLOs and freshness policy.
- Lesson: 'fast queries' plus 'fresh enough' (Phase A) is exactly the freshness-vs-cost trade Phase D has to make.
Like the index at the back of a book, rebuilt every second
Open any thick textbook and flip to the index at the back. You want every page that mentions 'photosynthesis'? You don't read the whole book — you jump to the P's and the index hands you the page numbers directly. That back-of-book index is exactly what powers search: instead of term → read every page looking for it, you flip it around to term → the exact list of places it appears. That flip is why it's called an inverted index.
Now make it brutal. The 'book' is every tweet ever posted — trillions of entries — and it's growing by thousands of tweets a second, each of which must be slotted into the index while people are still searching it. One index at the back of one book can't hold that, and one librarian can't keep up. So you split the index across many librarians (shards) and, when someone searches, you ask all of them at once and merge what they return. That split-and-merge is the whole shape of the system.
What makes it hard — the problem before the solution
- A scan is far too slow. Reading every tweet to find matches would take seconds per query. You need the answer to be a lookup, which means pre-building an index.
- The corpus is too big for one machine. Trillions of postings won't fit — let alone serve fast — from a single node, so the index must be split across many.
- Writes never stop. Thousands of new tweets a second must be folded into the index continuously, without ever pausing or slowing the people searching.
- Fresh and cheap pull against each other. Making a tweet searchable the instant it's posted costs more compute; batching is cheaper but staler. Where you sit on that line is a real decision, not a default.
Why the ADM fits
Search over tweets sounds like 'grep the database' — until you confront a continuous firehose of new tweets, the need to return matches in milliseconds, and the tension between showing the very latest tweet and keeping indexing costs sane. The ADM keeps those in order: the fast queries and fresh enough principles from Phase A are precisely what force the sharded inverted index and the streaming indexing pipeline that dominate Phase D. Each technology choice answers an earlier constraint rather than a hunch.
Phase A — Architecture Vision
Intent: agree what we're building, for whom, and the principles that constrain every later choice.
- Vision: let anyone type words and instantly find relevant tweets, including ones posted moments ago, across an enormous and ever-growing corpus.
- Stakeholders: searchers (want fast, relevant, recent results), the platform (wants trends and discovery to work), operators (want indexing and query cost under control at firehose scale).
- Principles (the constraints that cascade): fast queries (results in milliseconds, not seconds); fresh enough results (new tweets become searchable quickly, but perfect instant visibility isn't required); scale with volume (both the corpus and the query load only grow).
Phase B — Business Architecture
Intent: model the business capabilities and value streams before any technology talk.
- Value stream: a tweet is posted → it gets indexed → a user searches a term → matching tweets are found, merged, and ranked → the user sees recent, relevant results.
- Capability 1 — Index new tweets: a continuous, high-throughput write stream; every tweet must be tokenized and added to the index.
- Capability 2 — Search terms: high-volume, latency-critical reads that must find all tweets containing the query terms.
- Capability 3 — Rank results: order matches by recency, relevance, and engagement so the best tweets surface first.
Impact: indexing (write) and searching (read) are different beasts — one is a steady firehose, the other a bursty latency-critical lookup — and ranking sits on top of search. That separation, surfaced in Phase B, is why Phase D builds a pipeline for the write side and a scatter-gather read side that meet only at the index.
Phase C — Information Systems Architecture (Data & Application)
Intent: define the data and application architecture, and the gap from today (greenfield).
Data architecture
- Core structure: an inverted index — a mapping from each term → list of tweet IDs (a postings list) that contain it. Searching 'coffee' is then a lookup, not a scan.
- Access pattern: given terms, return matching tweet IDs fast, then fetch tweet content by ID — the index answers the 'which tweets' question and a separate store holds the tweet bodies.
- Freshness state: the index lags the live tweet stream by some small, bounded amount — an accepted eventual consistency between 'tweet posted' and 'tweet searchable'.
- Conclusion: this is a classic inverted-index shape (see Indexing) — the access pattern, defined by the capabilities, chose the data structure, not the other way around.
# Inverted index: term -> newest-first list of tweet IDs that contain it.
inverted_index = {
"coffee": [99812, 99550, 98001, ...], # postings list
"shop": [99812, 97233, ...],
"rain": [99988, 99812, ...],
}
# The index answers "WHICH tweets" — it holds IDs, never the text.
# Tweet store: ID -> the actual tweet (fetched only after the index narrows it down).
tweet_store = {
99812: { "text": "best coffee shop in the rain", "author": "ada", "ts": ... },
}
# Split on purpose: lookups stay tiny; heavy bodies live in a separate store.Application architecture
- An indexing pipeline that consumes the tweet stream, tokenizes each tweet, and updates the index — decoupled so a burst of tweets never stalls queries.
- A stateless query tier that fans a search across index shards and merges the results — scales horizontally per the Phase A principle.
- A ranking stage applied after merge, so ordering logic is isolated from both indexing and the raw postings lookup.
Phase D — Technology Architecture (the core)
Intent: choose the concrete technologies and the deployment design that realize Phase C — and justify each one against the principles and numbers. This is where a technical interviewer spends most of the time, so we'll cover every step.
D1 — Estimate the load (sizing drives technology)
# 500M tweets/day indexed
index_writes_per_sec = 500_000_000 / 86_400 # ~5,800 tweets/sec to index
# ~10 searchable terms per tweet -> postings updates
postings_updates_per_sec = index_writes_per_sec * 10 # ~58,000 updates/sec
# Query side: say 50k searches/sec at peak
queries_per_sec = 50_000
# Corpus: 500M/day * 365 * few years -> ~trillion postings
# Verdict: one index can't hold or serve this -> SHARD the index,
# and feed it from a streaming pipeline, not synchronous writesThe numbers confirm the Phase B separation quantitatively: a relentless write stream fanning into tens of thousands of postings updates per second, a heavy query load, and a corpus far too large for one index. Those three facts dictate a streaming pipeline, a sharded index, and scatter-gather reads.
D2 — Build & shard the inverted index
- The index is an inverted index: for each term, keep a postings list of tweet IDs (newest-first helps recency ranking). A query term becomes a direct postings lookup instead of a full scan.
- Shard the index (see Sharding) because one trillion postings won't fit or serve from a single node — the corpus from D1 forces this.
- Shard by document (tweet ID range or hash), not by term: each shard holds a complete mini-index over its slice of tweets, so writes spread evenly and no single hot term (like a trending hashtag) overloads one shard.
- Replicate each shard for durability and read throughput, so a node loss doesn't lose part of the index or drop query capacity.
# Build the inverted index: term -> newest-first list of tweet IDs (D2).
def index_tweet(index, tweet):
terms = set(tokenize(tweet.text.lower())) # dedupe terms within a tweet
for term in terms:
postings = index.setdefault(term, [])
# Prepend so the newest tweet sits at the front -> cheap recency ranking.
postings.insert(0, tweet.id)
# A query term is now a direct lookup, never a full-corpus scan.Why shard by document, and why not the obvious shard-by-term?
The intuitive way to split an index is by term: put all of 'coffee's postings on one shard, all of 'rain's on another. A query for one term then hits exactly one shard — tempting. But it has a fatal flaw at Twitter scale: terms are wildly unequal. When a hashtag trends, every tweet contains it, so that one term's shard takes the entire write firehose and the entire query load for the trend — a guaranteed hotspot that melts.
Sharding by document (each shard owns a slice of tweets and keeps a complete mini-index over just those) spreads writes evenly — a new tweet updates exactly one shard regardless of which words it uses — and no single term can overload one node. The cost is that every query must ask all shards (scatter-gather) since any shard might hold a match. That's a cost you pay happily, because it's bounded and parallel, whereas a term hotspot is not.
| Approach | What it buys | The gap it can't fill |
|---|---|---|
| Shard by term | A single-term query touches just one shard. | Trending terms create brutal hotspots; write load for a hot term all lands on one node — it melts. |
| Shard by document (chosen) | Even write spread; no term can hotspot; each shard is a self-contained mini-index. | Every query must fan out to all shards — accepted, since scatter-gather is parallel and bounded. |
| One giant index (no sharding) | Simplest; no merge step. | Won't fit or serve a trillion-posting corpus from one node — a non-starter at scale. |
D3 — The write path (streaming pipeline) & the read path (scatter-gather)
- Index via a pipeline: new tweets flow onto a stream (see Message queues); indexer workers consume it, tokenize each tweet, and append to the right shard's postings — decoupling indexing from both tweeting and querying so bursts are absorbed, not blocked.
- Freshness vs cost is the key trade: index more eagerly (smaller batches, more workers) and tweets become searchable sooner but you pay more; batch more and it's cheaper but staler. This is exactly the fresh enough results knob from Phase A (see Consistency models).
- Query = scatter-gather: the stateless query tier fans the search out to all shards in parallel (scatter), each shard returns its local matches, and the tier merges them and applies ranking by recency, relevance, and engagement (gather).
- Cache hot queries (see Caching): trending terms repeat constantly, so caching merged results for popular queries shaves load off the shards and realizes fast queries under spikes.
# 'coffee shop' => tweets that contain BOTH terms (D3 read path).
def search(index, query):
terms = tokenize(query.lower())
# Look up each term's postings; a missing term means zero results.
lists = [index.get(t, []) for t in terms]
if not lists or any(len(l) == 0 for l in lists):
return []
# Start from the SHORTEST list so the intersection stays cheap.
lists.sort(key=len)
result = set(lists[0])
for postings in lists[1:]:
result &= set(postings) # keep only IDs present in every list
# Per-shard matches; the query tier merges + ranks across shards.
return sorted(result, reverse=True) # newest-first by tweet IDasync def search_cluster(query):
cached = cache.get(query)
if cached: # trending terms repeat constantly
return cached
# SCATTER: fan the same query to every shard at once (parallel).
partials = await gather(*[shard.search(query) for shard in all_shards])
# GATHER: flatten every shard's local matches into one candidate set.
candidates = [tid for part in partials for tid in part]
# RANK across the merged set: recency, relevance, engagement.
ranked = rank(candidates, query)[:50]
cache.set(query, ranked, ttl=10) # short TTL keeps trends fresh-ish
return rankedScaling & bottlenecks — what breaks first
Turn the dial up and search fails in a predictable order. Because every query touches every shard, the surprising first casualty is often the slowest shard, not the busiest one — a single lagging node drags the whole scatter-gather.
| Breaks first as you scale | The symptom | The fix |
|---|---|---|
| Tail latency on scatter-gather | One slow shard makes every query slow, since the merge waits for the laggard. | Replicate shards and race replicas; set a per-shard deadline and return partial results past it. |
| Indexing lag | New tweets take too long to become searchable during a spike. | Add indexer workers; shrink batch size (spend more for fresher results); shard the stream. |
| Trending-term query flood | A breaking event sends identical queries by the million. | Cache merged results for hot queries with a short TTL; serve the cache, not the shards. |
| Postings-list bloat for common words | Ubiquitous terms have enormous postings lists that are slow to intersect. | Start intersections from the shortest list; drop stopwords; cap/segment very long lists by time. |
Phases E & F — Opportunities, Solutions & Migration Planning
- Greenfield, so sequence by risk: first build a single-shard inverted index over a static tweet dump to prove query correctness and ranking.
- Add the streaming indexing pipeline next, so new tweets become searchable continuously instead of via re-imports.
- Then shard and tune freshness once corpus and query volume outgrow one node — each step independently shippable, echoing the expand-contract spirit of the TOGAF commerce scenario.
Phases G & H — Governance & Change Management
- Governance (G): define query SLOs (search p99 in the low hundreds of ms), a freshness policy (how long a tweet may take to become searchable), and ranking-quality and content-safety guardrails.
- Change management (H): adding a new ranking signal or a language-specific tokenizer is a bounded change to the ranking stage or indexer — not a re-architecture — precisely because indexing, lookup, and ranking were drawn as clean boundaries.
Twitter search is the canonical full-text-search-at-scale problem: an inverted index, sharded across nodes, fed by a stream and queried by scatter-gather — a shape that recurs in every large search system.
Why it matters
- It makes the inverted index concrete: search becomes a lookup, not a scan.
- It forces the freshness-vs-cost trade into the open as an explicit, governed decision.
- It shows scatter-gather — fan out, merge, rank — as the standard way to query a sharded index.
If ignored
- Scan the tweet store per query and searches take seconds instead of milliseconds.
- Index synchronously on the tweet path and a posting burst stalls both tweeting and querying.
- Shard by term and a single trending hashtag turns one shard into a hotspot that melts under load.
Where it fits
- Phase D holds the inverted index, its sharding, the streaming indexing pipeline, and scatter-gather queries.
- Phase A's fast-queries and fresh-enough principles drive those D mechanisms.
- Sits beside the interview framework as a second way to structure the answer.
Related topics
- Sharding: splits the inverted index so no single node holds the whole corpus
- Message queues: carries the tweet stream into the indexing pipeline
- Indexing: the inverted index that turns search into a lookup
- Caching: absorbs repeated trending-term queries off the shards
Interview lens
Questions it unlocks
- Design Twitter search.
- How do you build full-text search over a firehose of tweets?
- Walk me through the technology architecture (Phase D) for a sharded, scatter-gather search service.
60-second answer
I frame it as an ADM walk so every choice is traceable. Phase A sets principles — fast queries, fresh enough results, scale with volume. Phase B separates indexing, a continuous write stream, from searching, a latency-critical read, with ranking on top. Phase C makes the core structure an inverted index mapping terms to tweet-ID postings lists, accepting a bounded lag between posted and searchable. Then Phase D builds it: a sharded inverted index sharded by document so no trending term hotspots a single node, fed by a streaming pipeline where indexer workers tokenize tweets off a queue — with the batch size as the freshness-vs-cost knob the Phase A principle asked for. Queries scatter-gather: fan out to all shards in parallel, merge the matches, and rank by recency, relevance, and engagement, with hot trending queries cached. E–H start single-shard, add the pipeline, then shard and tune freshness, governed by query SLOs and a freshness policy. The power is that the sharded index and scatter-gather are consequences of the Phase A and B constraints, not guesses.
Common traps
- Scanning the tweet store per query instead of building an inverted index, so searches are slow.
- Sharding by term, which turns a trending hashtag into a single overloaded shard.
- Indexing synchronously on the tweet-write path so posting bursts stall both tweeting and search.