Book Deep-Read · Software Engineering at Google · Chapter 17
Software Engineering at Google · Ch 17 · Code Search · Alexander Neubeck & Ben St. John · 2020
When you look someone up in your phone's contacts, you type two letters and they pop up; you never scroll page by page. Now imagine a contact list with billions of entries that changes every minute. That is the daily reality for Google's engineers: all of the company's code lives in one place, and it is too big to fit on any single computer. This chapter is about Google's internal "Code Search" website: why it is the tool engineers open most, and how it answers in the blink of an eye.
You might think programmers spend their days writing code. In fact they spend a huge amount of time reading it: where does this feature live? How did other people use it? Why was this line written this way, and who added it? Google measured it: about a third of searches are looking for "how did someone else do this" examples. So a tool built purely for reading turns out to be worth more than a better editor, and many engineers keep several Code Search tabs open next to their editor.
The usual approach is to download the code to your own machine and use your editor's search. Once the code no longer fits, that road is closed. Even when it fits, every person's computer has to build its own catalog from scratch, so starting up takes ages. Skip the catalog and search by brute force, and it is like flipping through every book in a library to find one sentence: slow enough that your mind wanders.
The payoff: a new hire can browse all of the company's code on day one with zero setup and find good examples to copy. Code locations mentioned in logs, error reports and docs all link straight here, so it becomes the company's "street address" for code. The honest cost: the "click anything" part requires analyzing the entire codebase, which is so expensive that it is refreshed only once a day and occasionally disagrees with code that was just changed.
Code is mostly read: build one company-wide catalog that stays fresh as code changes; only if it is fast, well ranked and complete will people trust it and use it.
Want to see how a trigram index replaces a 300,000-core brute-force search, how the ranking signals are designed, why "find everything" is harder than "find it fast", and why one index updates in seconds while the other takes a day? → Switch to the deep read
You think code search is "a bigger grep"; this chapter says it is really a search engine built for reading code. Scale forced Google to centralize the index in the cloud, interactivity demands that every operation stay under 200 ms, and what decides success is not speed but trust: index all the code, be able to return all the results, and still put the one you want first.
The second chapter of Part IV, "Tools", right after Version Control (Ch16): because there is one repository and one version, whole-repo search is both possible and necessary. It leads into Build Systems (Ch18), the Critique review tool (Ch19) and Large-Scale Changes (Ch22), which rely on it to find every call site. Real-world counterparts: GitHub code search, Sourcegraph, an IDE's "find in project".
Engineers spend much of their time understanding code. The chapter cites a Google study (Sadowski et al., FSE 2015) that splits search intent into five kinds: about one third is "How", seeing how others use an API; roughly a quarter is "What", browsing to understand what some code does; about 16% is "Where", locating a definition or a config; about 16% is "Why", why something was added or behaves as it does, often while debugging production; and about 8% is "Who / When", who introduced it and when.
At Google's size these questions can't be answered with local tools: the whole repo doesn't fit on one machine; even if it did, every IDE start would rebuild an index, and without one, grep is slow enough to break concentration. With well over a million code searches a day, the question is not whether to build a service but how to make it fast, complete and well ranked over a terabyte-scale corpus.
The authors give four reasons. Scale: a central index is built once and shared. A footnote does the math nicely: if every developer indexes in their own IDE, the codebase grows linearly over time and so does the number of IDEs, so total cost is roughly quadratic; central, incremental indexing is linear. A zero-setup global view: to start quickly and keep autocomplete free of noise, an IDE pushes you to shrink your visible scope; a web tool needs no project setup or build environment, lets you browse the whole repo at any time, and when you change an API you won't miss a dependent. Specialization: precisely because it is not an IDE, there is no text cursor, so every click can mean something (jump to definition, list usages) rather than move a caret.
The fourth is a platform effect. A Code Search link is the canonical "location" of a source file. The log viewer links "file:line" back to code; crash-report stack frames know which snapshot the binary was built from, so they link to that version and stay valid even after the code is refactored or deleted; docs can embed the latest snippet from head. In the other direction, repo-wide analyses (such as flagging uncalled "dead" code) surface their results right here, so tool authors don't need their own UI. An RPC API and plug-ins for vim, emacs and IntelliJ bring search and cross-references back into editors.
The authors draw on web search: breaking news changes fast, encyclopedia pages slowly, and each can be updated incrementally. The text search index is incremental: a commit reindexes only the files it touched, independently and in parallel, with a median commit-to-searchable latency under 10 seconds.
The cross-reference index can't be. It comes from Kythe, which instruments the build to extract a partial semantic graph per build rule, then merges them into one global graph optimized for go-to-definition and find-usages. Any change can affect the whole codebase, and in practice often touches thousands of files, so nearly every binary must be built or analyzed; extraction and post-processing are each about as costly as a full build (a footnote cites about six hours for Chromium in a distributed setup). So it is built once a day, and only one version is kept. The gap between the two is a "rare but recurring" source of user confusion; during an incident, an index that doesn't match the running code can hide the real cause or add irrelevant distractions.
Low latency isn't free, so the authors price it in engineer time: a million queries a day, each one second slower, is about 35 full-time engineers sitting idle every day (a million seconds ≈ 278 hours), while the search backend can be built and run by roughly a tenth of that. So at about 100,000 queries a day (fewer than 5,000 developers), the one-second argument alone is already close to break-even.
And the loss isn't linear: a UI feels responsive below 200 ms; after one second attention starts to drift; after ten more the developer has probably switched context entirely, which is costly. Hence the target: sub-200 ms end-to-end for every frequent operation. It also explains why, in a large repo, searching for a file often beats clicking through the tree: with the current file sent as context, the backend favors nearby directories, and a few keystrokes get you there.
First, the brute-force bill (the book's estimate): the index was about 1.5 TB, serving about 200 QPS at a median server-side latency under 50 ms. The RE2 regex library processes about 100 MB/s in RAM, so scanning 1.5 TB within 50 ms needs about 300,000 cores. A specialized substring search at about 1 GB/s cuts that tenfold, but 200 QPS means roughly 10 queries in flight in any 50 ms window, which takes you right back to 300,000 cores.
The way out is an index. The first was a trigram index: cut every file into all its consecutive three-character pieces and keep, for each piece, a list of files it occurs in. A query for Point intersects the lists for Poi, oin and int to get candidate files, then runs the real match on the candidates to confirm. Regexes work the same way: rewrite the regex automaton into a set of substrings that must all occur, and pre-filter with the index. Russ Cox later open sourced a simplified version.
It then moved to a custom suffix array design and on to today's token-based sparse n-gram design, more than 500 times more efficient than brute force while still answering regexes at speed. The two reasons for switching are pure engineering. First, n-grams run on Google's primary search stack and its standard inverted indices, inheriting everything the core search team built for index construction, encoding, serving and instant indexing, whereas just building and distributing custom suffix-array indices was a challenge of its own. It trades some performance for simplicity, though retrieval and scoring stay heavily customized. Second, the index moved from RAM to flash, which is at least an order of magnitude cheaper but at least two orders of magnitude slower to access. Trigrams need many large posting lists from flash; n-grams buy fewer, smaller lists at the price of a bigger index. One more detail: indexing the full revision history with a custom compression scheme raised resource use by a factor of only 2.5.
A small repo needs no ranking; at Google any short substring occurs thousands or millions of times, so without ranking you either read every hit or keep refining the query. A scoring function maps a file's features (signals) to a number, and there are two kinds. Query-independent signals are computed offline: how often a file is viewed (base-library utilities score high naturally), and how often it is referenced. Swap web links for include and import statements and you have PageRank, extendable up to build dependencies and down to functions and classes; together this is a file's "priority". The catch with views is a feedback loop (ranked high → viewed more → ranked higher) plus cold start for new files; the authors find mild over-showing harmless in practice. The catch with references is large migrations: when files move, indirection layers dilute their rank and view counts are lost, so the simplest fix is to boost them manually during the transition.
Query-dependent signals must be computed per query, so they may only use the query and data the index can hand over quickly: clean word-boundary matches get a boost and case is considered (searching Point, Point *p beats "appointed"), symbol and filename hits outrank plain content hits, and query terms found in the path (such as a project name) add more.
Before scoring comes retrieval: you cannot score every file, only the candidates you retrieved. The classic trap is searching for a class name: thousands of usages, one definition, and a fixed-size retrieval may stop before it ever reaches the definition. The fix is supplemental retrieval: rewrite the query into more specialized ones (only definitions and filenames), merge their hits into the candidate pool, and use partial scores so that only the most promising candidates get a full evaluation. Finally comes result diversity: if a function name exists in both Java and Python, don't fill the first page with one of them. The authors admit they do this less well than web search.
Nearly every trade-off in this chapter revolves around completeness, and the authors' stance is clear: err on the side of indexing too much.
Table 1 · Query expressiveness: more power is more useful and harder to index
| Approach | Can find | Index cost | Honest cost |
|---|---|---|---|
| Token (words) | Whole words | Stores a fraction of the source; supported by standard engines | Imprecise for code: can't search function(x) or === myClass; CamelCase / snake_case splitting is ill defined; case folding and stemming blur terms |
| Substring (trigram etc.) | Any character sequence | Index still smaller than the source | Low recall precision, so false hits must be filtered and queries slow down; size, latency and resources must be tuned to repo size and QPS |
| Regex | A class of patterns | Rewrite the automaton into substring searches on a substring index | No perfect regex index exists, so some queries degrade to brute force; but complex regexes are a small share |
| Brute-force grep | Everything | None | Fine for a few MB; 1.5 TB needs about 300,000 cores |
Table 2 · Three kinds of completeness, and what each costs
| Dimension | The easy way | Google's choice | Price paid |
|---|---|---|---|
| Which files | Drop huge files, generated JS | Drop only non-text content (keep the filename); limits set high, mainly against abuse | More resources; an unindexed file can't even trigger an "incomplete results" warning, and lost trust is hard to regain |
| All vs most relevant | Like web search, only consider top-ranked items | Shards ordered by file priority; normally read only high-priority matches per shard, but return all on request (alphabetical if wanted) | A more complex implementation and API, not a slower one |
| Which versions | Head only (as every IDE does) | Index the linear Piper history plus developer workspaces | About 2.5x resources; workspaces need brute-force search stitched onto the history index |
Row two is the counterintuitive one: the usual framing is "complete or fast, pick one", and Google turned it into "complexity versus capability". Refactoring, global search-and-replace and analysis tools must get every result, which is the fundamental difference from web search; meanwhile about a third of queries return fewer than 20 results anyway.
When a review asks "should we invest in internal developer tooling?", this chapter hands you a reusable formula: queries × seconds saved per query ÷ seconds in an engineer's day, compared against the people needed to build and run it. In an interview on designing code search or log search, being able to explain trigram indexing plus candidate verification, incremental versus full-rebuild freshness, how retrieval and scoring cooperate, and an "all results" mode puts you well beyond "just use Elasticsearch".
Industry evidence · publicly verifiable
① Code is mostly read: about 1/3 of searches look for usage examples, 1/4 for understanding, 16% for location, 16% ask why, 8% ask who and when.
② Four reasons for a separate web tool: scale (central indexing is linear, per-IDE indexing roughly quadratic), a zero-setup global view, a UX built for reading, and a platform that becomes the company's canonical address for code.
③ Price latency in people: a million queries × 1 s ≈ 35 engineers a day; target sub-200 ms end-to-end for frequent operations.
④ The text index is incremental (median <10 s to visibility); cross-references need nearly every binary built, so they're rebuilt daily and the gap confuses users.
⑤ Brute-forcing 1.5 TB needs about 300,000 cores; trigrams → suffix arrays → sparse n-grams, over 500x more efficient and still regex-capable.
⑥ A standard search stack trades some performance for simplicity; moving to flash demands fewer, smaller posting lists: the medium shapes the index.
⑦ Ranking = offline signals (views, references ≈ PageRank) + per-query signals (word boundaries, symbols, paths); retrieval needs supplemental queries.
⑧ Three completeness questions: index too much rather than too little; priority-ordered shards serve both "most relevant" and "all"; index full history and workspaces.
⑨ The test: only if it indexes all code, returns all results and ranks the wanted one first will a tool be trusted, and used.