Bloom filter

A compact bit array that answers "definitely not present" or "probably present" using several hash functions: tiny memory, no false negatives.

Description

A Bloom filter tests whether an item might be in a set, using far less memory than storing the items. It's an array of m bits, all starting at 0, and k hash functions, each mapping an item to one of the bit positions.

To add an item, hash it k times and set those k bits to 1. To check an item, hash it the same way: if any of the k bits is 0, the item was definitely never added. If all are 1, it was probably added, but those bits may have been set by other items: a false positive.

False positives get more likely as the filter fills up, but you can size it in advance. With about 10 bits per item and 7 hash functions, the false-positive rate is around 1%, regardless of how large the items themselves are.

Bloom filters are used to avoid expensive lookups that would usually fail: databases such as Cassandra and RocksDB check them before reading from disk, browsers used them for malicious-URL lists, and CDNs use them to decide what's worth caching. A standard Bloom filter can't delete items; counting Bloom filters and cuckoo filters can.

How it works

00110203140506170809110011012013114015h1h2h3

16 bits after adding two words. Checking "cat": its three hash positions are all 1, so it's probably present.

  1. index 0: 0
  2. index 1: 1
  3. index 2: 0
  4. index 3: 0
  5. index 4: 1
  6. index 5: 0
  7. index 6: 0
  8. index 7: 1
  9. index 8: 0
  10. index 9: 0
  11. index 10: 1
  12. index 11: 0
  13. index 12: 0
  14. index 13: 0
  15. index 14: 1
  16. index 15: 0
16 bits after adding two words. Checking "cat": its three hash positions are all 1, so it's probably present.

Complexity

OperationAverageWorst
Addk hash functions, independent of the number of items.O(k)O(k)
Check membershipO(k)O(k)
DeleteUse a counting Bloom filter or cuckoo filter.not supportednot supported

Space: O(m) bits: about 9.6 bits per item for a 1% false-positive rate

The false-positive rate is roughly (1 − e^(−kn/m))^k for n items. The optimal number of hash functions is k ≈ (m/n) · ln 2.

TypeScript implementation

A Bloom filter sized from the expected number of items and target false-positive rate, using double hashing to derive k positions from two hashes.

bloom-filter.ts
// A Bloom filter sized for n items and a target false-positive rate.
// k bit positions come from two hashes: position_i = h1 + i * h2 (double hashing).

function fnv1a(s: string, seed: number): number {
  let h = 0x811c9dc5 ^ seed;
  for (let i = 0; i < s.length; i++) {
    h ^= s.charCodeAt(i);
    h = Math.imul(h, 0x01000193) >>> 0;
  }
  return h >>> 0;
}

export class BloomFilter {
  private bits: Uint8Array;
  readonly m: number;
  readonly k: number;

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

  private *positions(item: string): Generator<number> {
    const h1 = fnv1a(item, 0);
    const h2 = (fnv1a(item, 0x9e3779b9) | 1) >>> 0; // `| 1` makes it odd, `>>> 0` keeps it unsigned
    for (let i = 0; i < this.k; i++) yield (h1 + i * h2) % this.m;
  }

  add(item: string): void {
    for (const p of this.positions(item)) this.bits[p >> 3] |= 1 << (p & 7);
  }

  /** false = definitely not added; true = probably added. */
  mightContain(item: string): boolean {
    for (const p of this.positions(item)) if (!(this.bits[p >> 3] & (1 << (p & 7)))) return false;
    return true;
  }
}

export function demo(): string[] {
  const n = 10_000;
  const seen = new BloomFilter(n, 0.01);
  for (let i = 0; i < n; i++) seen.add(`https://example.com/page/${i}`);
  let falsePositives = 0;
  const trials = 100_000;
  for (let i = 0; i < trials; i++) if (seen.mightContain(`https://example.com/other/${i}`)) falsePositives++;
  return [
    `${n.toLocaleString("en")} URLs in ${seen.m.toLocaleString("en")} bits (${(seen.m / 8 / 1024).toFixed(1)} KB), k = ${seen.k}`,
    `every added URL found: ${Array.from({ length: n }, (_, i) => `https://example.com/page/${i}`).every((u) => seen.mightContain(u))} (never a false negative)`,
    `false-positive rate on ${trials.toLocaleString("en")} new URLs: ${((falsePositives / trials) * 100).toFixed(2)}% (target 1%)`,
  ];
}

When to use it

Use it when

  • You want to skip expensive lookups for items that are almost certainly absent: disk reads, network calls, database queries.
  • Memory is tight and an occasional false positive is acceptable.
  • Deduplicating huge streams approximately, such as "have we crawled this URL?".

Avoid it when

  • You need exact answers: use a hash set.
  • You need to delete items or list them.
  • The set is small enough to keep exactly in memory anyway.

Pitfalls

  • Undersizing the bit array, so the false-positive rate climbs far above the target as items are added.
  • Correlated hash functions, which behave like fewer functions and raise false positives.
  • Treating "probably present" as present: always confirm with the real data source when it matters.
  • Removing by clearing bits, which can create false negatives for other items.

Alternatives

Hash set

Choose it when you need exact membership and can afford the memory.

Cuckoo filter

Choose it when you need deletions and similar memory efficiency.

HyperLogLog

Choose it when you only need to count distinct items, not test membership.