Video in progress
Requests for IDs that don't exist in the database bypass the cache and overload the DB. What do you do?
This is cache penetration. It helps to cache the "not found" result with a short TTL, validate the ID format on input, and, at large scale, add a Bloom filter: if the filter says "no", you don't go to the DB at all.
📖 Answer
In plain cache-aside, if null isn't cached, GET /products/999999999 is a miss every time and a DB query every time. If a bot or crawler sends hundreds of thousands of such IDs, it makes no difference whether you have a cache.
The steps, simplest first:
- Validation: a negative, huge or malformed ID should get a 400 right in the controller.
- Cache the empty result:
if (dto == null) {
redis.opsForValue().set(key, "__NONE__", Duration.ofSeconds(60));
return null;
}
Keep the TTL short, and delete this key when the product is created.
-
A Bloom filter: the set of all existing IDs in a compact probabilistic structure. If it says "no", the ID definitely doesn't exist; if it says "yes", it probably does (a small percentage of false positives). In Redis Stack there are
BF.ADD/BF.EXISTS, or Redisson'sRBloomFilter. It doesn't support deletion, so it is rebuilt periodically. -
If it comes from a single IP, rate limiting.
In most cases 1 and 2 are enough. A Bloom filter pays off with a big catalog and a constant attack.
Sign up to mark studied questions and save your progress.