Bugpit

Lessons › Core concepts

The crawler that empties the cache

A news site: 24,000 req/s, nearly all reads, and the cache usually answers 85% of them. Every hour a search engine crawler reads every old article once, and the database falls over.

Play this level

Free with an account. It runs in your browser: build the design, press Run, and watch what breaks.

The lesson

A cache holds only so much. When it's full and a new key arrives, it has to throw one out. Which one is its eviction policy.

Least recently used (LRU) throws out what nobody asked for in the longest time. It's the usual default, and it's great when popular pages stay popular.

A crawler breaks it. It asks for thousands of old articles once each. Each one is now the most recently used, so LRU throws out the front page to make room for an article nobody will read again. The popular pages miss, and those reads land on the database.

Least frequently used (LFU) counts how often each key is asked for. One read from the crawler can't outrank a front page read thousands of times a minute, so the popular pages stay.

What you have to achieve

24,000 requests a second at the busiest hour, 2% of them writes.

What you learn

Same machines, same bill, and the database stops falling over. How full a cache is matters less than what it chooses to keep. LFU has its own weak spot: when what's popular changes, yesterday's favourites linger.

Check yourself

A crawler reads every old article once. Why does an LRU cache suddenly miss on the front page?

Show the answer

Each crawled article becomes the most recently used, so the popular pages get thrown out. LRU only looks at when a key was last read. A flood of one-off reads looks recent, so it pushes out pages that are read all day.

A shop switches its cache to LFU. Then a new phone launches and becomes the most viewed page. What goes wrong?

Show the answer

Old favourites have huge counts, so the new page keeps getting thrown out. LFU trusts history. Keys that were popular last month still have big counts, so a new favourite struggles to stay in. Real LFU caches let counts fade over time for this reason.

Try it yourself

More in Core concepts

← The worker that woke up late One slow export jams a server →