Video in progress

Strong Junior 🏗️ System design

If lots of requests come in for IDs that don't exist in the database, why doesn't the cache help, and what do you do?

This is cache penetration: a missing key never gets into the cache, so every request goes straight to the DB. The fix is to cache the "not found" answer too with a short TTL, validate the ID format, and use a Bloom filter if needed.

📖 Answer

With cache-aside, the cache only stores values that were found. If someone runs a script hitting /products/999999999, /products/999999998..., every request is a miss, and every miss is a DB query. The cache is there, but the DB takes this traffic in full. It could be a bot or a bug in the front end.

The simplest fix is to cache the empty result too:

public Optional<Product> find(long id) {
    String key = "product:" + id;
    String cached = redis.opsForValue().get(key);
    if ("NULL".equals(cached)) return Optional.empty();   // it didn't exist before either
    if (cached != null) return Optional.of(fromJson(cached));

    Optional<Product> p = repo.findById(id);
    if (p.isPresent()) {
        redis.opsForValue().set(key, toJson(p.get()), Duration.ofMinutes(10));
    } else {
        redis.opsForValue().set(key, "NULL", Duration.ofSeconds(60)); // short TTL
    }
    return p;
}

The TTL has to be short: if the product is created later, the user shouldn't see it as "missing" for more than a minute.

Extra protection:

  • validate the ID up front — a negative or absurdly large number shouldn't reach the DB;
  • rate-limit lots of 404s from a single IP;
  • if there are very many keys, a Bloom filter: it answers "this ID definitely doesn't exist" without going to the DB.