Skip to content

Bloom filter

TL;DR

  • What: a probabilistic set: a bit array plus k hash functions. It answers "definitely not present" or "possibly present".
  • Why an architect cares: it avoids expensive lookups (database, network, disk) for items that are almost certainly absent, at a tiny memory cost.
  • Verdict: ideal as a pre-filter in front of an authoritative store. Never the source of truth on its own.

Problem and forces

Checking each incoming payment against a list of 1M+ references (duplicates, sanctions, blocked accounts) means a database round trip per message. Forces: latency, memory, accuracy, ability to delete.

Diagram

flowchart LR
  M[Incoming payment] --> B{Bloom filter<br/>in memory}
  B -- definitely NOT in list --> F[Fast path: continue]
  B -- maybe in list --> D[(Authoritative DB check)]
  D -- real match --> X[Block / flag]
  D -- false positive --> F

About 99% of traffic skips the database. Only "maybe" results pay for the exact check.

Sizing (memorise these)

  • Bits: m = −n · ln(p) / (ln 2)²
  • Hash functions: k = (m / n) · ln 2
n (items) p (false-positive rate) Memory k
1,000,000 1% ~1.14 MB 7
1,000,000 0.1% ~1.71 MB 10
10,000,000 1% ~11.4 MB 7

Measured with the Java implementation below: 1M items, a 1% target, and a 1.02% observed false-positive rate, with 0 false negatives.

Trade-offs

Attribute Impact Notes
Memory + About 10 bits per item at a 1% false-positive rate, regardless of item size
Latency + O(k) hashes; no I/O
Accuracy ± No false negatives; tunable false positives
Deletes − Not supported. Use a counting Bloom filter or a cuckoo filter, or rebuild
Evolvability − Must size for n up front; over-filling increases false positives quickly

Alternatives

Option Best at Weak at
HashSet / Redis SET Exact answers Memory: ~50–100+ bytes per item
Cuckoo filter Deletes; lower false positives at small p Insert failures when nearly full
Redis Bloom (RedisBloom module) Shared across instances Network hop
Database index only Simple, exact Latency per lookup

Practitioner insights

  • Use double hashing (Kirsch–Mitzenmacher): two good hashes simulate k hashes at no accuracy cost.
  • For time windows (e.g. duplicate checks over 24h), use rotating filters (current plus previous) instead of trying to delete.
  • With Kafka, keep one filter per partition. The key gives locality, so there's no shared state.
  • Rebuild from the source of truth on startup, or snapshot the bit array. Version it alongside the list.

Takeaway

  • One-liner: a memory-cheap "definitely not" check that shields an expensive exact lookup.
  • Heuristic: use it when misses dominate and a false positive only costs one extra lookup.
  • Review question: "What happens when n exceeds the design size, and how is the filter rebuilt?"
Java implementation (BloomFilter.java)
import java.nio.charset.StandardCharsets;

/**
 * A minimal, production-shaped Bloom filter.
 *
 * Build steps:
 *  1. Size it from the expected number of items (n) and the false-positive rate you can accept (p).
 *  2. Back it with a bit array of m bits.
 *  3. Derive k bit positions per item from ONE 64-bit hash, using double hashing.
 *  4. add() sets those k bits; mightContain() checks that all k are set.
 */
public final class BloomFilter {

    private final long[] words;      // the bit array, 64 bits per long
    private final long bitCount;     // m
    private final int hashCount;     // k

    public BloomFilter(long expectedItems, double falsePositiveRate) {
        if (expectedItems <= 0 || falsePositiveRate <= 0 || falsePositiveRate >= 1) {
            throw new IllegalArgumentException("need n > 0 and 0 < p < 1");
        }
        // Step 1: optimal sizing
        // m = -n * ln(p) / (ln 2)^2      (bits)
        // k = (m / n) * ln 2             (hash functions)
        double ln2 = Math.log(2);
        this.bitCount = (long) Math.ceil(-expectedItems * Math.log(falsePositiveRate) / (ln2 * ln2));
        this.hashCount = Math.max(1, (int) Math.round((double) bitCount / expectedItems * ln2));
        // Step 2: the bit array
        this.words = new long[(int) ((bitCount + 63) / 64)];
    }

    public void add(String item) {
        long hash = hash64(item);
        int h1 = (int) hash;
        int h2 = (int) (hash >>> 32);
        for (int i = 1; i <= hashCount; i++) {
            setBit(position(h1, h2, i));
        }
    }

    /** false = definitely not present; true = probably present. */
    public boolean mightContain(String item) {
        long hash = hash64(item);
        int h1 = (int) hash;
        int h2 = (int) (hash >>> 32);
        for (int i = 1; i <= hashCount; i++) {
            if (!getBit(position(h1, h2, i))) {
                return false;          // one unset bit is proof of absence
            }
        }
        return true;
    }

    // Step 3: double hashing (Kirsch–Mitzenmacher): g_i(x) = h1 + i * h2 mod m.
    // Gives k independent-enough positions from one hash, instead of k separate hash functions.
    private long position(int h1, int h2, int i) {
        long combined = (long) h1 + (long) i * h2;
        return Math.floorMod(combined, bitCount);
    }

    private void setBit(long index) {
        words[(int) (index >>> 6)] |= 1L << index;    // index & 63 is implied by Java's shift
    }

    private boolean getBit(long index) {
        return (words[(int) (index >>> 6)] & (1L << index)) != 0;
    }

    // 64-bit FNV-1a over the UTF-8 bytes, then a MurmurHash3 finaliser to spread the bits.
    // Never use String.hashCode() here: 32 bits and weak mixing push the false-positive rate up.
    private static long hash64(String item) {
        long h = 0xcbf29ce484222325L;
        for (byte b : item.getBytes(StandardCharsets.UTF_8)) {
            h ^= b;
            h *= 0x100000001b3L;
        }
        h ^= h >>> 33;
        h *= 0xff51afd7ed558ccdL;
        h ^= h >>> 33;
        h *= 0xc4ceb9fe1a85ec53L;
        h ^= h >>> 33;
        return h;
    }

    public long bitCount() { return bitCount; }
    public int hashCount() { return hashCount; }

    /** Demo: 1,000,000 items at a 1% target, then measure the real false-positive rate. */
    public static void main(String[] args) {
        int n = 1_000_000;
        BloomFilter filter = new BloomFilter(n, 0.01);
        System.out.printf("m = %,d bits (%.2f MB), k = %d%n",
                filter.bitCount(), filter.bitCount() / 8.0 / 1_048_576, filter.hashCount());

        for (int i = 0; i < n; i++) {
            filter.add("TRADE-" + i);
        }

        int missed = 0;
        for (int i = 0; i < n; i++) {
            if (!filter.mightContain("TRADE-" + i)) missed++;   // must always be 0
        }

        int falsePositives = 0;
        for (int i = n; i < 2 * n; i++) {
            if (filter.mightContain("TRADE-" + i)) falsePositives++;
        }

        System.out.printf("false negatives: %d%n", missed);
        System.out.printf("false-positive rate: %.3f%% (target 1%%)%n", 100.0 * falsePositives / n);
    }
}