Scrivio Interview library
DebuggingIntermediate7 min read · updated 13 November 2026

A product API caches products by id in Redis with a 95 percent hit ratio. Overnight the hit ratio fell to 62 percent, database queries per second rose eight times, and logs show many GET /products/{id} requests for ids that return 404, coming from a few hundred IP addresses.

What is happening, and how do you protect the database now and for the long term?

Someone is enumerating or scraping product ids that do not exist. Misses for absent ids are never cached, so every one of those requests reaches the database: this is cache penetration. Right away we rate limit or block the offending clients at the edge and cache not-found results for 30 to 60 seconds with a size limit; for the long term we reject impossible ids cheaply with validation and a Bloom filter of existing ids, use non-sequential public identifiers, add bot detection, and track hits, found misses and empty misses separately.

Why this question is asked

A falling hit ratio usually makes people suspect the cache: a bad TTL, an eviction problem, a deploy. Here the cache is working perfectly; it is being asked for things it can never hold. Interviewers like this scenario because the logs give the answer away if we read them carefully, and because the fix needs both an emergency response and lasting design changes. In this answer, we will read the symptoms, confirm the diagnosis, stop the bleeding, make absent ids cheap to reject, make ids harder to guess, and set up the metrics that would have caught it in minutes.

1Reading the Symptoms

Three facts arrived together overnight: the hit ratio fell from 95 to 62 percent, database queries per second rose eight times, and the logs show many GET /products/{id} requests returning 404 from a few hundred IP addresses. A cache that suddenly gets worse while the data has not changed usually means the requests changed, not the cache.

A simple model shows how this happens. Suppose normal traffic is 10,000 requests per second with 95 percent hits, so the database answers 500 per second. Now a scraper adds 4,000 requests per second for ids that do not exist. Those can never hit, so the hit ratio becomes 9,500 out of 14,000, about 68 percent, and database queries rise to 4,500 per second, nine times the normal load. The exact numbers depend on how many ids repeat and how expensive each query is, but the shape matches what we see.

2Confirming It Is Cache Penetration

Cache penetration is the name for requests that pass through the cache because the data does not exist, so there is nothing to cache. To confirm it, group the 404 responses by client IP and by id: a few hundred addresses producing most of the 404s, with ids that look sequential or random, is enumeration or scraping. If the service records misses that found nothing separately from misses that found data, that counter will have jumped while the second stayed flat.

It matters to confirm this before acting, because the fixes for an avalanche or a bad deploy, such as warming the cache, would do nothing here. There is nothing to warm.

3Protecting the Database Right Now

The first action is at the edge. Rate limit or block the offending clients at the CDN, WAF or API gateway, ideally with a rule on 404 rate per client rather than on total requests, so a scraper that hammers absent ids is slowed while normal users are untouched. Because the addresses are a few hundred, this is quick to deploy and immediately cuts most of the bad traffic.

The second action is in the service: cache not-found results. When the database finds nothing, we store a small marker with a short TTL, so repeated requests for the same id stop at the cache.

Java
Optional<Product> find(long id) {
String key = "product:" + id;
String cached = redis.opsForValue().get(key);
if ("NF".equals(cached)) return Optional.empty(); // cached not-found: no query
if (cached != null) return Optional.of(decode(cached));
Optional<Product> p = repository.findById(id);
if (p.isPresent()) redis.opsForValue().set(key, encode(p.get()), Duration.ofMinutes(30));
else redis.opsForValue().set(key, "NF", Duration.ofSeconds(45)); // short TTL for absence
return p;
}
// find(99999999) twice within 45 s -> 1 database query instead of 2

The TTL is short on purpose: a product can be created with that id, and we do not want it to look missing for long. The negative entries also need a bound. In Redis they can be kept small and given their own prefix to monitor; in a local cache, a separate Caffeine instance with a maximumSize keeps an attacker from filling memory with markers. Note that not-found caching only helps when ids repeat; a scraper that never asks for the same id twice still reaches the database, which is why the next layer matters.

4Rejecting Impossible Ids Cheaply

