A crawler requests thousands of product ids that do not exist. Each request misses the cache and reaches the database. What can you do?
Sketch your own answer first, then compare it with the one below.
A strong answer
Cache the answer "not found" as well. This is called negative caching, and DNS standardised it long ago. The next request for the same missing id is answered from memory.
The details need care:
- Store an explicit marker, distinct from a cached null, so a reader can tell "known missing" from "not cached".
- Use a short TTL, perhaps 30 to 60 seconds, because the item may be created later. Also delete the marker when the item is created.
- Bound the damage. A crawler walking an unbounded id space will insert a marker for each id, fill the cache with entries nobody will read twice, and evict useful data. An admission policy that ignores one-off keys prevents that.
If most missing ids are invalid by construction, go one step earlier. A Bloom filter of existing ids, kept in memory in front of the cache, answers "definitely not present" without any lookup, at the cost of a small chance of a false "maybe present", which just falls through to the normal path.
Finally, rate-limit the offending client. Caching makes the abuse cheaper to absorb but does not stop it.
Sources
- Mark Andrews (1998). Negative Caching of DNS Queries (DNS NCACHE).
- Gil Einziger, Roy Friedman, Ben Manes (2017). TinyLFU: A Highly Efficient Cache Admission Policy.