Lesson 10 of 15
34. Design Search Autocomplete (Typeahead)

34.9 How do you cache suggestions?

3 min read+10 XP

The same prefix gets the same answer for everyone (no personalisation), which makes caching very effective:

  • Short prefixes dominate. In the chapter's code, prefixes of 4 characters or fewer carry about 22% of all keystroke requests, yet there are only a few hundred one- and two-character prefixes in total. Cache them everywhere: in the browser, at the CDN, in each suggest server's memory.
  • CDN caching with a TTL of minutes (Cache-Control: public, max-age=300) absorbs a large share of the 14,000 a second at the edge (Chapter 26).
  • Client cache: typing "data", backspacing to "dat" and retyping shouldn't call the server again.
  • Invalidation: when a new table is published, versioned cache keys (or short TTLs) roll it out within minutes; for an urgent removal (an offensive suggestion), purge it at the CDN by key.

Interviewer pushback:

  • "Doesn't caching stop trends from showing?" → Only for the TTL: a few minutes of lag on suggestions is fine. For an urgent removal, purge.

Memory code: "Same prefix, same answer: cache it at every layer."