Case Study 29 โ€” Web Search Engine (Simplified)

Design a simplified Google-like web search: crawl the web, build an index, and return ranked results for a query in milliseconds.

1. Problem

Given a search query like "distributed systems cap theorem", return the most relevant web pages from billions of documents โ€” fast ( < 300 ms) and fresh (recent pages indexed within days).

This case study covers a minimal but realistic pipeline: crawler โ†’ indexer โ†’ inverted index โ†’ ranking โ†’ query service.

2. Requirements

Functional (MVP)

  • Crawl known seed URLs; discover new links
  • Parse HTML; extract text, title, links
  • Build inverted index: term โ†’ list of docIds
  • Query: return top 10 URLs with titles and snippets
  • Basic ranking: term frequency + PageRank-style authority
  • Avoid duplicate content (URL normalization, simhash)

Out of scope (initially)

  • Image/video/news verticals
  • Personalized ranking (search history)
  • Full natural-language understanding (BERT reranking)
  • Ads auction
  • Real-time index (minutes-level freshness for all web)

Non-functional

  • Index billions of documents (web scale simplified to 100Mโ€“1B docs)
  • Query latency p99 < 300 ms
  • Crawl politeness (rate limits per domain)
  • Fault tolerance โ€” crawler and indexer are distributed
  • Storage efficiency โ€” compression, sharding

3. Back-of-the-envelope estimates

These numbers are rough order-of-magnitude math โ€” not a capacity plan. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained โ‰ˆ 86,400 requests/day. Search peaks (breaking news, product launches) often hit 3โ€“4ร— average query rate.

Why we estimate

A search engine splits into offline (crawl + index โ€” batch, huge storage) and online (query โ€” low latency, in-memory). Estimates tell us:

  • Whether query QPS or index size drives architecture
  • Why the inverted index must live in RAM (or SSD with hot shards)
  • Minimum crawl throughput to keep 500M pages fresh

Assumptions

AssumptionValueWhy it matters
Indexed web pages500MCorpus size
Average extracted text per page5 KBRaw text + index input
Average HTML fetched20 KBCrawl bandwidth
Unique vocabulary (terms)10MDictionary size
Searches per day5BQuery path load
Index refresh target30 daysCrawl rate floor
Top results returned10Query response size

Step A โ€” Traffic (QPS) with labeled arithmetic

Search queries (online path โ€” latency critical):

Searches per day    = 5 billion
Query QPS (avg)     = 5B รท 86,400
                    โ‰ˆ 58,000 queries/second

Peak query QPS (3ร—) โ‰ˆ 58,000 ร— 3
                    โ‰ˆ 174,000 queries/second

Each query: tokenize โ†’ lookup postings lists โ†’ score โ†’ return top-10. Target p99 < 300 ms.

Crawl fetches (offline path โ€” throughput critical):

Pages to refresh in 30 days = 500M
Seconds in 30 days          = 30 ร— 86,400 = 2,592,000

Minimum crawl QPS           = 500M รท 2,592,000
                            โ‰ˆ 193 pages/second (steady refresh only)

With discovery + dead links + deep web:
Target crawl cluster        โ‰ˆ 1,000โ€“10,000 pages/second

Index build (batch jobs):

If re-indexing 500M pages daily (aggressive):
  Indexer throughput needed โ‰ˆ 500M รท 86,400 โ‰ˆ 5,800 pages/second
MVP: incremental indexing on crawl completion โ€” thousands of docs/s per indexer shard

Step B โ€” Storage

Raw extracted text:

Text storage        = 500M pages ร— 5 KB/page
                    โ‰ˆ 2.5 TB uncompressed
Compressed (~3ร—)    โ‰ˆ 750 GB โ€” S3/HDFS for crawl store

Inverted index (postings lists):

Terms               = 10M unique
Avg postings/term   โ‰ˆ 50 KB (doc IDs + frequencies, delta-encoded)

Index size (rough)  = 10M ร— 50 KB โ‰ˆ 500 GB
Compressed          โ‰ˆ 150โ€“300 GB โ€” must shard across index servers

Document metadata (title, URL, PageRank, snippet):

500M docs ร— 500 B   โ‰ˆ 250 GB โ€” colocated with index shards or separate KV store

Link graph (for PageRank โ€” offline):

Assume 50 links/page avg ร— 8 B = 400 B/page
500M ร— 400 B        โ‰ˆ 200 GB โ€” processed offline, not on query hot path

Step C โ€” Bandwidth and other resources

Crawl ingress (fetching web pages):

Crawl rate (target) = 5,000 pages/second
Page size (avg)     = 20 KB HTML

