This article explores the core architectural principles behind web search engines like Google, focusing on how they efficiently retrieve and rank billions of documents. It details the use of an inverted index for fast keyword-to-document mapping, the scatter-gather pattern for distributing queries across sharded indices, and a two-phase ranking approach to balance performance with relevance.
Read original on Dev.to #systemdesignThe fundamental problem in web search is retrieving relevant documents from billions of pages in milliseconds. This is impossible with a linear scan. The architectural insight is to perform the expensive work of processing and indexing documents ahead of time, during crawling, leaving only fast, cheap operations for query time. This precomputed structure is known as the inverted index.
Unlike a traditional document-to-word index, an inverted index maps words to the documents that contain them. For each unique word, a "postings list" stores references to all documents where it appears. When a user queries for multiple words (e.g., "database sharding"), the system performs a set intersection of the corresponding postings lists. Since these lists are typically sorted by document ID, intersections can be executed very efficiently in linear time. Postings lists also store additional signals like term frequency and position, crucial for later ranking, and are aggressively compressed to reduce I/O.
To handle the scale of the entire web, the inverted index is partitioned across thousands of servers, usually by document ID. Each server (shard) holds a complete index for its slice of documents. At query time, the system employs a scatter-gather pattern:
This parallel processing ensures that query latency is determined by the slowest shard, not the sum of all operations. Shards are also replicated for fault tolerance and increased throughput.
Retrieving documents based on keywords can yield thousands of matches. Ranking all of them with a complex model is computationally prohibitive. Therefore, search engines use a two-phase ranking strategy:
Key Trade-off
The entire design of a web search engine front-loads significant cost. Crawling, parsing, and building the inverted index is a continuous, resource-intensive process. However, this upfront investment transforms query time into a rapid read operation. The trade-off involves sacrificing instantaneous freshness (new pages aren't immediately searchable) and incurring high storage/indexing costs for sub-second query latency. This is a deliberate choice for systems where read operations vastly outnumber write (update/index) operations.