Many absent ids can be rejected without any lookup. If ids are positive integers below the current maximum, anything malformed, negative or far above the maximum is invalid on its face. For the rest, a Bloom filter of existing ids answers definitely absent for almost all unknown ids. It is a bit array with several hash functions: an id that was added always tests positive, and an id that was never added tests negative except for a small false positive rate we choose, for example 1 percent, which for 10 million ids takes about 12 MB.

The filter must be updated on create, before the new product is visible anywhere, or a brand-new product would be rejected as absent. Since standard Bloom filters cannot remove entries, deleted products stay possibly present until the filter is rebuilt from the database, which can run nightly.

Step throughHandling GET /products/{id}
  1. Edge: client over its 404 limit?Rate limit by client at CDN or gateway
    YesReject with 429NoPass to service
  2. Id well-formed and in range?Format and range check
    YesNext checkNoReturn 404 at once
  3. Bloom filter says possibly present?About 1 percent false positives
    YesLook in the cacheNoReturn 404 at once
  4. Cache hit or cached not-found?Product or NF marker
    YesAnswer from cacheNoQuery the database once

4 steps in order. Play them, or step through them one at a time.

5Making Ids Harder to Guess

Sequential public ids invite enumeration: if product 5001 exists, so do 5000 and 5002, and a scraper can walk the whole catalogue by counting. Using non-sequential public identifiers, such as random slugs or UUIDs, in URLs while keeping internal numeric keys in the database, turns enumeration into guessing in a space too large to search. It does not stop a scraper that crawls links, but it stops the cheap attack and makes most random ids absent by design, which the Bloom filter then rejects.

For a public catalogue, bot detection at the edge adds the remaining layer, recognising automated clients by behaviour and challenging them before they reach our services.

6Watching the Right Signals

This incident was found by its effect, the database load, rather than its cause. Separate counters for hits, misses that found data and misses that found nothing would have shown the cause directly: empty misses climbing from near zero to thousands per second. Add database queries per endpoint and the top clients by 404 rate, alert on sudden changes in any of them, and the next scraper is caught within minutes rather than by morning.

7Follow-up questions

What can go wrong with caching not-found results when products are created?

A product created during the TTL of a cached not-found marker looks missing until the marker expires, which can confuse the merchant who just created it. The create path should delete the marker for its id, the TTL should stay short, and with several cache layers or regions, each one needs that delete. The Bloom filter has a related trap: if the id is not added before the product is published, the filter rejects the new product as absent.

Why not just block the IP addresses and move on?

Because the scraper will come back from new addresses, and the service is still open to anyone who requests absent ids. Blocking stops this incident; not-found caching, validation and the Bloom filter stop the class of incident.

Could a Bloom filter replace the not-found cache?

Mostly, for ids that never existed. But false positives and deleted products still pass through, so the short-lived not-found cache remains a cheap second layer for whatever the filter lets by.

8Conclusion

In this answer, we saw that a falling hit ratio with a surge of 404s from a few hundred clients is cache penetration: absent ids that can never be cached reach the database on every request. We stopped it with edge rate limits on 404s and short-lived not-found caching with a size bound, made absent ids cheap to reject with validation and a Bloom filter updated on create, made enumeration harder with non-sequential public ids and bot detection, and set up metrics that separate hits, found misses and empty misses.

What to say in the interviewAbout 80 seconds aloud

Open with

The hit ratio fell because the requests changed, not the cache. A few hundred clients are asking for product ids that do not exist, probably enumerating or scraping, and a miss for an absent id is never cached, so every one of those requests goes to the database.

Then, if they want more

That is cache penetration. Right now I would rate limit or block those clients at the CDN or gateway, ideally with a limit on 404s per client, and start caching not-found results with a short TTL, 30 to 60 seconds, and a size limit so the markers cannot fill memory. That stops repeats of the same id.

For the long term, I would reject impossible ids cheaply: validate the format and range, and keep a Bloom filter of existing ids, updated on every create before the product is visible, so most unknown ids get a 404 without touching the cache or database.

I would move public URLs to non-sequential identifiers so the catalogue cannot be walked by counting, and add bot detection at the edge.

Finally I would track hits, misses that found data and misses that found nothing as separate metrics, plus database queries per endpoint and the top clients by 404 rate, with alerts, so the next one shows up in minutes.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is happening, and how do you protect the database now and for the long term?": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/33f8f11c30/