Crawl bandwidth     = 5,000 ร— 20 KB โ‰ˆ 100 MB/s โ‰ˆ 800 Mbps
Peak with retries   โ‰ˆ 1โ€“2 Gbps โ€” politeness rate limits per domain cap this

Query response egress:

Results payload     โ‰ˆ 10 results ร— 2 KB (title + URL + snippet) โ‰ˆ 20 KB
Peak query QPS      โ‰ˆ 174,000/s

Egress (if uncached) = 174,000 ร— 20 KB โ‰ˆ 3.5 GB/s โ€” CDN for static assets; API JSON from query tier

Index shard memory (query hot path):

500 GB index รท 20 shards โ‰ˆ 25 GB/shard
Each shard serves   โ‰ˆ 174,000 รท 20 โ‰ˆ 8,700 QPS
โ†’ RAM or NVMe SSD with mmap; hot terms cached in memory

Step D โ€” Read:write ratio table

OperationTypeAvg ratePeak rateNotes
User search queryRead~58K QPS~174K QPSSub-300 ms
Crawl page fetchWrite (store)~193โ€“5K/s~10K/sPoliteness per domain
Index update (incremental)Write~1K docs/s~5K docs/sAsync from crawl pipeline
PageRank (offline batch)Read/writeN/APeriodicNot on query path
Autocomplete (optional)Read~10K QPS~40K QPSPrefix index in Redis

Ratio: online path is read-only at massive QPS; offline crawl/index is write-heavy but latency-forgiving.

What the numbers tell us

  • ~174K query QPS peak โ†’ shard inverted index by term_hash or doc_id; replicate hot shards
  • ~500 GB inverted index must sit on index servers with RAM/NVMe โ€” disk-only query path is too slow
  • Crawl ~193 pages/s minimum for 30-day refresh; real systems crawl 1Kโ€“10K/s with distributed frontier
  • 750 GB compressed text in object store โ€” query path never reads raw HTML
  • Precompute PageRank offline โ€” store score in doc metadata; query-time scoring uses precomputed + BM25
  • Politeness โ€” rate limit per domain (1โ€“2 req/s) โ†’ huge URL frontier queue, many crawler workers

Common mistake for this problem

Scanning 500M documents linearly per query. Inverted index lookup is O(postings for matched terms), not O(corpus). Another mistake: crawling without politeness โ€” you get blocked and skew freshness. Finally, storing the full index on spinning disk for 174K QPS โ€” hot shards need memory or SSD.

4. High-Level Design (HLD)

Components

ComponentRole
URL FrontierPriority queue of URLs to crawl (BFS-ish with politeness)
CrawlersFetch HTTP pages; respect robots.txt
Raw StoreBlob storage for HTML (S3/HDFS)
ParserExtract text, title, outbound links, metadata
Index BuilderBuilds inverted index + forward index
Index ShardsPartitioned by term range or document ID
PageRank JobOffline compute authority scores
Query ServiceParse query, merge shard results, return ranked list
Doc ServerMap docId โ†’ URL, title, snippet text

Flows

Crawl loop

  1. Frontier dequeues URL for domain D (respect per-domain rate limit)
  2. Crawler fetches page โ†’ store raw HTML
  3. Parser extracts text + links
  4. New links enqueued to frontier (dedupe by normalized URL)
  5. Index builder consumes parsed doc โ†’ update inverted index

Query

  1. Tokenize query โ†’ stem โ†’ remove stop words
  2. Lookup postings for each term on index shards
  3. Intersect / merge posting lists (AND for multi-term)
  4. Score candidates (TF-IDF + PageRank)
  5. Fetch top N doc metadata for snippets
  6. Return JSON results

Trade-offs

  • Freshness vs crawl cost โ€” prioritize popular/changing pages
  • Index sharding by term vs doc โ€” term shard: single-term lookup easy; multi-term needs merge. Doc shard: update easy; query hits all shards
  • Exact PageRank vs approximation โ€” offline batch OK for MVP
  • Snippets precomputed vs at query time โ€” precompute first 160 chars per doc

5. Low-Level Design (LLD)

APIs

GET /api/v1/search?q=cap+theorem+distributed&limit=10
โ†’ {
     "query": "cap theorem distributed",
     "tookMs": 42,
     "results": [
       {
         "url": "https://example.com/cap",
         "title": "CAP Theorem Explained",
         "snippet": "...Consistency, Availability, Partition tolerance...",
         "score": 0.92
       }
     ],
     "totalEstimate": 1250000
   }

POST /internal/v1/crawl/enqueue
Body: { "urls": ["https://example.com/"] }
โ†’ 202 Accepted

GET /internal/v1/doc/:docId
โ†’ { "docId": "d_991", "url": "...", "title": "...", "text": "..." }

