Bloom filters in front of a cache

Deriving the false positive bound, choosing the hash count, and implementing double hashing to drop negative lookups before they hit disk.

systemsalgorithmsmath
Contents (7)
  1. Lookup path
  2. Keeping filters in sync on writes
  3. False positive bound and optimal hash count
  4. Optimal number of hashes
  5. State transitions and avoided origin reads
  6. Double hashing implementation
  7. Operational constraints

In key-value stores and edge caches, a large share of tail latency comes from negative lookups. Every request for a missing key misses memory and falls through to disk or an origin server.

Placing a Bloom filter in front of the backing store lets a node reject missing keys in memory. Below is the request path, the false positive derivation, and a compact double-hashing implementation in TypeScript.

Lookup path

Incoming reads check the L1 memory cache first. On a miss, the node tests its local Bloom filter. When the filter reports absence, the node returns 404 immediately and skips origin I/O.

YesNoNoYesFoundFalse positiveClient GET keyL1 cache hit?Return cached valueIn Bloom filter?Return 404 immediatelyRead disk or originPopulate L1 cacheReturn valueLog false positive andreturn 404

Keeping filters in sync on writes

When multiple application instances write to shared storage, edge nodes update their filters from snapshots or an asynchronous event stream. Workloads that need deletes use a counting filter or rebuild a fresh bit array on a schedule.

PUT /items/k42Persist key and payloadAck (LSN 1084)Broadcast key hashSet k bit positions201 CreatedClientWrite APIPrimary StoreEdge NodeClientWrite APIPrimary StoreEdge Node

False positive bound and optimal hash count

Let mm be the bit array size, nn the number of inserted keys, and kk the number of independent hash functions. One hash leaves a given bit unset with probability 1−1m1 - \frac{1}{m}. After inserting nn keys, the probability that a bit remains 00 is approximately:

p0=(1−1m)kn≈e−kn/mp_0 = \left(1 - \frac{1}{m}\right)^{kn} \approx e^{-kn/m}

A missing key triggers a false positive when all kk probed positions are 11:

pfp≈(1−e−kn/m)kp_{\text{fp}} \approx \left(1 - e^{-kn/m}\right)^k

Optimal number of hashes

For fixed mm and nn, setting the derivative of g(k)=kln⁡(1−e−kn/m)g(k) = k \ln(1 - e^{-kn/m}) to zero gives the optimal hash count k∗k^* and minimum false positive rate:

k∗=mnln⁡2≈0.693⋅mn,pfp∗=(12)k∗≈(0.6185)m/nk^* = \frac{m}{n} \ln 2 \approx 0.693 \cdot \frac{m}{n}, \qquad p_{\text{fp}}^* = \left(\frac{1}{2}\right)^{k^*} \approx (0.6185)^{m/n}

Allocating 10 bits per key (m/n=10m/n = 10) with k∗=7k^* = 7 keeps the false positive rate near 0.82%0.82\%. More than 99% of negative lookups never reach the origin.

State transitions and avoided origin reads

If a TTL cache models item temperature across Hot, Warm, and Cold states, unit-time transitions form a stochastic matrix P\mathbf{P}:

P=[0.750.200.050.300.500.200.100.150.75],πP=π,∑i=13πi=1\mathbf{P} = \begin{bmatrix} 0.75 & 0.20 & 0.05 \\ 0.30 & 0.50 & 0.20 \\ 0.10 & 0.15 & 0.75 \end{bmatrix}, \qquad \boldsymbol{\pi}\mathbf{P} = \boldsymbol{\pi}, \quad \sum_{i=1}^{3} \pi_i = 1

With arrival rate λ(t)\lambda(t) and exponential residency decay μ\mu, the expected number of avoided origin reads over [0,T][0, T] is:

E[S(T)]=∫0Tλ(t) (1−pfp(t)) e−μt dt\mathbb{E}[S(T)] = \int_{0}^{T} \lambda(t)\,\bigl(1 - p_{\text{fp}}(t)\bigr)\,e^{-\mu t}\,dt

Because pfp(t)p_{\text{fp}}(t) climbs as nn grows, production caches rotate to a larger bit array before the rate crosses a fixed threshold such as 2%.

Double hashing implementation

Computing kk separate hash functions is unnecessary. By the Kirsch and Mitzenmacher result, two independent 32-bit hashes h1(x)h_1(x) and h2(x)h_2(x) generate kk bit indices via gi(x)=(h1(x)+i⋅h2(x)) mod mg_i(x) = (h_1(x) + i \cdot h_2(x)) \bmod m without hurting the asymptotic false positive rate.

export class BloomFilter {
  private readonly bits: Uint8Array;
  private readonly bitCount: number;
  private readonly hashCount: number;

  constructor(expectedItems: number, falsePositiveRate = 0.01) {
    const m = Math.ceil(
      (-expectedItems * Math.log(falsePositiveRate)) / Math.LN2 ** 2,
    );
    const k = Math.max(1, Math.round((m / expectedItems) * Math.LN2));
    this.bitCount = m;
    this.hashCount = k;
    this.bits = new Uint8Array(Math.ceil(m / 8));
  }

  private hashPair(key: string): [number, number] {
    let h1 = 0x811c9dc5;
    let h2 = 0x01000193;
    for (let i = 0; i < key.length; i += 1) {
      const code = key.charCodeAt(i);
      h1 = Math.imul(h1 ^ code, 0x01000193) >>> 0;
      h2 = Math.imul(h2 ^ (code + i), 0x85ebca6b) >>> 0;
    }
    return [h1, h2 || 1];
  }

  add(key: string): void {
    const [h1, h2] = this.hashPair(key);
    for (let i = 0; i < this.hashCount; i += 1) {
      const pos = (h1 + i * h2) % this.bitCount;
      this.bits[pos >>> 3] |= 1 << (pos & 7);
    }
  }

  mightContain(key: string): boolean {
    const [h1, h2] = this.hashPair(key);
    for (let i = 0; i < this.hashCount; i += 1) {
      const pos = (h1 + i * h2) % this.bitCount;
      if ((this.bits[pos >>> 3] & (1 << (pos & 7))) === 0) {
        return false;
      }
    }
    return true;
  }
}

Operational constraints

  • Replication lag after a write can cause temporary false negatives. Reads inside that window must bypass the filter or query through a short grace period.
  • When memory bandwidth dominates, a blocked Bloom filter fits all kk probes inside a single 64-byte CPU cache line.
  • Monitor bit fill ratio and rotate before it exceeds 50%, where false positives rise sharply.