Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Preventing Cache Penetration
with Bloom Filters.

Queries for keys that exist in neither Redis nor the database (e.g., negative IDs, scraped random UUIDs, or deleted SKUs) bypass the cache on every single request and hammer the database directly.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, block non-existent key floods using a multi-layer shield: strict edge format validation, a fast in-memory/Redis Bloom Filter (or Cuckoo Filter) pre-check, and short-TTL Negative Caching (`__NULL__` sentinels) for keys that pass the filter.

TL;DR30-second simplified summary
▾

Core Mechanics: GET /v1/items/{item_id} serves 25,000 QPS from Redis 7 (98% hit rate) backed by PostgreSQL 16 (3,000 QPS max).

Visual & Structural Flow: Depicts Edge Validation + In-Memory Bloom Filter + Short Negative Cache (Edge Regex/Range -> Bloom Filter (~24 MB) -> Redis Negative Cache -> Postgres (3k QPS)); 6x DB Overload vs. 99% In-Process Bloom Rejection (Botnet (18k QPS) -> Pod Bloom (24 MB) -> Redis (Neg Cache) -> Postgres (3k max)).

Trade-Offs & Production: Caching NULL in Redis for every missed ID without a Bloom filter lets a botnet spray 100M unique random IDs, bloating Redis RAM and evicting legitimate hot keys. Deploy a 3-layer defense within the 128 MB/pod budget: Layer 1 — Edge Format Validation: Reject -1, abc, and out-of-range IDs at the API gateway (400 Bad Request) with zero DB/Redis calls.

Failure Modes & Application: Bloom filters are a staple across storage and edge security architectures: Public User/Item Lookup APIs: Protects OLTP databases from scraping and credential-stuffing floods.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Preventing Cache Penetration Matters.

Why this matters: The mechanism: understand how Why Preventing Cache Penetration Matters works from first principles.

GET /v1/items/{item_id} serves 25,000 QPS from Redis 7 (98% hit rate) backed by PostgreSQL 16 (3,000 QPS max). When a botnet sends 18,000 QPS of random non-existent item_ids (-1, abc, or valid-looking missing IDs), every request misses Redis and hits Postgres—overwhelming the database by 6×.

Constraints: 20M valid items (~50k new/day), pod RAM budget <= 128 MB, Redis 32 GB.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of Cache Penetration Floods.

Why this matters: The problem: see what breaks without Real-World Impact of Cache Penetration Floods under real concurrency or scale.

Unlike cache stampedes (one hot key), cache penetration attacks non-existent keys:

  1. 100% Cache Misses: Neither Redis nor standard cache-aside populates anything for missing keys.
  2. 6× DB Saturation: 18,000 QPS of SELECT * WHERE id = ? saturates a 3,000 QPS Postgres cluster.
  3. Redis Eviction Pollution: Caching NULL values for millions of random botnet IDs evicts real hot product keys from Redis.
Multi-Layer Penetration Shield

Edge Validation + In-Memory Bloom Filter + Short Negative Cache

Edge Regex/RangeReject -1, abc at 0B…Bloom Filter (~24MB)20M items, 1% FPRRedis NegativeCacheNULL sentinel TTL=60sPostgres (3k QPS)<=180 QPS false pos1% FPR -> Neg Cache

1.Bloom Sizing: 20M items at 1% FPR = ~23.9 MB RAM (well under 128 MB/pod).

2.Zero False Negatives: If Bloom says 'not present', the item definitely does not exist.

3.New Item Sync: Update Bloom via CDC/Kafka stream + daily/hourly rebuild for deletions.

4.Negative Cache: Cache NULL for 60s for the 1% Bloom false positives.

A 24 MB Bloom filter blocks 99% of non-existent IDs in-process, while short-TTL negative caching absorbs the 1% false positives.