Schema

documents (
  doc_id       BIGINT PRIMARY KEY,
  url          TEXT NOT NULL UNIQUE,
  url_hash     BIGINT NOT NULL,
  title        TEXT,
  text_blob_id TEXT,              -- pointer to object storage
  pagerank     FLOAT DEFAULT 0,
  indexed_at   TIMESTAMPTZ NOT NULL,
  content_hash VARCHAR(64)        -- simhash for dedup
)

-- Forward index (metadata by doc)
-- Inverted index is mostly custom binary on index servers, not row-per-posting in SQL

url_frontier (
  url          TEXT PRIMARY KEY,
  domain       VARCHAR(256) NOT NULL,
  priority     INT DEFAULT 0,
  last_crawled TIMESTAMPTZ NULL,
  crawl_delay_ms INT DEFAULT 1000
)

links (
  from_doc_id  BIGINT,
  to_doc_id    BIGINT,
  anchor_text  TEXT,
  PRIMARY KEY (from_doc_id, to_doc_id)
)

Inverted index file format (per shard):

term โ†’ [docFreq, [docId, tf, positions...], [docId, tf, positions...], ...]
       postings sorted by docId with delta + varint compression

Modules

SearchController
QueryParser               (tokenize, stem, stop words)
IndexShardClient            (fan-out to shards)
PostingsMerger              (intersect / union)
RankingService              (BM25 + PageRank blend)
SnippetGenerator
CrawlScheduler
RobotsTxtCache
DocumentRepository

Algorithm โ€” build inverted index

function indexDocument(docId, terms[], positions[]):
  for each term in terms:
    shard = shardForTerm(term)           // e.g., hash(term) mod numShards
    shard.appendPosting(term, docId, tf, positions)

function shardForTerm(term):
  return hash(term) % NUM_TERM_SHARDS

Algorithm โ€” query execution (multi-term AND)

function search(query):
  terms = stem(tokenize(query)) - stopWords
  if terms.isEmpty(): return []

  lists = []
  for term in terms:
    lists.append(indexShard.lookup(term))   // parallel fan-out

  candidates = intersectSortedPostings(lists)   // merge join on docId

  scored = []
  for doc in candidates:
    score = bm25(doc, terms) + alpha * doc.pagerank
    scored.append((doc.id, score))

  top = partialSort(scored, k=100)
  return fetchSnippets(top, k=10)

function intersectSortedPostings(lists):
  // Simultaneous scan โ€” doc must appear in ALL lists
  pointers = [0] * len(lists)
  results = []
  while all pointers valid:
    maxDoc = max(lists[i][pointers[i]].docId for i)
    if all lists[i][pointers[i]].docId == maxDoc:
      results.append(combine(lists, pointers))
      advance all pointers
    else:
      advance pointers where docId < maxDoc
  return results

Algorithm โ€” BM25 scoring (simplified)

function bm25(doc, queryTerms):
  score = 0
  for term in queryTerms:
    tf = termFrequency(doc, term)
    df = documentFrequency(term)
    idf = log((N - df + 0.5) / (df + 0.5))
    score += idf * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * doc.length / avgDocLength))
  return score

Algorithm โ€” crawler politeness

function crawlNext():
  url = frontier.dequeueHighestPriority()
  domain = extractDomain(url)
  if not robotsAllowed(domain, url): return skip
  if timeSinceLastFetch(domain) < crawlDelay(domain): requeue(url); return
  html = httpGet(url)
  storeRaw(url, html)
  enqueueOutlinks(parseLinks(html))
  markCrawled(url, now())

Concurrency & correctness

  • URL normalization before dedup (http/https, trailing slash, lowercase host)
  • Simhash near-duplicate detection avoids indexing same content twice
  • Index updates are segment-based โ€” new segments built offline, swapped atomically
  • Crawl idempotency by URL hash in frontier

6. Scale evolution

StageChange
MVPSingle-machine index; crawl 1M pages; BM25 only
ShardingTerm-based index shards; query fan-out + merge
FreshnessTiered crawl priorities; delta index for recent docs
RankingOffline PageRank; optional ML reranker on top 100
GlobalGeo-distributed index replicas; CDN for static assets only
Scale queryResult caching for head queries; autocomplete separate index

7. Recap

  • Search = offline indexing + online postings lookup
  • Inverted index maps term โ†’ documents; compressed postings lists are core
  • Multi-term queries = intersect sorted postings across shards
  • Crawler politeness and URL frontier prevent overload and bans
  • Ranking blends relevance (BM25) and authority (PageRank)

Practice: draw the offline/online split diagram from memory, then write pseudocode for intersectSortedPostings without looking.