DEV Community

Mubashir Taj
Mubashir Taj

Posted on

How Google Search Returns Results in Under a Second

Type a query into Google Search and the results arrive in well under a second. That feels ordinary now, but it is worth pausing on what the system has to do in that time. The web contains hundreds of billions of pages. A single query has to find the pages that match, rank them by relevance and quality, and return the top ten, all while thousands of other people are doing the same thing at the same moment. No single machine can hold the index, and no single machine can answer the query fast enough on its own. The answer is a distributed system built from a few simple ideas, applied at enormous scale: crawl everything in advance, organize the index so lookups are cheap, split the work across tens of thousands of machines, and cache aggressively at every layer. This article walks through each piece, in the order a query actually flows through the system.

The first thing to understand is that almost no work happens at query time. The expensive work happens in advance, continuously, in the background. Crawlers fetch pages from across the web, day and night. The fetched pages are parsed, and the text is extracted and analyzed. Links are followed to discover new pages. Copies of pages are stored so the system can show cached versions and reprocess content without fetching it again. This pipeline runs constantly, because the web changes constantly: news pages update within minutes, product pages change prices, and new pages appear every second. By the time you type a query, the system has already done the slow work of finding and reading the pages. The query itself is a lookup against data structures that were built for exactly that purpose.

The central data structure is the inverted index, and it is the same idea that powers search inside a database or a documentation site, scaled up. A normal index maps a document to the words it contains. An inverted index flips that around: it maps each word to the list of documents that contain it, along with the positions of the word inside each document. When you search for "postgres connection pooling", the system looks up three posting lists, one per word, and intersects them to find documents containing all three. The positions matter because they let the system tell a document where the words appear next to each other from a document where they appear in unrelated paragraphs. The phrase match is a strong relevance signal, and it is cheap to compute once positions are stored.

A simplified inverted index in Go shows the shape of the idea:

package main

import "fmt"

type Posting struct {
    DocID     int
    Positions []int
}

type Index struct {
    postings map[string][]Posting
}

func (idx *Index) Add(term string, docID int, pos int) {
    list := idx.postings[term]
    if len(list) > 0 && list[len(list)-1].DocID == docID {
        list[len(list)-1].Positions = append(list[len(list)-1].Positions, pos)
    } else {
        list = append(list, Posting{DocID: docID, Positions: []int{pos}})
    }
    idx.postings[term] = list
}

func main() {
    idx := &Index{postings: make(map[string][]Posting)}
    idx.Add("postgres", 1, 4)
    idx.Add("pooling", 1, 5)
    idx.Add("postgres", 2, 9)
    fmt.Println(idx.postings["postgres"])
}
Enter fullscreen mode Exit fullscreen mode

This toy version stores everything in memory on one machine. The real index is far too large for that, which leads to the next idea: sharding. The index is split into shards, and each shard lives on its own set of machines. There are two common ways to split it. One way is by document: each shard holds a slice of the documents, with a complete index over just those documents. The other way is by term: each shard holds the posting lists for a slice of the vocabulary. Document based sharding is the more common choice for web search, because a query then goes to every shard, each shard returns its best matches, and the results are merged. Term based sharding sends each query term to a different shard, which complicates merging and ranking. Either way, the point is the same: no single machine holds the whole index, and the work is spread across many machines that run in parallel.

The query path starts when your request reaches a front end server. The front end parses the query, normalizes it, and expands it: it handles spelling correction, recognizes synonyms, and identifies entities such as people, places, and products. This is where the system decides that a query about a recent event is a news query, or that a query with a location implies local results. The parsed query is then fanned out to the index shards. Each shard searches its portion of the index, scores its candidate documents, and returns its top results. A fan out like this only works if every shard answers quickly, because the total response time is set by the slowest shard, not the fastest. That constraint shapes the whole design: shards are kept small enough to answer in tens of milliseconds, machines are replicated so a slow or failed replica can be skipped, and strict timeouts cut off stragglers rather than letting one bad machine delay every query.

A simplified fan out in Go illustrates the pattern, with each shard queried in its own goroutine and results merged as they arrive:

package main

import (
    "fmt"
    "time"
)

type Result struct {
    ShardID int
    DocIDs  []int
}

func queryShard(id int, q string) Result {
    time.Sleep(20 * time.Millisecond)
    return Result{ShardID: id, DocIDs: []int{id * 100, id*100 + 1}}
}

func fanOut(q string, shards int) []Result {
    out := make(chan Result, shards)
    for i := 0; i < shards; i++ {
        go func(id int) {
            out <- queryShard(id, q)
        }(i)
    }
    results := make([]Result, 0, shards)
    for i := 0; i < shards; i++ {
        results = append(results, <-out)
    }
    return results
}

func main() {
    results := fanOut("postgres connection pooling", 4)
    fmt.Println(results)
}
Enter fullscreen mode Exit fullscreen mode

The real system adds timeouts, retries to a replica, and a merge step that combines scores across shards. The shape is the same: parallel calls, bounded waiting, merge at the end. This is the same fan out pattern you see in any distributed search or aggregation service, and it is worth learning well, because the failure modes are also the same. A shard that is slow every time needs investigation, not a longer timeout, and a merge step that waits for every shard will always be as slow as the worst one.

Once candidate documents arrive from the shards, the system ranks them. Ranking is not a single score but a pipeline of stages. The first stage is cheap and broad: it scores a large set of candidates using fast signals such as term frequency, document length, and whether the terms appear in the title. The second stage is expensive and narrow: it takes the top few hundred candidates and applies heavier signals, including machine learning models that consider hundreds of features. Those features include the quality and authority of the page, measured largely through the link graph, the freshness of the content, the match between the query and the page, and the behavior of users who issued similar queries in the past. The link graph matters because a page that many other pages link to, especially pages that are themselves well linked, is more likely to be authoritative than a page nobody references. Freshness matters because a query about a breaking event should return minutes old coverage, not a five year old article.

Caching sits at every layer, and it is what makes the latency budget possible. Popular queries are cached at the front end, so a query that thousands of people issue every day may never reach the index shards at all. The posting lists for common terms are cached in memory on the shard machines. The rendered result pages for common queries are cached closer to the user. There are also caches for spelling correction, for entity lookups, and for the snippets shown under each result. Caching works because query traffic is highly skewed: a small fraction of distinct queries accounts for a large share of total traffic. The long tail of rare queries still has to hit the index, but the cache absorbs the repeated load and leaves capacity for the queries that are genuinely new.

There are also systems around the edges that the query path depends on. The crawler has to respect robots rules, avoid overloading small sites, and prioritize pages that change often or are linked to frequently. The index has to be updated incrementally, because rebuilding hundreds of billions of pages from scratch is not feasible on a useful schedule. Fresh documents are added to the index in near real time, while the bulk of the index is rebuilt in batches. Spell checking, query understanding, and result presentation all have their own services, and each one has its own latency budget, because the total budget for the whole request is under a second, and every millisecond spent in one service is a millisecond unavailable to the others.

The lesson for backend engineers is not that you should build a search engine. It is that the patterns in this system show up everywhere at smaller scale. Precompute in the background instead of at request time. Use an inverted index when you need to find documents by their contents. Shard by document when you need parallel search with simple merging. Fan out with timeouts and replicas, and never let the slowest dependency set your latency without a bound. Rank in stages, cheap first and expensive second. Cache the hot paths, and measure the skew in your own traffic before deciding what to cache. None of these ideas is exotic on its own. The achievement is combining them so that a query across hundreds of billions of pages returns in the time it takes to blink. That combination, done carefully and measured relentlessly, is what system design at scale actually looks like.

Top comments (0)