Engineering Decision Framework
Problem
How to implement Preventing Cache Penetration with Bloom Filters without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When traffic spikes expose hidden coupling, block non-existent key floods using a multi-layer shield: strict edge format validation, a fast in-memory/Redis Bloom Filter (or Cuckoo Filter) pre-check, and short-TTL Negative Caching (__NULL__ sentinels) for keys that pass the filter.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Preventing Cache Penetration with Bloom Filters experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Think of Naive Solution (and Why It Breaks) as the intuition layer for Preventing Cache Penetration with Bloom Filters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Caching NULL in Redis for every missed ID without a Bloom filter lets a botnet spray 100M unique random IDs, bloating Redis RAM and evicting legitimate hot keys. Using a HashSet<String> of 20M IDs in every pod consumes >1.5 GB RAM—violating the 128 MB pod RAM budget.

Design Trade-Off

Naive Solution (and Why It Breaks)

Before · Fixed TTL + Direct DB
  • Synchronized cache avalanche
  • 1,000 duplicate DB queries
  • Big-key event-loop freeze
After · Jittered TTL + Singleflight
  • 1 origin fetch per expired key
  • Randomized TTL spreads expiry
  • O(1) HashMap + DLL eviction
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: Edge Format Guard + 24 MB Bloom Filter + Short Negative Cache.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Deploy a 3-layer defense within the 128 MB/pod budget:

  • Layer 1 — Edge Format Validation: Reject -1, abc, and out-of-range IDs at the API gateway (400 Bad Request) with zero DB/Redis calls.
  • Layer 2 — Compact Bloom Filter (~24 MB): Size for n=20Mn = 20\text{M} items at p=1%p = 1\% FPR: m=−nln⁡p(ln⁡2)2≈191.7M bits≈23.9 MBm = -\frac{n \ln p}{(\ln 2)^2} \approx 191.7\text{M bits} \approx 23.9\text{ MB} with k=7k = 7 hash functions. 99% of valid-format missing IDs return 404 in < 0.1 ms. Sync new items (+50k/day) via Kafka CDC (or use a Cuckoo/Scalable Bloom Filter if deletes are frequent).
  • Layer 3 — Short-TTL Negative Cache: For the 1% Bloom false positives (~180 QPS, well under 3,000 QPS), cache a NULL sentinel in Redis with EX 60.
18k QPS Botnet Mitigation

6x DB Overload vs. 99% In-Process Bloom Rejection

Botnet (18k QPS)Pod Bloom (24 MB)Redis (Neg Cache)Postgres (3k max)1. GET /items/nonexistent_991822. 99% prob: not in set -> instant404!3. 1% false positive (~180 QPS)4. First miss queries PG -> cachesNULL (60s)

Bloom filter + negative caching cuts 18,000 QPS botnet traffic down to <180 QPS on Postgres.

import json, re

UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
NULL_SENTINEL = "__NULL__"

def get_item(redis, db, item_id: str):
    if not UUID_RE.match(item_id):
        raise BadRequestError("Invalid item_id format")

    if not redis.execute_command("BF.EXISTS", "items:bf", item_id):
        return None  # 99.9% of non-existent probes stop here

    cache_key = f"item:{item_id}"
    cached = redis.get(cache_key)
    if cached is not None:
        return None if cached == NULL_SENTINEL else json.loads(cached)

    row = db.fetch_item(item_id)
    if row is None:
        redis.set(cache_key, NULL_SENTINEL, ex=60)  # Absorb 0.1% FP repeats
        return None

    redis.set(cache_key, json.dumps(row), ex=3600)
    return row
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Bloom Filters & Penetration Guards Apply in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Bloom filters are a staple across storage and edge security architectures:

  • Public User/Item Lookup APIs: Protects OLTP databases from scraping and credential-stuffing floods.
  • LSM-Tree Databases (RocksDB / Cassandra): Avoids disk SSTable reads for non-existent keys.
  • URL Shorteners & Crawlers: Checks billions of seen URLs in a few hundred MB of RAM.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why can a Bloom filter safely return `404 Not Found` immediately when `might_contain(id)` returns `False`?

Recommended Learning Flow