Skip to content

Bloom Filters & Probabilistic Structures ​

"Analysis of the paradigm problem demonstrates that allowing a small number of test messages to be falsely identified as members of the given set will permit a much smaller hash area to be used without increasing reject time." — Burton H. Bloom, Space/Time Trade-offs in Hash Coding with Allowable Errors, Communications of the ACM, 1970

Summary: A Bloom filter answers "is this key in the set?" with "definitely not" or "probably yes", in about ten bits per key; its relatives count distinct items (HyperLogLog), frequencies (Count-Min sketch) and percentiles (t-digest) in a few kilobytes. Focus: Sizing and the false positive formula, the filter family (counting, scalable, cuckoo, quotient, xor, Ribbon), the sketches, and exactly where PostgreSQL, Cassandra, RocksDB, Redis, Parquet and analytics engines use them. Learning goal: Decide when an approximate answer is safe, size a filter from a false positive budget, read the filter metrics of your database, and know when not to use any of this.

This page is the complete reference for probabilistic data structures in database work: the Bloom filter and every variant you will meet, the cardinality, frequency and quantile sketches, and the products that ship them. The B-tree/LSM background is in Storage Engines and the index catalogue is in Indexing; here we only explain the filters those pages mention in one line. The generic distributed-cache angle continues in Redis and Storage & Data Scaling.

Page map ​

If you are looking forGo to
Every structure in one tableEverything in one minute
Why approximate answers are a good tradeWhy probabilistic structures exist
Bloom 1970 and the later papersWhere it comes from
How a Bloom filter works, sizing, the formulaBloom filter, Sizing and the FPR formula, k hash functions
Deletion, growth, newer filtersCounting, Scalable, Cuckoo, Quotient, Xor and Ribbon
Distinct counts, frequencies, percentiles, similarityHyperLogLog, Count-Min, t-digest, MinHash and LSH
PostgreSQL bloom extension and BRINPostgreSQL bloom index, BRIN
LSM engines, Cassandra, RocksDBLSM SSTable filters
Analytics join filters, partition pruning, ParquetAnalytics engines
Cache admission, distributed cachesCaches and TinyLFU
Per-product tableWhat each product really does
Fixes in SQL, Go, LaravelSolving the classic problems
Which structure for which questionChoosing a structure
Monolith to distributedIn architecture
Reproduce itLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The structures. Every row is unpacked later.

StructureQuestion it answersErrorMemoryDelete?Used in
Bloom filterIs x in the set?False positives only; never false negativesAbout 9.6 bits per key at 1% (1.44 log2(1/p))NoRocksDB, Cassandra, HBase, Parquet, Redis Bloom, Spark runtime filters
Counting Bloom filterSame, with removalFalse positives; counters can overflowAbout 4x a Bloom filter (4-bit counters)YesSummary caches, teaching
Scalable Bloom filterSame, set size unknownFalse positives, bounded by a tightening seriesGrows by stacking filtersNoRedis BF.RESERVE (default expansion), libraries
Cuckoo filterSame, with removalFalse positives; insert can fail when full(log2(1/p)+3)/load bits per keyYesRedis Cuckoo, Go and Rust libraries
Quotient filterSame, mergeable and resizableFalse positivesSlightly above Bloom, cache-friendlyYesFlash and on-disk stores, research systems
Xor / binary fuse filterSame, immutable setFalse positivesAbout 9.84 bits per key (Xor8), less for fuseNo (built once)Static indexes, SSTable-like files
Ribbon filterSame, immutable setFalse positivesAbout 30% less than BloomNo (built once)RocksDB NewRibbonFilterPolicy
HyperLogLogHow many distinct items?Relative error 1.04/sqrt(m), 0.81% in Redis12 KB max in RedisNo (but mergeable)Redis PFADD, PostgreSQL extension postgresql-hll, BigQuery HLL_COUNT, Presto/Trino approx_distinct
Count-Min sketchHow often did x occur?Over-estimates only, by at most eps*Nw x d countersDecrement only for non-negative streamsRedis CMS.*, heavy hitters, TinyLFU
t-digestWhat is the p99?Small relative to min(q, 1-q)Hundreds of centroidsNoRedis TDIGEST.*, Elasticsearch percentiles
MinHash / LSHHow similar are two sets?Estimate of Jaccard similarityk signatures per setn/aNear-duplicate detection, search
PostgreSQL bloom indexWhich heap rows match many equality columns?Lossy, rechecked on heapSignature per row (default 80 bits)Normal index maintenanceOne index for many column combinations
BRINWhich block ranges can hold the value?Lossy, recheckedOne summary per page rangeNormalHuge, physically ordered tables

The error directions. The most important thing to remember is which way a structure is wrong.

StructureWhen it says "yes" / a numberWhen it says "no"
Bloom, Cuckoo, Xor, Ribbon, QuotientMight be wrong (false positive)Always right
Counting Bloom (after a bad delete)Might be wrongCan be wrong if you delete something never inserted
HyperLogLogWithin about 1-2% of the truth, either directionn/a
Count-Min sketchNever below the truth, possibly aboven/a
t-digestWithin a small rank error, best at the tailsn/a

Why probabilistic structures exist ​

Exact answers cost memory proportional to the data. An exact set of one billion 16-byte keys needs 16 GB plus overhead; a Bloom filter that answers "definitely not there" for 99% of absent keys needs about 1.2 GB. An exact distinct counter needs the whole set; HyperLogLog needs 12 KB. The deal is always the same: give up a bounded, known amount of accuracy and get memory that does not grow with the data, or grows far slower.

Exact structureProbabilistic structure
Memory grows with the number of itemsMemory fixed by the error budget
One lookup may touch disk or the networkOne lookup touches a few cache lines in RAM
Never wrongWrong in a known direction by a known amount
Hard to merge across shardsMany are mergeable (bitwise OR, register max)
Right when the answer is a decision (money, access)Right when the answer is a filter or an estimate

An everyday picture. A club bouncer has a short list of "tonight's guests" written as a rough fingerprint: height, hair colour, jacket colour. If you do not match the fingerprint you are certainly not on the list and the bouncer need not open the big guest book. If you match, the bouncer opens the book and checks properly. Sometimes a stranger happens to match and the book check turns them away; that wasted check is the false positive. The bouncer never turns a real guest away without checking, so there are no false negatives. The whole structure is cheap because the book is opened only for "maybe" visitors.

Three common misunderstandings, up front.

  1. "A Bloom filter can tell me an item IS in the set." It cannot; it can only tell you an item is definitely not in the set. A yes is a "maybe" that must be confirmed by the real source of truth.
  2. "These are only for huge companies." The same logic saves one disk read per missing key in SQLite-sized caches, in a Laravel app that guards a hot lookup, or in a PostgreSQL table with ten searchable columns.
  3. "An approximate counter is inaccurate, so it is unsafe." HyperLogLog's error is a documented, constant-percentage number (0.81% in Redis). Unsafe is using it for billing; fine is using it for a dashboard.

Where it comes from ​

Burton Bloom published the idea in Communications of the ACM in 1970. He considered "testing a series of messages one-by-one for membership in a given set of messages" and introduced the "reject time" (the time to classify a test message as a non-member) as the quantity to optimise. His sample application is automatic hyphenation: a few simple rules hyphenate 90 percent of words correctly, a disk-resident dictionary holds the exceptions, and the filter keeps the program from touching the disk for the words that are not exceptions. The paper already states the two properties that still define the structure: false positives are allowed, and the "hash area" can be much smaller than with conventional hash coding. The paper names two methods; the second (one shared bit area, several hash probes per message) is what everyone calls a Bloom filter today.

"Analysis of the paradigm problem demonstrates that allowing a small number of test messages to be falsely identified as members of the given set will permit a much smaller hash area to be used without increasing reject time." — Bloom 1970 (read from the CACM PDF, p. 422)

The later papers named on this page, with what each added:

YearPaperWhat it added
1970Bloom, CACMThe filter, reject time, the space/error trade-off
1998-2000Fan, Cao, Almeida, Broder, Summary CacheCounting Bloom filters for web-cache directories (secondary source, not read for this page)
2005Cormode & Muthukrishnan, An Improved Data Stream Summary: The Count-Min SketchFrequency estimates in sublinear space
2006Kirsch & Mitzenmacher, Less hashing, same performancek probes from two hashes (double hashing), used in this page's Go code (secondary)
2007Flajolet, Fusy, Gandouet, Meunier, HyperLogLogNear-optimal cardinality estimate with about 1.04/sqrt(m) error
2007Almeida et al., Scalable Bloom FiltersFilters that grow with the data (secondary)
2012Bender et al., Don't Thrash: How to Cache Your Hash on FlashQuotient filter (secondary)
2014Fan, Andersen, Kaminsky, Mitzenmacher, Cuckoo FilterDeletion, better space at low error rates
2017Einziger, Friedman, Manes, TinyLFUFrequency-based cache admission with a Count-Min sketch
2019Graf & Lemire, Xor FiltersFaster and smaller static filters
2019Dunning & Ertl, Computing Extremely Accurate Quantiles Using t-DigestsPercentiles that are best at the tails

Claims in the "(secondary)" rows come from the literature's standard citations and the vendor docs below, not from a fresh reading of those papers.

The Bloom filter ​

How it works Must-know ​

In plain words: Keep a long row of bits, all zero. To add a key, run it through k different hash functions, each giving a bit position, and set those k bits to 1. To ask about a key, compute the same k positions: if any bit is 0 the key was never added; if all are 1 it was probably added.

Common misunderstanding: "If all k bits are 1, the key is in the set." The bits could have been set by other keys. The more keys you add, the more bits are 1 and the likelier a stranger's k bits are all 1 by accident. That accident is the false positive.

Definition: A Bloom filter is an array of m bits and k independent hash functions h1..hk mapping a key to [0, m). add(x) sets bits h1(x)..hk(x); contains(x) returns true iff all those bits are 1. There are no false negatives because bits are never cleared; the false positive rate rises with the number of inserted keys n.

00110203140506170819010011112013014115016017018019Insertadd("alice")add("bob")m = 20 bits, k = 3 hash functions: h1(x), h2(x), h3(x) each pick a bit positionQuerycontains("carol")bit 2 is 0: definitely NOT in setcontains("dave")bits 4, 9, 12 all 1: "probably" (false positive)
Step  Action                              Bits touched        Result
1     add("alice")                        1, 7, 12            set to 1
2     add("bob")                          4, 9, 15            set to 1
3     contains("carol")                   2, 7, 17            bit 2 is 0 -> definitely absent
4     contains("dave")                    4, 9, 12            all 1 -> "probably present"
5     real lookup for dave                -                   not found: that was a false positive
6     contains("alice")                   1, 7, 12            all 1 -> present (never a false negative)

Real scenarios: a username-availability check that skips the database for names that cannot exist; a web crawler that skips URLs it has probably seen; an LSM engine skipping SSTables; a CDN that only caches an object the second time it is requested; a payments service that checks "have we seen this idempotency key?" before a database lookup (the filter only short-circuits the "never seen" case).

What provides it:

ProductWhere the Bloom filter lives
RocksDB / LevelDBPer SSTable (full filter) or per 2 KB block in the old format
Cassandra / ScyllaDBPer SSTable, Filter.db component, off-heap
HBasePer HFile, row or row+column blooms
PostgreSQLbloom contrib index; BRIN *_bloom_ops operator classes
Redis Open SourceBF.RESERVE, BF.ADD, BF.EXISTS (the Bloom module)
ParquetSplit-block Bloom filters per column chunk
MySQL InnoDB, SQL Server, Oracle, SQLite, MongoDBNo user-facing Bloom index; Oracle and SQL Server use Bloom filters internally in parallel hash joins

Fix / how to use it:

sql
-- PostgreSQL: a Bloom index is an ordinary CREATE INDEX with a method
CREATE EXTENSION IF NOT EXISTS bloom;
CREATE INDEX tickets_bloom ON tickets USING bloom (status, priority, assignee_id, team_id);
go
// Go: the teaching filter from this page, sized for 1M keys at 1%.
f := bloom.NewForCapacity(1_000_000, 0.01)
f.Add("user:42")
if f.MayContain("user:42") { /* confirm against the real store */ }

The full Go package is in the Go section. In Laravel, the same idea sits in front of a repository lookup (see Laravel).

Sizing and the false positive formula {#sizing} Must-know ​

In plain words: More bits per key means fewer false positives, with sharply diminishing returns. About 10 bits per key gives about 1% false positives; each extra 4.8 bits divides the rate by ten.

Common misunderstanding: "I can add more keys than I planned." You can, but the false positive rate climbs fast. A filter sized for 1 million keys at 1% reaches about 16% when 2 million are added with the same bits.

Definition: For n inserted keys, m bits and k hashes, the false positive rate (FPR) is approximately

p = (1 - e^(-k n / m))^k

With the optimal k the formulas rearrange to:

k_opt = (m / n) * ln 2                 (about 0.693 * bits per key)
m     = - n * ln p / (ln 2)^2          (bits needed for n keys at rate p)
bits per key = - ln p / (ln 2)^2 = 1.44 * log2(1 / p)

The factor 1.44 is the overhead against the information-theoretic minimum of log2(1/p) bits per key: the Cuckoo filter paper states "a space-optimized Bloom filter imposes a 44% space overhead over the information-theoretic lower bound". At the optimum, exactly half of the bits are 1.

Target FPR pBits per key (1.44 log2(1/p))Optimal kMemory for 1 billion keys
10%4.830.6 GB
1%9.671.2 GB
0.1%14.4101.8 GB
0.01%19.2132.4 GB
0.001%24.0173.0 GB

The teaching Go program (measured) confirms the formula: at 10 bits per key and k=7 the formula predicts 0.82% and the measurement over 200,000 absent keys is 0.80%.

Step  n added   m bits   k    fill ratio   theoretical FPR
1     100,000   1.0M     7    ~0.50        0.0082
2     200,000   1.0M     7    ~0.75        ~0.14   (same bits, double the keys: 17x worse)

The second row is arithmetic from the formula, not a measurement. The point: over-filling a Bloom filter degrades it much faster than linearly.

Choosing k, hashing and cache lines {#k-hashes} Important ​

In plain words: k is how many bits each key sets. Too few and strangers collide easily; too many and the array fills up with ones. There is an optimum, and in practice you compute k from the bits-per-key budget.

Common misunderstanding: "I need k independent hash functions, so k separate hash computations." No. Kirsch and Mitzenmacher showed that two hashes are enough: probe i is h1(x) + i * h2(x) mod m. The teaching Go code does exactly this from one 64-bit hash.

Definition: k_opt = (m/n) ln 2. Practical engines add two more tricks. First, probes are confined to one CPU cache line (RocksDB "limits the probe bits for a key to be all within the same CPU cache line"), costing a small FPR increase for far fewer cache misses; the RocksDB wiki computes about 0.95% against 0.84% for a classic filter at 10 bits per key. Second, hashing uses 64 bits so very large filters do not saturate (RocksDB's format_version=5 fixed an older 32-bit limitation).

SettingEffectProduct knob
Bits per keySpace vs false positivesRocksDB NewBloomFilterPolicy(10), Cassandra bloom_filter_fp_chance, Redis BF.RESERVE key error_rate capacity
kDerived from bits per keyNever set by hand in these products
Whole key vs prefixPrefix filters serve Seek but have higher FPRRocksDB whole_key_filtering, prefix_extractor
Filter per file vs per block vs partitionedMemory vs cache churnRocksDB full filter, partitioned filter, cache_index_and_filter_blocks
Memory fragmentationSpend allocator slack on lower FPRRocksDB optimize_filters_for_memory

Counting Bloom filter Good to know ​

In plain words: Replace each bit with a small counter. Adding increments k counters; deleting decrements them; a key may be present if all k counters are above zero.

Common misunderstanding: "So Bloom filters can delete after all." Only if you delete keys you really inserted; deleting a never-inserted key decrements counters that belong to others and creates false negatives, the one thing a Bloom filter must never do. Counters also overflow.

Definition: An array of m counters (the Cuckoo filter paper notes "the counter consists of four or more bits"), so a counting filter costs about four times the memory of a plain Bloom filter.

Step  Action                 Counters (positions 3, 8, 11)
1     add("a")               3:1  8:1  11:1
2     add("b") shares 8      3:1  8:2  11:1   (b also touches other cells)
3     remove("a")            3:0  8:1  11:0
4     contains("b")          still true, because its counters are untouched
5     remove("zzz")          if zzz was never added, counters under others fall -> false negatives later

Real scenario: a membership table of "currently online" devices where entries expire. Today a Cuckoo filter or a periodically rebuilt Bloom filter is usually preferred.

What prevents misuse: application-level discipline (only remove what you added) or switching to a Cuckoo filter, which stores fingerprints and can verify a delete target.

Scalable Bloom filter Good to know ​

In plain words: When the filter fills up, start a second, bigger filter and keep checking the old ones too.

Common misunderstanding: "Growing is free." A query now probes every sub-filter, and each sub-filter has to be created with a tighter FPR so the sum stays bounded. Lookups slow down and memory grows by the expansion factor.

Definition: Almeida et al. (2007) chain filters with geometrically tightening error rates so the total FPR stays below a bound. Redis Bloom implements this: BF.RESERVE key error_rate capacity [EXPANSION n] [NONSCALING]; when the capacity is reached a new sub-filter is added unless NONSCALING is set, in which case further adds fail.

Step  Command                                         Meaning
1     BF.RESERVE users:seen 0.001 1000000            Target 0.1% FPR for 1M keys
2     BF.ADD users:seen "u-1"                        Added to sub-filter 1
3     (1M keys later) BF.ADD users:seen "u-1000001"  Sub-filter 2 created, bigger and tighter
4     BF.EXISTS users:seen "u-1"                     Probes sub-filter 1 and 2

Fix: size from the real forecast when you can; use the scalable mode as a safety net rather than a plan. In PostgreSQL, Cassandra and RocksDB filters are per immutable file, so growth does not arise: a new file gets a new filter sized for exactly its keys.

Cuckoo filter Important ​

In plain words: Instead of setting bits, store a short fingerprint of each key in one of two possible buckets. A lookup checks the two buckets for the fingerprint. Because the fingerprint is stored you can remove it again.

Common misunderstanding: "A Cuckoo filter is just a better Bloom filter." It is more space-efficient than a Bloom filter when the target FPR is below about 3% (the paper's figure) and when you need deletion, but it can reject an insert when it is full, deleting an item that was never inserted can remove another item's identical fingerprint, and inserting the same item many times can overflow its buckets.

Definition: Fan et al. (2014): a table of buckets, each with a few fingerprint slots (typically four); partial-key cuckoo hashing makes the alternate bucket computable from the first bucket and the fingerprint alone (i2 = i1 XOR hash(fingerprint)), so entries can be "kicked" to their other bucket without the original key. Space per item is (log2(1/p) + 3) / load factor bits with load about 95%. The paper's headline: "cuckoo filters outperform previous data structures that extend Bloom filters to support deletions substantially in both time and space".

Step  Action                              Detail
1     insert(x)                           fingerprint f = fp(x); buckets i1 = h(x), i2 = i1 XOR h(f)
2     bucket i1 has a free slot           store f in i1. Done.
3     both buckets full                   evict a random fingerprint g from i1, put f there
4     re-home g                           g goes to its alternate bucket i1 XOR h(g); may evict again
5     after ~500 kicks                    give up: the filter is full, insert returns false
6     delete(x)                           remove one matching fingerprint from i1 or i2

Real scenario: "has this user already been targeted by campaign X?" with users being removed when they unsubscribe (the Redis docs use exactly this ad-campaign example); a dedup layer where items expire.

What provides it: Redis Open Source CF.RESERVE, CF.ADD, CF.ADDNX, CF.EXISTS, CF.DEL, CF.COUNT; libraries in Go and Rust.

> CF.RESERVE campaign:42 1000000
> CF.ADD campaign:42 "user:7"
> CF.EXISTS campaign:42 "user:7"
> CF.DEL campaign:42 "user:7"

Quotient filter Good to know ​

In plain words: Hash the key, split the hash into a "quotient" (which slot) and a "remainder" (the stored value), and keep the remainders sorted in a compact table with three metadata bits per slot.

Common misunderstanding: "It is a Bloom filter with a different name." It is a different structure: it supports deletion, can be merged and resized without the original keys, and its access pattern is sequential, which matters on flash storage and in cache lines.

Definition: Bender et al. 2012 (secondary source). A quotient filter stores p-bit fingerprints split into a q-bit quotient that indexes a table and an r-bit remainder that is stored; collisions are resolved by linear probing with metadata bits that keep each run attached to its canonical slot. Counting quotient filters add counts per remainder.

Real scenario: an on-disk filter that must be merged during compaction without re-reading keys; analytics systems that need a mergeable filter per partition.

Fix: use a library; no mainstream SQL database exposes one directly.

Xor, binary fuse and Ribbon filters {#xor} Good to know ​

In plain words: If the set never changes after it is built (an SSTable, a Parquet file), you can build a filter in one go that is both smaller and faster to query than a Bloom filter.

Common misunderstanding: "I can add keys later." No: xor, binary fuse and Ribbon filters are built once from the full key list and are immutable. That is fine for LSM files, which are immutable too.

Definition: Graf and Lemire (2019) show "xor filters can be faster than Bloom and cuckoo filters while using less memory", with an Xor8 filter storing 8-bit fingerprints in an array about 1.23 times the number of keys (about 9.84 bits per key, FPR about 0.4%). Binary fuse filters (same authors) reduce the overhead to roughly 1.13x. Ribbon filters solve a linear system to the same effect; RocksDB's documentation states that NewRibbonFilterPolicy(9.9) "has the same 1% FP rate as Bloom but only uses around 7 bits per key", at the price of higher temporary memory (~231 bits per key vs ~74) during construction.

FilterMutableSpace at ~1% FPRConstruction costWhere
Bloom (RocksDB format 5)Add only9.9 bits per keyLowestRocksDB default
RibbonBuilt once~7 bits per keyHigher temporary memoryRocksDB NewRibbonFilterPolicy
Xor8Built once~9.84 bits per keyModerateStatic indexes
Binary fuseBuilt once~9 bits per keyModerateLibraries (Go, C++, Rust)

Fix: In RocksDB set filter_policy to a Ribbon policy for the bottom levels (the big, long-lived files), keep Bloom for the upper levels (hot, short-lived).

The sketches ​

HyperLogLog Must-know ​

In plain words: Count how many different things you have seen using a fixed 12 KB, however many there are, with an error under 1%.

Common misunderstanding: "PFCOUNT is a count of PFADD calls" or "PFADD tells me whether the visitor is new". Neither is right: duplicates do not change the estimate, and the 0/1 return of PFADD only says whether an internal register changed, which is a hint, not "new".

Definition: Hash every item to a 64-bit value. Use the first p bits to choose one of m = 2^p registers; in the remaining bits count the leading zeros (+1) and keep the maximum per register. A rare long run of zeros means many distinct items; averaging across m registers (harmonic mean) removes noise. The standard error is about 1.04/sqrt(m); with Redis's p = 14 (16,384 registers, 6 bits each = 12 KB) that is 1.04/128 = 0.81%. The paper: "estimate cardinalities well beyond 10^9 with a typical accuracy of 2% while using a memory of only 1.5 kilobytes". Small cardinalities use a correction (linear counting) and Google's HyperLogLog++ improves bias; Redis switches between a sparse encoding (small counts, far under 12 KB) and a dense one.

Step  Command                                   Result
1     PFADD visitors:2026-11-25 u1 u2 u3        1   (a register changed)
2     PFADD visitors:2026-11-25 u2              0   (no register changed: a duplicate, probably)
3     PFCOUNT visitors:2026-11-25               3
4     PFADD visitors:2026-11-26 u3 u4           1
5     PFCOUNT visitors:2026-11-25 visitors:2026-11-26   4   (union, u3 counted once)
6     PFMERGE week visitors:2026-11-25 visitors:2026-11-26   OK   (roll up)

Real scenario: unique visitors per page per day; distinct queries per tenant; distinct IPs hitting an endpoint (abuse detection); COUNT(DISTINCT) over a billion rows in an analytics engine.

What provides it:

ProductFunction
RedisPFADD, PFCOUNT, PFMERGE; a HyperLogLog is an ordinary string value, so GET/SET serialize it
PostgreSQLExtension postgresql-hll (Citus/Aggregate Knowledge), not in core
BigQueryHLL_COUNT.* functions
Presto/Trino, Spark, ClickHouseapprox_distinct, approx_count_distinct, uniqHLL12
MySQL, SQL Server, OracleAPPROX_COUNT_DISTINCT in SQL Server and Oracle; MySQL has none
MongoDB, SQLite, CockroachDBNone built in

Fix: see the Redis and Laravel code.

Count-Min sketch Important ​

In plain words: A small grid of counters that tells you roughly how often each key appeared, never less than the truth, sometimes a bit more.

Common misunderstanding: "The estimate is accurate for every key." Low counts are noise: the error is a fraction of the total stream, so a key seen twice can report 25 if the stream is large. The Redis documentation says estimates below a threshold "should be ignored and often even approximated to zero". The sketch is for finding the heavy hitters, not the tail.

Definition: Cormode and Muthukrishnan (2005): d rows of w counters, one hash function per row. add(x) increments one counter per row; estimate(x) is the minimum over the d counters. With w = ceil(e/eps) and d = ceil(ln(1/delta)), the estimate exceeds the true count by at most eps*N (N is the total of all increments) with probability at least 1 - delta. The paper: "the CM sketches never underestimate counts". A conservative update (increment only the minimum counters) tightens the bound.

Step  Event                         Row 1 col   Row 2 col   Row 3 col
1     add("a")                      c3 -> 1     c9 -> 1     c4 -> 1
2     add("b")                      c3 -> 2     c1 -> 1     c4 -> 2     (collides with a in rows 1 and 3)
3     estimate("a")                 2           1           2           min = 1 -> correct
4     estimate("b")                 2           1           2           min = 1 -> correct

Real scenario: top-K endpoints by request count; abuse detection ("which IPs sent over 1,000 requests this minute"); the frequency estimator inside TinyLFU cache admission; hot-key detection in a sharded store.

What provides it: Redis CMS.INITBYDIM key width depth, CMS.INITBYPROB key error probability, CMS.INCRBY, CMS.QUERY, CMS.MERGE, plus TOPK.* for a ready-made heavy-hitter list; Caffeine (JVM cache) for TinyLFU; no relational database ships one.

t-digest {#tdigest} Good to know ​

In plain words: A compact summary of a stream of numbers that gives accurate percentiles, especially p99 and p99.9, without storing every value.

Common misunderstanding: "Averages are fine for latency." The mean hides the tail that users feel; and computing exact percentiles over a stream requires storing it. t-digest keeps a bounded number of centroids and is most accurate near 0 and 1.

Definition: Dunning and Ertl (arXiv 1902.04023) present on-line algorithms for approximating rank-based statistics "that give high accuracy, particularly near the tails of a distribution, with very small sketches"; the accuracy of a quantile q is relative to max(q, 1-q) rather than absolute, and separately computed digests can be merged. In Redis: TDIGEST.CREATE key COMPRESSION 100 (the default compression is 100; higher means more accuracy and more memory), TDIGEST.ADD, TDIGEST.QUANTILE, TDIGEST.CDF, TDIGEST.MERGE.

Step  Command                                           Meaning
1     TDIGEST.CREATE latency:api COMPRESSION 100       Create
2     TDIGEST.ADD latency:api 12 15 11 480 13 ...      Stream of milliseconds
3     TDIGEST.QUANTILE latency:api 0.5 0.99 0.999      Estimated p50, p99, p99.9

Real scenario: latency SLO dashboards; percentile aggregations in Elasticsearch (percentiles uses t-digest or HDR); merging per-shard digests into a global p99.

PostgreSQL itself has exact percentile_cont/percentile_disc ordered-set aggregates (sort-based, memory grows with rows); approximate percentiles need an extension (tdigest by Tomas Vondra) or an analytics engine.

MinHash and LSH {#minhash} Good to know ​

In plain words: Estimate how much two big sets overlap by comparing small signatures, and use banding to find similar pairs without comparing every pair.

Common misunderstanding: "It deduplicates exactly." It estimates Jaccard similarity, so near-duplicates, not duplicates; a high-similarity pair can be missed by chance unless you tune bands and rows.

Definition: MinHash (Broder 1997, secondary): for k independent hash functions, the signature of a set is the minimum hash value per function; the probability that two sets have the same minimum equals their Jaccard similarity |A ∩ B| / |A ∪ B|, so the fraction of equal signature positions estimates it. Locality-sensitive hashing (LSH) splits the signature into b bands of r rows and buckets sets that agree on a whole band; a pair with similarity s is a candidate with probability 1 - (1 - s^r)^b.

Real scenario: near-duplicate web pages and product listings, plagiarism checks, recommendation candidate generation. No mainstream relational engine ships MinHash; PostgreSQL's pg_trgm does trigram similarity instead (see Full-Text Search), and embedding similarity is in Vector Search.

In databases and engines ​

PostgreSQL bloom index {#pg-bloom} Important ​

"This type of index is most useful when a table has many attributes and queries test arbitrary combinations of them." — PostgreSQL documentation, F.6 bloom

In plain words: One compact index that helps queries on any combination of many columns, as long as they use equality.

Common misunderstanding: "A Bloom index replaces btree indexes." It is lossy, supports only =, is slower than a matching btree, and cannot enforce UNIQUE or search NULL. It trades speed for needing one index instead of dozens.

Definition: The bloom contrib extension is an index access method. Each row gets a signature of length bits (default 80, rounded up to a multiple of 16, maximum 4096); each column sets col1..col32 bits (default 2, maximum 4095) into it. A query computes the same signature, scans all signatures, and returns candidates that must be rechecked against the heap, because "index search results must always be rechecked using the actual attribute values from the heap entry". Only int4 and text operator classes ship; only = is supported; no UNIQUE; no NULL search.

Step  Query: WHERE i2 = 898732 AND i5 = 123451     10M-row table, PostgreSQL docs example
1     Sequential scan                              357 ms
2     btree on (i1..i6)                            still a sequential scan (351 ms); leading column unconstrained
3     bloom on (i1..i6), 153 MB                    Bitmap Heap Scan 22.6 ms; Rows Removed by Index Recheck: 2300
4     six single-column btrees, 531 MB total       Bitmap Index Scans + BitmapAnd 0.047 ms

The numbers are from the PostgreSQL documentation's own example. The honest summary in that page: the Bloom index is "over three times" smaller than the six btrees, but the six btrees are faster. Pick the Bloom index when the number of column combinations is too large to index, or write amplification of dozens of indexes hurts.

Real scenarios: an admin "advanced search" screen over 10-30 attributes; support-ticket filters; a wide event table where analysts filter on any few of many categorical columns; replacing a pile of rarely used single-column indexes.

What prevents trouble:

RiskMitigation
High recheck count (visible in Rows Removed by Index Recheck)Larger length, more bits for selective columns
Index is scanned in full for every queryOnly use on tables where a full signature scan beats a seq scan
Range or LIKE predicatesNot supported; use btree, GIN or full-text search
Other types (uuid, bigint)Write an operator class with a hash function and equality operator (see text_ops in the docs)
sql
CREATE EXTENSION bloom;
CREATE INDEX tbloom_idx ON tbloom USING bloom (i1, i2, i3, i4, i5, i6)
  WITH (length = 80, col1 = 2, col2 = 2, col3 = 4);
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM tbloom WHERE i2 = 898732 AND i5 = 123451;

BRIN: block range indexes {#brin} Important ​

"BRIN is designed for handling very large tables in which certain columns have some natural correlation with their physical location within the table." — PostgreSQL documentation, BRIN Indexes

In plain words: Do not index every row; store a tiny summary (minimum and maximum, or a Bloom filter) for each group of neighbouring pages, and skip the groups that cannot match.

Common misunderstanding: "BRIN is a small btree." BRIN stores nothing per row; it works only if values are physically correlated with position (append-only timestamps, auto-increment ids). On a randomly ordered column, every range contains every value and the index skips nothing.

Definition: A block range is "a group of pages that are physically adjacent"; the size is the pages_per_range storage parameter (default 128). Operator classes: minmax (min and max per range), minmax-multi (several intervals per range, robust to outliers), inclusion (for geometric types and inet) and bloom ("build a Bloom filter for all values in the range"), with parameters n_distinct_per_range, false_positive_rate and values_per_range. Summaries are created by VACUUM or, with autosummarize, by autovacuum; brin_summarize_new_values(regclass), brin_summarize_range and brin_desummarize_range are the manual controls. A BRIN scan produces a bitmap of page ranges; the executor then rechecks the rows in those pages.

Step  Event                                          Index entry for range 3 (pages 384-511)
1     Rows inserted in time order                   min = 2026-11-01  max = 2026-11-02
2     Query: created_at >= '2026-11-25'             range 3 max < query value -> skipped
3     Old rows UPDATEd, new row versions land here  max = 2026-11-25   (summary widens, skips less)
4     UPDATE/DELETE churn over months               ranges overlap -> need CLUSTER or desummarize

Real scenario: a billion-row time-series or log table where a btree on created_at would be tens of gigabytes and BRIN is a few megabytes; a sales table queried by month; an IoT table. When values are correlated per range but not ordered (for example tenant ids) use bloom or minmax-multi operator classes instead of minmax.

What provides it:

ProductSimilar structure
PostgreSQLBRIN (USING brin) since 9.5; bloom and minmax-multi classes since 14
MySQL InnoDBNone
SQL ServerColumnstore segment elimination, per-segment min/max
OracleZone maps and storage indexes (Exadata)
Snowflake, Parquet, ClickHousePer-block/per-row-group min/max statistics, optional Bloom filters
sql
CREATE INDEX events_created_brin ON events USING brin (created_at) WITH (pages_per_range = 32, autosummarize = on);
-- correlation close to 1 or -1 means BRIN will work
SELECT attname, correlation FROM pg_stats WHERE tablename = 'events' AND attname = 'created_at';

The wider billion-row playbook, including partial indexes and partitioning, is in Working with Billion-Row Tables.

LSM SSTable filters (RocksDB, Cassandra, LevelDB, HBase) {#lsm} Must-know ​

"Bloom filters are a probabilistic data structure that allows Cassandra to determine one of two possible states: - The data definitely does not exist in the given file, or - The data probably exists in the given file." — Apache Cassandra documentation, Bloom filters

In plain words: A key can live in any of many immutable files. Before opening a file the engine asks that file's in-memory filter; "no" means skip the file without a disk read.

Common misunderstanding: "Bloom filters speed up range scans." They speed up point lookups (Get); a range scan has no single key to hash. RocksDB offers prefix Bloom filters for Seek when a prefix_extractor is configured, with a higher false positive rate.

Definition: Each SSTable is written once, never modified. At flush or compaction time the engine hashes every key into a filter stored with the file and kept in RAM (Cassandra: off-heap, Filter.db; RocksDB: opened with the file, optionally in the block cache). A Get walks memtable then files newest to oldest, consulting each filter first.

Get("user:42")from the clientMemtable(RAM, newest)missL0 SST-7 (newest)Bloom filter in RAMfilter: NOskip, 0 disk readsL0 SST-6Bloom filter in RAMfilter: NOskip, 0 disk readsL1 SST-3Bloom filter in RAMfilter: MAYBEread block, key absentL2 SST-1 (oldest)Bloom filter in RAMfilter: MAYBEread block, key foundRed row = a false positive: the filter said MAYBE, the file did not hold the key.At about 10 bits per key that happens for roughly 1 file in 100 that lacks the key.Without filters, a miss reads one block from every SSTable (read amplification).
Step  Get("user:42") in an LSM engine
1     check memtable                      miss
2     SST-7 (L0) filter                   NO  -> skip, 0 disk reads
3     SST-6 (L0) filter                   NO  -> skip
4     SST-3 (L1) filter                   MAYBE -> read index and data block -> key absent (false positive)
5     SST-1 (L2) filter                   MAYBE -> read block -> found
6     total                               2 block reads instead of 4

Real scenario: a Cassandra table with a read-mostly workload on a node with spare RAM: lower bloom_filter_fp_chance; a RocksDB-based store behind a service where most requests are for keys that do not exist (cache-penetration style); time-series ingestion where reads are rare: raise the rate to save RAM. The Cassandra documentation lists exactly these three cases.

Per-product table:

ProductDefaultKnobStats to watch
Cassandrabloom_filter_fp_chance 0.01, but 0.1 for LeveledCompactionStrategyALTER TABLE ... WITH bloom_filter_fp_chance = 0.01; applies to new SSTables only until rewritten with nodetool upgradesstables -a or nodetool scrubnodetool tablestats (Bloom filter false positives, false ratio, space used)
ScyllaDBSame option nameSame; filters are per SSTable tooMonitoring "bloom filter" metrics
RocksDBNone by default; NewBloomFilterPolicy(10) is the common choicefilter_policy, whole_key_filtering, prefix_extractor, cache_index_and_filter_blocks, optimize_filters_for_memory, partitioned filtersrocksdb.bloom.filter.useful, rocksdb.bloom.filter.full.positive, rocksdb.bloom.filter.full.true.positive
LevelDBNewBloomFilterPolicy(bits_per_key)Same idea, one filter per block (old format)n/a
HBasePer column family BLOOMFILTER set to ROW or ROWCOLTable descriptorRegion server metrics
PostgreSQL, InnoDBNo LSM, no SSTable filters (B-tree page lookups)n/an/a

The observed false positive rate in RocksDB is (positives - true positives) / (positives - true positives + true negatives), computed from those statistics. Cassandra's own memory warning: halving the FPR cost grows non-linearly; the docs state that 0.01 needs about three times the memory of 0.1. RocksDB's table: 10 bits per key gives about a 1% rate; "9.9 bits per key (1% false positive rate) is 99% as effective as 100 bits per key".

Compaction details are in Storage Engines.

Analytics engines: join filters, partition pruning, Parquet {#analytics} Important ​

In plain words: Before shuffling a huge table across the network for a join, send a small Bloom filter of the join keys of the other side and drop rows that cannot match. It is a semi-join reduction with an approximate set.

Common misunderstanding: "Partition pruning is a Bloom filter." Partition pruning (PostgreSQL, Hive, Spark) uses exact partition bounds known to the planner; it removes whole partitions deterministically. Bloom filters work at a finer level (files, row groups, rows) where exact information is too big.

Definition: A runtime (dynamic) filter builds a Bloom filter from the build side of a join (after its predicates run) and pushes it to the scan of the probe side. Spark 3.3 added spark.sql.optimizer.runtime.bloomFilter.enabled (default true): when one side of a shuffle join has a selective predicate "we attempt to insert a bloom filter in the other side to reduce shuffle data", gated by creationSideThreshold (10MB), applicationSideScanSizeThreshold (10GB), expectedNumItems (1,000,000) and numBits (8,388,608) with maxNumBits (67,108,864). Trino has dynamic filtering and Impala has runtime filters with the same idea (Bloom and min/max). Parquet defines "split block Bloom filters" per column chunk, so engines can skip a row group when an equality predicate cannot match; "Bloom filters do not have false negatives". PostgreSQL's hash join does not use a Bloom filter; its pruning tools are partition bounds, BRIN and its planner statistics (see Query Planning).

Step  Query: SELECT ... FROM orders o JOIN customers c ON o.cid = c.id WHERE c.country = 'NO'
1     scan customers with country = 'NO'          300K ids
2     build a Bloom filter of those ids           ~0.4 MB at 10 bits per id
3     push it to the scan of orders (1B rows)     rows with cid not in the filter are dropped before shuffle
4     shuffle only the survivors                  maybe 3% of orders plus 1% false positives
5     hash join exact                             false positives disappear here

Real scenarios: star-schema joins where a small selective dimension joins a giant fact table; lakehouse queries over Parquet with WHERE user_id = ? on a high-cardinality column where min/max statistics do not help.

What provides it:

ProductFeature
Apache Spark 3.3+Runtime Bloom filter joins; spark.sql.optimizer.runtime.bloomFilter.*
ParquetSplit block Bloom filters in the file format; Spark, Trino, DuckDB read them
TrinoDynamic filtering (exact sets or min/max for small builds; Bloom-like for larger)
ClickHouseSkip indexes bloom_filter, tokenbf_v1, ngrambf_v1 (from the ClickHouse docs, not re-read here)
SQL ServerBloom filters in parallel hash joins (visible as Bitmap operator)
OracleBloom filters in parallel joins (JOIN FILTER in plans)
PostgreSQL, MySQL, SQLiteNo runtime Bloom join filters

Caches, TinyLFU and cache penetration {#caches} Important ​

In plain words: A cache fills with one-hit wonders (items asked for once) and pushes out useful entries. A small filter remembers "have I seen this key before?" and admits it only on the second request.

Common misunderstanding: "A bigger cache solves it." A scan or crawler can evict a hot working set regardless of size; admission control, not capacity, protects it. And a different problem, cache penetration (requests for keys that exist nowhere) hits the database every time; a filter in front of the cache answers "does this key exist at all?" without a database call.

Definition: TinyLFU (Einziger et al. 2017) "decides, based on the recent access history, whether it is worth admitting the new item into the cache at the expense of the eviction candidate", keeping the history in a Count-Min sketch (with periodic halving) and a small Bloom filter "doorkeeper" that absorbs one-hit wonders before they reach the sketch. Caffeine (Java) and Ristretto (Go) use it. Memcached has no admission policy; Redis's allkeys-lfu policy uses a probabilistic Morris counter per key rather than a sketch.

Step  Request for key K                         Doorkeeper (Bloom)   Cache
1     GET K  (miss, first time)                 add K                not admitted
2     GET K  (miss, second time)                K present            admit K, serve next hits from RAM
3     GET Z  (scan, never again)                add Z                never cached; no eviction caused
4     GET M  (never existed anywhere)           existence filter: no  return 404 without calling the database

Real scenario: a product catalog behind Redis where a crawler walks millions of URLs; a username lookup where bots probe random names; a CDN edge cache.

What each product really does ​

ProductBloom / probabilistic featuresDefaults to know
PostgreSQLbloom contrib index (equality, int4/text), BRIN (minmax, minmax-multi, inclusion, bloom), planner stats; percentile_* exact only; HLL by extensionBloom signature 80 bits, 2 bits per column; BRIN pages_per_range 128, autosummarize off
MySQL / InnoDBNo Bloom index, no HLL; adaptive hash index is exactAPPROX_COUNT_DISTINCT does not exist
SQL ServerBloom filters inside parallel hash joins; APPROX_COUNT_DISTINCT, APPROX_PERCENTILE_CONT (2022+)Not tunable
OracleBloom filters in parallel joins; APPROX_COUNT_DISTINCT, APPROX_PERCENTILE; zone mapsOptimizer-controlled
SQLiteQuery planner may build an automatic index; no Bloom indexn/a
MongoDBWiredTiger is a B-tree; no user Bloom filters; aggregation $count is exactn/a
CockroachDBPebble (an LSM) uses Bloom filters per SSTableNot exposed as a table option
Redis (Open Source)HyperLogLog, Bloom, Cuckoo, Count-Min, Top-K, t-digestHLL 12 KB / 0.81%; t-digest compression 100
Cassandra / ScyllaDBSSTable Bloom filtersbloom_filter_fp_chance 0.01 (0.1 for LCS)
RocksDB / LevelDBBloom, Ribbon, partitioned filtersYou choose NewBloomFilterPolicy(10)
Spark / Trino / ImpalaRuntime Bloom join filtersSpark: on by default since 3.3
ParquetSplit-block Bloom filters per column chunkWriters must enable them

Mechanics: knobs, arithmetic and failure modes ​

The hash-and-probe pipeline ​

StageWhat happensWhy it matters
1. HashKey bytes become one 64-bit value (xxHash, MurmurHash, FNV plus a mixer)A weak hash clusters bits and raises the real FPR above the formula
2. Derive probesh1 + i*h2 mod m for i in 0..k-1 (double hashing)k hash computations collapse into one
3. LocateWord index = pos / 64, bit = pos mod 64One memory access per probe unless cache-line blocked
4. Test or setAND for a query, OR for an insertBitwise OR makes two same-sized filters mergeable
5. Stop earlyA query stops at the first 0 bitA negative lookup touches on average about two probes, which is why "reject time" is small

Arithmetic you should be able to do in your head ​

QuestionFormulaExample
Wasted reads per absent-key lookup across L filesL * p100 SSTables at p = 1% gives 1.0 wasted block read
Filter RAM for n keysn * 1.44 * log2(1/p) / 8 bytes500M keys at 1% = about 600 MB
Safe n for fixed m and pn = m * (ln 2)^2 / -ln p1 MiB of filter at 1% holds about 875,000 keys
HyperLogLog error1.04 / sqrt(m)m = 16384 gives 0.81%; m = 4096 gives 1.6%
Count-Min width/depthw = ceil(e/eps), d = ceil(ln(1/delta))eps = 0.001, delta = 0.01 gives w = 2719, d = 5 (matches the Go demo)
BRIN index entriestable pages / pages_per_range1,000,000 pages / 128 = 7,813 summaries

Redis probabilistic commands and their knobs ​

CommandPurposeNotes
BF.RESERVE key error_rate capacity [EXPANSION n] [NONSCALING]Create a Bloom filterWithout NONSCALING, adds past capacity create sub-filters
BF.ADD, BF.MADD, BF.EXISTS, BF.MEXISTSAdd and testBF.ADD returns 1 if newly added, 0 if probably present
BF.SCANDUMP / BF.LOADCHUNKIncremental save and restoreO(n) in the capacity
CF.RESERVE, CF.ADD, CF.ADDNX, CF.EXISTS, CF.DEL, CF.COUNTCuckoo filterBucket size is an option
PFADD, PFCOUNT, PFMERGEHyperLogLogPlain string value; GET/SET serialise it; sparse then dense encoding
CMS.INITBYDIM, CMS.INITBYPROB, CMS.INCRBY, CMS.QUERY, CMS.MERGECount-MinCMS.INFO shows width, depth and count
TOPK.RESERVE, TOPK.ADD, TOPK.LISTHeavy hittersReady-made top-K list
TDIGEST.CREATE, TDIGEST.ADD, TDIGEST.QUANTILE, TDIGEST.CDF, TDIGEST.MERGEt-digestCOMPRESSION default 100; TDIGEST.ADD does not create the key

Using a normal command on the wrong type returns Redis's usual WRONGTYPE error; a string that is not a valid HyperLogLog is rejected by PFADD/PFCOUNT (behaviour of Redis in general, not re-read on the docs page above). The commands marked with BF., CF., CMS., TDIGEST. and TOPK. come from the Redis Open Source probabilistic modules; on a Redis build without them the server answers with an unknown-command error.

PostgreSQL bloom extension and BRIN, underneath ​

Aspectbloom extensionBRIN
Index entryOne signature per heap row (length bits, rounded to a multiple of 16)One summary per block range
Scan costReads the whole signature index sequentially, then heap rechecksReads the small summary set, then whole page ranges
Size driverslength, rowsTable pages / pages_per_range
Precision knobslength, col1..col32 bits per columnpages_per_range; for bloom opclass n_distinct_per_range, false_positive_rate
Planner visibilityBitmap Index Scan; Rows Removed by Index RecheckBitmap Index Scan; recheck of whole ranges
MaintenanceNormal index insert; not UNIQUESummaries by VACUUM or autosummarize; brin_summarize_new_values, brin_desummarize_range
ConcurrencyCREATE INDEX CONCURRENTLY supportedSame

Failure modes ​

SymptomCauseFix
FPR in production far above targetFilter over-filled, weak hash, or a filter reused for a different key setResize from real n; use a 64-bit mixed hash; rebuild
RocksDB filter memory pressure and p99 spikesFilters evicted from the block cachePartitioned filters, cache_index_and_filter_blocks, pin filters
Cassandra change to bloom_filter_fp_chance seems to do nothingExisting SSTables keep their filtersnodetool upgradesstables -a or nodetool scrub
HyperLogLog count drifts after merging differently-sized sketchesSketches must share precisionUse one p everywhere (Redis fixes it)
BRIN index scans most of the tableCorrelation lost through updates or random insertsCLUSTER, rewrite, or switch to btree/partitioning
Cuckoo insert returns falseTable full after maximum kicksReserve larger capacity, rebuild
Count-Min says a key is hot but it is notCollisions with heavy keys (over-estimate)Larger width, conservative update, verify with an exact counter

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limitation
Misses hit the database (cache penetration)Existence filter in frontBloom or Cuckoo filter of all valid ids; no => 404Database untouched for bad keysFilter must be rebuilt/updated when keys are added; false positives still reach the database
Unique visitors at scaleHyperLogLogPFADD, PFCOUNT12 KB per counter, mergeable0.81% error, no per-user answers
Many equality columns, one indexPostgreSQL bloomUSING bloom (a, b, c, ...)One index instead of dozensEquality only, lossy, slower than btree
Huge append-only tableBRINUSING brin (created_at)Megabytes instead of gigabytesNeeds physical correlation
LSM point-read amplificationSSTable Bloom filtersbloom_filter_fp_chance, NewBloomFilterPolicySkip files with no disk I/ORAM per key, point reads only
Heavy hittersCount-Min sketchCMS.INCRBY, CMS.QUERY or TOPK.*Fixed memoryOver-estimates, noisy tail
Latency percentilest-digestTDIGEST.ADD, TDIGEST.QUANTILEMergeable, accurate tailsApproximate
One-hit wonders pollute a cacheDoorkeeper admissionBloom filter then cache on second requestProtects hot setOne extra miss for real hot keys
Join shuffles too much dataRuntime Bloom filterSpark runtime filter, Parquet filtersLess networkNeeds a selective build side
Deletions neededCuckoo or counting filterCF.DELReal removalInsert can fail; delete discipline

The Go section ​

A teaching Bloom filter, HyperLogLog and Count-Min sketch (standard library only, gofmt and go vet clean) live under docs/snippets/database/bloom-filters-probabilistic/go. They share one 64-bit hash (hashutil).

Bloom filter package:

go
// Package bloom is a teaching Bloom filter: m bits, k probes, no deletion.
package bloom

import (
	"math"

	"academy/bloom-filters-probabilistic/hashutil"
)

// Filter is a standard Bloom filter.
type Filter struct {
	bits []uint64
	m    uint64 // number of bits
	k    uint64 // number of probes per key
	n    uint64 // number of Add calls (for diagnostics)
}

// OptimalParams returns m (bits) and k (hash functions) for n expected keys
// and a target false positive rate p:
//
//	m = -n ln p / (ln 2)^2        k = (m / n) ln 2
func OptimalParams(n int, p float64) (m, k uint64) {
	mf := -float64(n) * math.Log(p) / (math.Ln2 * math.Ln2)
	m = uint64(math.Ceil(mf))
	k = uint64(math.Max(1, math.Round(mf/float64(n)*math.Ln2)))
	return m, k
}

// New builds a filter with explicit m and k.
func New(m, k uint64) *Filter {
	return &Filter{bits: make([]uint64, (m+63)/64), m: m, k: k}
}

// NewForCapacity sizes the filter for n keys at false positive rate p.
func NewForCapacity(n int, p float64) *Filter {
	m, k := OptimalParams(n, p)
	return New(m, k)
}

// probes derives k bit positions from one 64-bit hash with double hashing
// (Kirsch & Mitzenmacher): g_i(x) = h1(x) + i*h2(x) mod m.
func (f *Filter) probes(key string) func(yield func(uint64) bool) {
	h := hashutil.Sum64(key)
	h1, h2 := h&0xffffffff, (h>>32)|1 // h2 odd so it is never stuck at 0
	return func(yield func(uint64) bool) {
		for i := uint64(0); i < f.k; i++ {
			if !yield((h1 + i*h2) % f.m) {
				return
			}
		}
	}
}

// Add sets the k bits of key.
func (f *Filter) Add(key string) {
	for pos := range f.probes(key) {
		f.bits[pos/64] |= 1 << (pos % 64)
	}
	f.n++
}

// MayContain is false only when the key is definitely absent. A true answer
// means "probably present": it can be a false positive, never a false negative.
func (f *Filter) MayContain(key string) bool {
	for pos := range f.probes(key) {
		if f.bits[pos/64]&(1<<(pos%64)) == 0 {
			return false
		}
	}
	return true
}

// FillRatio is the fraction of bits set; the theoretical FPR is FillRatio^k.
func (f *Filter) FillRatio() float64 {
	var set int
	for _, w := range f.bits {
		for ; w != 0; w &= w - 1 {
			set++
		}
	}
	return float64(set) / float64(f.m)
}

// TheoreticalFPR is (1 - e^(-k n / m))^k for the keys added so far.
func (f *Filter) TheoreticalFPR() float64 {
	return math.Pow(1-math.Exp(-float64(f.k)*float64(f.n)/float64(f.m)), float64(f.k))
}

// Bits returns m and k.
func (f *Filter) Bits() (m, k uint64) { return f.m, f.k }

Measure the false positive rate against the formula:

go
// Command bloom measures the false positive rate of the teaching filter and
// compares it with the formula, for several bits-per-key budgets.
package main

import (
	"fmt"
	"math"

	"academy/bloom-filters-probabilistic/bloom"
)

func main() {
	const n = 100_000
	const probes = 200_000

	fmt.Printf("%-10s %-4s %-12s %-12s %-12s\n", "bits/key", "k", "fill", "theory FPR", "measured FPR")
	for _, bitsPerKey := range []float64{4, 8, 10, 12, 16} {
		m := uint64(bitsPerKey * n)
		k := uint64(math.Max(1, math.Round(bitsPerKey*math.Ln2)))
		f := bloom.New(m, k)
		for i := 0; i < n; i++ {
			f.Add(fmt.Sprintf("member-%d", i))
		}
		// Every member must be found: a Bloom filter has no false negatives.
		for i := 0; i < n; i += 997 {
			if !f.MayContain(fmt.Sprintf("member-%d", i)) {
				panic("false negative: impossible by construction")
			}
		}
		// Keys that were never added: every "true" is a false positive.
		var fp int
		for i := 0; i < probes; i++ {
			if f.MayContain(fmt.Sprintf("stranger-%d", i)) {
				fp++
			}
		}
		fmt.Printf("%-10.0f %-4d %-12.4f %-12.5f %-12.5f\n",
			bitsPerKey, k, f.FillRatio(), f.TheoreticalFPR(), float64(fp)/probes)
	}

	m, k := bloom.OptimalParams(1_000_000, 0.01)
	fmt.Printf("\n1M keys at 1%% FPR: m=%d bits (%.2f MiB), k=%d, %.2f bits/key\n",
		m, float64(m)/8/1024/1024, k, float64(m)/1_000_000)
}

Measured ​

Output of go run ./cmd/bloomfpr on 100,000 keys, probed with 200,000 keys that were never added:

bits/key   k    fill         theory FPR   measured FPR
4          3    0.5279       0.14689      0.14611
8          6    0.5276       0.02158      0.02183
10         7    0.5036       0.00819      0.00804
12         8    0.4871       0.00314      0.00310
16         11   0.4970       0.00046      0.00048

1M keys at 1% FPR: m=9585059 bits (1.14 MiB), k=7, 9.59 bits/key

Theory and measurement agree to the second digit, and the fill ratio sits near one half at the optimal k, exactly as the derivation says.

HyperLogLog:

go
// Package hll is a teaching HyperLogLog: 2^p registers of "rank" values.
package hll

import (
	"math"
	"math/bits"

	"academy/bloom-filters-probabilistic/hashutil"
)

// Sketch estimates the number of distinct keys in about 2^p bytes.
type Sketch struct {
	p   uint8
	reg []uint8
}

// New creates a sketch with 2^p registers (4 <= p <= 18). Redis uses p = 14,
// which is 16384 registers and a standard error of 1.04/sqrt(16384) = 0.81%.
func New(p uint8) *Sketch {
	if p < 4 || p > 18 {
		panic("hll: p must be in [4, 18]")
	}
	return &Sketch{p: p, reg: make([]uint8, 1<<p)}
}

// Add observes one key.
func (s *Sketch) Add(key string) {
	h := hashutil.Sum64(key)
	idx := h >> (64 - s.p)            // top p bits choose the register
	rest := h<<s.p | (1 << (s.p - 1)) // remaining bits; sentinel bounds the rank
	rank := uint8(bits.LeadingZeros64(rest)) + 1
	if rank > s.reg[idx] {
		s.reg[idx] = rank
	}
}

// Merge folds another sketch (same p) into s: the union of both streams.
func (s *Sketch) Merge(o *Sketch) {
	for i, r := range o.reg {
		if r > s.reg[i] {
			s.reg[i] = r
		}
	}
}

// Count returns the estimated cardinality, with the small-range
// (linear counting) correction from the HyperLogLog paper.
func (s *Sketch) Count() float64 {
	m := float64(len(s.reg))
	var sum float64
	var zeros int
	for _, r := range s.reg {
		sum += math.Ldexp(1, -int(r))
		if r == 0 {
			zeros++
		}
	}
	alpha := 0.7213 / (1 + 1.079/m)
	est := alpha * m * m / sum
	if est <= 2.5*m && zeros > 0 {
		return m * math.Log(m/float64(zeros))
	}
	return est
}

// StdError is the theoretical relative standard error, about 1.04/sqrt(m).
func (s *Sketch) StdError() float64 { return 1.04 / math.Sqrt(float64(len(s.reg))) }

// Bytes is the register memory (one byte per register in this teaching copy;
// Redis packs 6 bits per register into 12 KB).
func (s *Sketch) Bytes() int { return len(s.reg) }
go
// Command hll feeds the teaching HyperLogLog with known cardinalities and
// prints the relative error next to the theoretical standard error.
package main

import (
	"fmt"
	"math"

	"academy/bloom-filters-probabilistic/hll"
)

func main() {
	fmt.Printf("%-10s %-12s %-12s %-10s %-10s\n", "true n", "estimate", "rel. error", "std error", "registers")
	for _, n := range []int{100, 1_000, 10_000, 100_000, 1_000_000} {
		s := hll.New(14)
		for i := 0; i < n; i++ {
			s.Add(fmt.Sprintf("visitor-%d", i))
			if i%3 == 0 {
				s.Add(fmt.Sprintf("visitor-%d", i)) // duplicates must not change the count
			}
		}
		est := s.Count()
		fmt.Printf("%-10d %-12.0f %-12.4f %-10.4f %-10d\n",
			n, est, math.Abs(est-float64(n))/float64(n), s.StdError(), s.Bytes())
	}

	// Merge: two shards count independently, the union is exact in register space.
	a, b := hll.New(14), hll.New(14)
	for i := 0; i < 60_000; i++ {
		a.Add(fmt.Sprintf("u-%d", i))
	}
	for i := 40_000; i < 100_000; i++ {
		b.Add(fmt.Sprintf("u-%d", i)) // overlaps a on 20_000 keys
	}
	a.Merge(b)
	fmt.Printf("\nmerged estimate of 100000 distinct: %.0f\n", a.Count())
}
true n     estimate     rel. error   std error  registers
100        100          0.0031       0.0081     16384
1000       991          0.0086       0.0081     16384
10000      9993         0.0007       0.0081     16384
100000     99636        0.0036       0.0081     16384
1000000    1006734      0.0067       0.0081     16384

merged estimate of 100000 distinct: 99482

Every relative error is within one standard error (0.81%), and duplicates (every third key was added twice) did not change the count. This teaching copy stores one byte per register; Redis packs 6 bits.

Count-Min sketch and the shared hash:

go
// Package cms is a teaching Count-Min sketch: d rows of w counters.
package cms

import (
	"math"

	"academy/bloom-filters-probabilistic/hashutil"
)

// Sketch estimates item frequencies; it never underestimates.
type Sketch struct {
	w, d  uint64
	rows  [][]uint32
	total uint64
}

// New sizes the sketch from the error target: estimates exceed the true count
// by at most eps*N with probability at least 1-delta, where w = ceil(e/eps)
// and d = ceil(ln(1/delta)).
func New(eps, delta float64) *Sketch {
	w := uint64(math.Ceil(math.E / eps))
	d := uint64(math.Ceil(math.Log(1 / delta)))
	rows := make([][]uint32, d)
	for i := range rows {
		rows[i] = make([]uint32, w)
	}
	return &Sketch{w: w, d: d, rows: rows}
}

func (s *Sketch) col(row uint64, key string) uint64 {
	return hashutil.Mix(hashutil.Sum64(key)+row*0x9e3779b97f4a7c15) % s.w
}

// Add increments the counters of key by n.
func (s *Sketch) Add(key string, n uint32) {
	for r := uint64(0); r < s.d; r++ {
		s.rows[r][s.col(r, key)] += n
	}
	s.total += uint64(n)
}

// Estimate is the minimum over the d counters: collisions only add, so the
// smallest counter is the least polluted one.
func (s *Sketch) Estimate(key string) uint32 {
	best := ^uint32(0)
	for r := uint64(0); r < s.d; r++ {
		if v := s.rows[r][s.col(r, key)]; v < best {
			best = v
		}
	}
	return best
}

// Total is the sum of all increments (the N in the eps*N error bound).
func (s *Sketch) Total() uint64 { return s.total }

// Dims returns width and depth.
func (s *Sketch) Dims() (w, d uint64) { return s.w, s.d }
go
// Command cms counts a Zipf-like stream and compares estimates with truth.
package main

import (
	"fmt"
	"math/rand"

	"academy/bloom-filters-probabilistic/cms"
)

func main() {
	s := cms.New(0.001, 0.01)
	w, d := s.Dims()
	fmt.Printf("width=%d depth=%d counters=%d (%d KiB)\n", w, d, w*d, w*d*4/1024)

	rng := rand.New(rand.NewSource(7))
	zipf := rand.NewZipf(rng, 1.2, 1, 99_999)
	truth := map[string]uint32{}
	for i := 0; i < 1_000_000; i++ {
		key := fmt.Sprintf("item-%d", zipf.Uint64())
		truth[key]++
		s.Add(key, 1)
	}
	bound := uint32(0.001 * float64(s.Total()))
	fmt.Printf("N=%d, error bound eps*N=%d\n\n", s.Total(), bound)
	fmt.Printf("%-12s %-10s %-10s %-10s\n", "key", "true", "estimate", "over")
	for _, key := range []string{"item-0", "item-1", "item-10", "item-1000", "item-50000", "item-never"} {
		est := s.Estimate(key)
		fmt.Printf("%-12s %-10d %-10d %-10d\n", key, truth[key], est, est-truth[key])
	}
}
go
// Package hashutil gives the teaching structures one shared 64-bit hash.
package hashutil

import "hash/fnv"

// Mix is the splitmix64 finalizer: it spreads every input bit over all
// output bits, which FNV alone does not do for short, similar keys.
func Mix(x uint64) uint64 {
	x ^= x >> 30
	x *= 0xbf58476d1ce4e5b9
	x ^= x >> 27
	x *= 0x94d049bb133111eb
	x ^= x >> 31
	return x
}

// Sum64 hashes a string key to a well-mixed 64-bit value.
func Sum64(key string) uint64 {
	h := fnv.New64a()
	_, _ = h.Write([]byte(key))
	return Mix(h.Sum64())
}
width=2719 depth=5 counters=13595 (53 KiB)
N=1000000, error bound eps*N=1000

key          true       estimate   over
item-0       196029     196059     30
item-1       85761      85791      30
item-10      11023      11049      26
item-1000    50         73         23
item-50000   0          25         25
item-never   0          20         20

The heavy keys are accurate to 0.02%; the keys with true count 50 and 0 both read 20-73, the noise floor that the Redis docs tell you to ignore.

Go ecosystem. Production code should use a maintained library rather than this teaching copy: github.com/bits-and-blooms/bloom/v3 (Bloom), github.com/seiflotfy/cuckoofilter, github.com/FastFilter/xorfilter, github.com/axiomhq/hyperloglog, github.com/dgryski/go-tdigest; for Redis use go-redis/v9 (rdb.PFAdd, rdb.PFCount, rdb.BFAdd, rdb.CFAdd). Verify any import path on pkg.go.dev before use.

The Laravel section ​

Laravel has no probabilistic-structure API, but its Redis facade "supports dynamic methods, meaning you may call any Redis command on the facade and the command will be passed directly to Redis", so Redis::pfadd and Redis::pfcount work as written, and Redis::command('rawCommand', [...]) reaches module commands (BF.*) with the phpredis client.

Unique visitors with HyperLogLog (PFADD, PFCOUNT, PFMERGE):

php
<?php

declare(strict_types=1);

namespace App\Analytics;

use Illuminate\Support\Facades\Redis;

/**
 * Unique visitors per page and day with HyperLogLog.
 * Memory per key is at most 12 KB and the standard error is 0.81%,
 * no matter whether 10 or 10 million visitors were counted.
 */
final class UniqueVisitors
{
    public function track(string $page, string $visitorId, ?\DateTimeInterface $at = null): void
    {
        // PFADD returns 1 when an internal register changed, 0 otherwise.
        // Do NOT read it as "this visitor is new": it is only a hint.
        Redis::pfadd($this->key($page, $at), [$visitorId]);
    }

    public function countDay(string $page, ?\DateTimeInterface $at = null): int
    {
        return (int) Redis::pfcount($this->key($page, $at));
    }

    /**
     * Distinct visitors over several days. PFCOUNT with many keys merges the
     * registers on the fly, so a visitor seen on Monday and Tuesday counts once.
     * Summing countDay() results would count that visitor twice.
     *
     * @param list<\DateTimeInterface> $days
     */
    public function countDays(string $page, array $days): int
    {
        $keys = array_map(fn (\DateTimeInterface $d) => $this->key($page, $d), $days);

        return (int) Redis::pfcount($keys);
    }

    /** Persist a weekly roll-up and let the daily keys expire. */
    public function rollUpWeek(string $page, string $weekLabel, array $days): void
    {
        $keys = array_map(fn (\DateTimeInterface $d) => $this->key($page, $d), $days);
        $dest = "uv:{$page}:week:{$weekLabel}";

        Redis::pfmerge($dest, $keys);
        Redis::expire($dest, 60 * 60 * 24 * 400);
    }

    private function key(string $page, ?\DateTimeInterface $at): string
    {
        $day = ($at ?? new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('Y-m-d');

        return "uv:{$page}:{$day}";
    }
}

countDays passes several keys to one PFCOUNT, which merges registers on the fly, so a visitor who appears on two days is counted once; summing daily counts would be wrong. In Redis Cluster all keys of a multi-key PFCOUNT/PFMERGE must hash to one slot (use a hash tag like uv:{page}:2026-11-25).

Cache admission (doorkeeper) with the Redis Bloom commands:

php
<?php

declare(strict_types=1);

namespace App\Cache;

use Closure;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

/**
 * "Doorkeeper" admission: a key is only written to the cache on its SECOND
 * request inside the window. One-hit wonders (crawlers, scans, random ids)
 * then never evict useful entries. This is the idea of the TinyLFU doorkeeper,
 * built here on the Bloom filter module of Redis Stack (BF.* commands).
 *
 * Laravel's cache API has no admission hook, so this wrapper sits in front of
 * Cache::remember. The BF.* commands are not wrapped by Laravel; with the
 * phpredis client they are sent through rawCommand (with Predis, use
 * executeRaw). The filter is reserved once, outside this class.
 */
final class CacheAdmission
{
    private const FILTER = 'doorkeeper:cache';

    public function __construct(private readonly int $ttlSeconds = 600)
    {
    }

    /** Run once at deploy time: 1M keys at 1% false positives, scaling allowed. */
    public static function reserve(): void
    {
        Redis::connection()->command('rawCommand', ['BF.RESERVE', self::FILTER, '0.01', '1000000']);
    }

    /**
     * @template T
     * @param Closure():T $loader
     * @return T
     */
    public function remember(string $key, Closure $loader): mixed
    {
        $hit = Cache::get($key);
        if ($hit !== null) {
            return $hit;
        }

        $value = $loader();

        // BF.ADD returns 1 if the key was NOT present before (first sighting)
        // and 0 if it was probably seen already. A false positive only admits a
        // one-hit wonder early, which is harmless.
        $firstSighting = (int) Redis::connection()->command('rawCommand', ['BF.ADD', self::FILTER, $key]) === 1;

        if (! $firstSighting) {
            Cache::put($key, $value, $this->ttlSeconds);
        }

        return $value;
    }
}

Laravel's Cache::remember has no admission hook (Cache::add and Cache::has are plain key operations), so the wrapper sits in front. The BF.* commands need the Bloom module (part of Redis Open Source per the Redis docs; the call through rawCommand is written against the phpredis API and has not been run on this machine).

PostgreSQL bloom and BRIN from a migration:

php
<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

/**
 * One PostgreSQL bloom index instead of one btree per column, for a wide
 * table queried with arbitrary equality combinations (support search, admin
 * filters). Laravel's schema builder has no bloom or BRIN index type, so raw
 * statements are the honest tool here.
 */
return new class extends Migration
{
    public $withinTransaction = false; // CREATE INDEX CONCURRENTLY cannot run in a transaction

    public function up(): void
    {
        DB::statement('CREATE EXTENSION IF NOT EXISTS bloom');

        // length is rounded up to a multiple of 16 bits; colN is bits per column.
        DB::statement(<<<'SQL'
            CREATE INDEX CONCURRENTLY tickets_bloom_idx ON tickets
            USING bloom (status, priority, assignee_id, team_id, category_id, channel_id)
            WITH (length = 80, col1 = 2, col2 = 2, col3 = 4, col4 = 3, col5 = 3, col6 = 2)
        SQL);

        // BRIN for the append-only, time-ordered column: tiny and good enough.
        DB::statement(<<<'SQL'
            CREATE INDEX CONCURRENTLY tickets_created_brin ON tickets
            USING brin (created_at) WITH (pages_per_range = 32)
        SQL);
    }

    public function down(): void
    {
        DB::statement('DROP INDEX CONCURRENTLY IF EXISTS tickets_created_brin');
        DB::statement('DROP INDEX CONCURRENTLY IF EXISTS tickets_bloom_idx');
    }
};

Eloquent and the schema builder have no bloom or brin index type, so DB::statement is the honest tool. CREATE INDEX CONCURRENTLY cannot run inside a transaction, hence $withinTransaction = false. For approximate percentiles and distinct counts inside PostgreSQL, install the extensions (tdigest, postgresql-hll) and call them from DB::select.

Choosing a structure ​

What is the question?(approximate is fine)"Is x in the set?"one-sided errorBloom / Cuckoo / xorfilter: false positives only"How many distinct?"relative error ~0.81%HyperLogLogPFADD, PFCOUNT, 12 KB"How often did x occur?"over-estimates onlyCount-Min sketchCMS.INITBYPROB, CMS.QUERY"What is the p99?"accurate at the tailst-digestTDIGEST.ADD, TDIGEST.QUANTILEDo not use when a wrong answer is unacceptable and no exact recheck exists.
SituationRecommendationExtra techniqueReason
Skip disk reads for absent keysBloom (or Ribbon for old, big files)Size from the real key countOne-sided error is exactly what a skip filter needs
Same, items expireCuckoo filterRebuild periodicallyDeletion without 4x memory
Set unknown in advanceScalable Bloom, or rebuild at thresholdsMonitor fill ratioOver-filling destroys the FPR
Static set, smallest and fastestXor / binary fuse / RibbonBuild at file-write timeImmutable, less space
Unique countsHyperLogLogPFMERGE per day, roll up12 KB, mergeable
Top-K, hot keysCount-Min + heap, or TOPK.*Decay (halving) for recencyFixed memory
p95/p99 over a streamt-digestMerge per-shard digestsAccurate tails
Many equality columns in PostgreSQLbloom indexTest with EXPLAIN ANALYZEOne index for all combos
Huge time-ordered tableBRINpages_per_range tuned, check correlationTiny index
Money, permissions, uniquenessExact structure (set, unique index)Bloom only as a pre-filterA wrong answer is not acceptable

When not to use these ​

Do not use whenWhyUse instead
A false positive is harmful and there is no recheckA Bloom "yes" is only "maybe"UNIQUE index, exact set
The data is small enough to hold exactlyThe complexity buys nothingA hash set or a btree
You need to enumerate membersFilters cannot list their contentsA real index or table
You need exact billing or audit countsHLL/CMS are estimatesCOUNT(DISTINCT), ledger
Range or inequality predicatesBloom is equality onlybtree, BRIN minmax
Randomly ordered table and BRINRanges overlap, nothing skippedbtree or partitioning
Highly selective predicates already served by a btreeBloom index is slower than btreeThe btree
Write path is the bottleneck and the filter must be updated per writeCross-service filters go staleRebuild on a schedule

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

One Laravel or Go service, one PostgreSQL. Start without any probabilistic structure; add them when a measured problem appears. First candidates: a PostgreSQL bloom index on an admin search table that has grown to 25 filterable columns; a BRIN index on created_at of an append-only audit_log (a btree would be gigabytes); a Redis PFADD counter for unique page visitors instead of a visits table that grows without bound. The simplest correct usage: the filter is a pre-check and the database stays the source of truth.

Modular monolith / multiple databases ​

Modules own their data; a module can keep a private Bloom filter of its ids (for example the catalogue module exposes exists(id) backed by a filter plus a database confirmation) without letting other modules read its tables. Rule: a filter built from module A's table is owned and rebuilt by module A. With several databases, a Bloom index in one PostgreSQL schema does not help queries in another; HyperLogLog sketches, being mergeable, are a good way to combine counts across module databases without joining them.

Microservices ​

What survives across service boundaries: serialized filters (a Bloom filter is bytes; BF.SCANDUMP/BF.LOADCHUNK, or a library's binary format) and mergeable sketches (bitwise OR for same-sized Bloom filters, register max for HyperLogLog, cell-wise sum for Count-Min). What does not: consistency. A filter published by a service is a snapshot.

Step  Flow: "is this e-mail already registered?" in a sign-up service
1     client -> sign-up API              POST /signup {email}
2     API -> Bloom filter (local)        MAY_CONTAIN(email)?
3     filter says NO                     skip the lookup; INSERT user (UNIQUE index guards the race)
4     filter says MAYBE                  SELECT 1 FROM users WHERE email = ?   (authoritative)
5     user service -> event stream       UserRegistered(email) published via outbox
6     every API instance                 consumes the event and adds email to its local filter

The unique index remains the safety net: the filter only avoids reads. Never let the filter be the authority for uniqueness, permissions or money. See Eventual Consistency in Database Systems for why a locally updated filter lags.

Distributed data (replicas, caches, sharded stores, multi-region) ​

Distributed stores are where Bloom filters live by default. Cassandra and ScyllaDB build one filter per SSTable per node; a coordinator contacts replicas and each replica uses its own filters, so a filter's effect is local and invisible to clients. A sharded Redis cluster keeps each BF.* key on one shard; a "global" filter needs either one key (a hotspot) or a hash by key prefix. Read replicas do not share filters with the primary (a PostgreSQL bloom index is physical and is replicated through WAL like any index; a Redis Bloom key replicates as a value). Per-region HyperLogLogs can be merged centrally with PFMERGE because the merge is exactly the union. Caches: a client-side filter of "keys known to be missing" prevents stampedes against a database after a cache restart, but it must be warmed; see the doorkeeper pattern above.

Step  Scenario: Cassandra node, read after compaction
1     Compaction merges 4 SSTables       writes SST-9 with a NEW Bloom filter sized for SST-9's keys
2     ALTER TABLE ... bloom_filter_fp_chance = 0.01     existing SSTables keep their old filters
3     nodetool upgradesstables -a        rewrites SSTables, rebuilding filters at 0.01
4     read                               only filters of the rewritten files have the new rate

Scaling path ​

ScaleDesignProbabilistic structures
1x: one database, thousands of usersExact structures everywhereMaybe BRIN on a log table
10x: millions of rowsAdd indexes carefullyPostgreSQL bloom for wide search tables; PFADD for visitors
100x: billions of rows, read replicas, Redis tierPartition, cache, replicateExistence filter in front of the cache; BRIN per partition; Count-Min for hot keys; TinyLFU-style admission
1000x: LSM stores, analytics lakeCassandra/RocksDB/Parquet/SparkPer-SSTable and per-row-group filters, runtime join filters, HyperLogLog everywhere, t-digest for latency

At each step, the question is "what does a wrong answer cost, and is there a cheap exact check behind it?"

Lab ​

Docker is the easiest way to get PostgreSQL 16+ and Redis (the commands below were not run on the authoring machine because neither server was installed there; the PostgreSQL figures quoted are from the official documentation, everything else is "typical" and yours will differ).

Setup ​

sh
docker run -d --name pg -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:17
docker run -d --name rs -p 6379:6379 redis:8
psql postgresql://postgres:pw@localhost:5432/postgres

Experiment 1: PostgreSQL bloom vs btree on 10 columns ​

sql
CREATE EXTENSION bloom;
CREATE TABLE tbloom AS
SELECT (random()*1000000)::int AS c1, (random()*1000000)::int AS c2, (random()*1000000)::int AS c3,
       (random()*1000000)::int AS c4, (random()*1000000)::int AS c5, (random()*1000000)::int AS c6,
       (random()*1000000)::int AS c7, (random()*1000000)::int AS c8, (random()*1000000)::int AS c9,
       (random()*1000000)::int AS c10
FROM generate_series(1, 5000000);
ANALYZE tbloom;

EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM tbloom WHERE c3 = 123456 AND c8 = 654321;
-- Seq Scan, hundreds of ms

CREATE INDEX bt_all ON tbloom (c1,c2,c3,c4,c5,c6,c7,c8,c9,c10);
EXPLAIN (ANALYZE) SELECT * FROM tbloom WHERE c3 = 123456 AND c8 = 654321;
-- still a Seq Scan or a full index scan: leading column c1 is not constrained
SELECT pg_size_pretty(pg_relation_size('bt_all'));          -- several hundred MB

DROP INDEX bt_all;
CREATE INDEX bl_all ON tbloom USING bloom (c1,c2,c3,c4,c5,c6,c7,c8,c9,c10) WITH (length = 160);
EXPLAIN (ANALYZE) SELECT * FROM tbloom WHERE c3 = 123456 AND c8 = 654321;
-- Bitmap Heap Scan + Bitmap Index Scan on bl_all; look at "Rows Removed by Index Recheck"
SELECT pg_size_pretty(pg_relation_size('bl_all'));           -- far smaller than bt_all

-- Ten single-column btrees: fastest query, biggest total size
DO $$ BEGIN FOR i IN 1..10 LOOP EXECUTE format('CREATE INDEX ON tbloom (c%s)', i); END LOOP; END $$;
SELECT pg_size_pretty(sum(pg_relation_size(indexrelid))) FROM pg_index WHERE indrelid = 'tbloom'::regclass;

Expected shape (PostgreSQL docs, 10M rows, 6 columns): sequential scan 357 ms; bloom 22.6 ms; separate btrees 0.047 ms; sizes 153 MB (bloom), 386 MB (one wide btree), 531 MB (six btrees). Try WHERE c3 = ... AND c8 = ... AND c10 > 5 and observe that the range predicate is not served by the Bloom index.

Experiment 2: Redis PFADD / PFCOUNT accuracy ​

redis-cli
> PFADD hll:demo a b c d
(integer) 1
> PFADD hll:demo a
(integer) 0
> PFCOUNT hll:demo
(integer) 4
> DEBUG OBJECT hll:demo      # or MEMORY USAGE hll:demo: small, sparse encoding

Load a million distinct items and compare (shell loop is slow; use redis-cli --pipe or a script):

sh
python3 - <<'PY' | redis-cli --pipe
for i in range(1_000_000):
    print(f"PFADD hll:big user-{i}")
PY
redis-cli PFCOUNT hll:big        # typically within about 1% of 1000000 (standard error 0.81%)
redis-cli MEMORY USAGE hll:big   # about 12304 bytes: 12 KB regardless of count
redis-cli PFADD hll:b user-0 user-1 user-9999999
redis-cli PFMERGE hll:union hll:big hll:b
redis-cli PFCOUNT hll:union      # about 1000001

Experiment 3: BRIN on a time-ordered table ​

sql
CREATE TABLE events AS
SELECT g AS id, now() - (interval '1 second' * (5000000 - g)) AS created_at, md5(g::text) AS payload
FROM generate_series(1, 5000000) g;
ANALYZE events;
SELECT correlation FROM pg_stats WHERE tablename = 'events' AND attname = 'created_at';   -- ~1

CREATE INDEX ev_btree ON events (created_at);
CREATE INDEX ev_brin ON events USING brin (created_at) WITH (pages_per_range = 32);
SELECT pg_size_pretty(pg_relation_size('ev_btree')), pg_size_pretty(pg_relation_size('ev_brin'));
-- btree ~ 100+ MB, BRIN well under 1 MB

DROP INDEX ev_btree;
EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM events WHERE created_at >= now() - interval '1 hour';
-- Bitmap Heap Scan using ev_brin; "Rows Removed by Index Recheck" is small

-- Break the correlation and watch BRIN stop skipping
UPDATE events SET created_at = created_at - (random() * interval '30 days');
VACUUM ANALYZE events;
SELECT correlation FROM pg_stats WHERE tablename = 'events' AND attname = 'created_at';   -- near 0
EXPLAIN (ANALYZE) SELECT count(*) FROM events WHERE created_at >= now() - interval '1 hour';
-- most of the table is now visited: BRIN no longer helps

Experiment 4: the Go programs ​

sh
cd docs/snippets/database/bloom-filters-probabilistic/go
go run ./cmd/bloomfpr      # FPR vs formula at 4..16 bits per key
go run ./cmd/hllaccuracy   # HyperLogLog error vs 0.81%
go run ./cmd/cmsdemo       # Count-Min over a Zipf stream

Experiment 5: Bloom and Cuckoo in Redis (needs the Bloom module) ​

> BF.RESERVE seen 0.01 100000
OK
> BF.ADD seen user:1
(integer) 1
> BF.ADD seen user:1
(integer) 0
> BF.EXISTS seen user:2
(integer) 0
> CF.RESERVE cf 100000
> CF.ADD cf user:1
> CF.DEL cf user:1
> CF.EXISTS cf user:1
(integer) 0

Common misconceptions ​

BeliefReality
A Bloom filter says an item is in the setIt says "definitely not" or "probably", never "definitely yes"
Bloom filters can have false negatives if I use too few bitsNo: bits are never cleared; only the false positive rate rises
More hash functions always means fewer errorsThere is an optimum k = 0.693 * bits per key; beyond it the array fills and errors rise
Every probe needs an independent hashTwo hashes (double hashing) are enough
I can keep adding keys to a sized filterFPR degrades quickly past the planned n; use scalable filters or rebuild
Counting Bloom filters make deletion safeOnly for keys you really inserted; otherwise false negatives
Cuckoo filters never failInserts fail when the table is full; duplicates can overflow buckets
PFADD returning 1 means the item is newIt means a register changed; duplicates can also change it rarely, and a new item can leave it at 0
HyperLogLog gives exact counts for small setsRedis uses sparse encoding for small sets and is accurate there, but still an estimate
Summing daily PFCOUNTs gives weekly uniquesUse one PFCOUNT over several keys or PFMERGE
Count-Min estimates are unbiasedThey never underestimate; they over-estimate
BRIN is a smaller btreeBRIN needs physical correlation; on random data it skips nothing
The PostgreSQL bloom index beats btreeIt is smaller and handles arbitrary column combinations, but is slower than a matching btree
Bloom filters speed up range scansOnly point lookups (or prefix filters for Seek)
Partition pruning uses Bloom filtersIt uses exact partition bounds

Cheat sheet ​

TopicWhat to remember
Bloom guaranteeNo false negatives; false positives at rate p
Bits per key1.44 log2(1/p): 10 bits for 1%, 14.4 for 0.1%
Optimal k0.693 * bits per key (7 at 10 bits)
FPR formula(1 - e^(-kn/m))^k
Over-fillingDoubling n at fixed m multiplies FPR many times
DeletionCounting (4x memory) or Cuckoo filter (CF.DEL)
GrowthScalable Bloom (EXPANSION, NONSCALING) or rebuild
Static setsXor, binary fuse, Ribbon
HyperLogLogPFADD/PFCOUNT/PFMERGE, 12 KB, 0.81%, mergeable
Count-Minw = e/eps, d = ln(1/delta), error eps*N, over-estimates only
t-digestTDIGEST.CREATE COMPRESSION 100, accurate at p99 and p99.9
PostgreSQL bloomUSING bloom, equality only, lossy, int4/text, length 80, colN 2
BRINpages_per_range 128, needs correlation, autosummarize off by default
Cassandrabloom_filter_fp_chance 0.01 (0.1 LCS), off-heap, applies to new SSTables
RocksDBNewBloomFilterPolicy(10); watch rocksdb.bloom.filter.useful
AnalyticsSpark runtime Bloom filter (3.3+), Parquet split block Bloom filters
CachesDoorkeeper + Count-Min = TinyLFU; filter in front of cache stops penetration
Not forMoney, permissions, uniqueness, exact audits, range queries

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A Bloom filter returns true for a key. What do you know? Must-know ​

Answer

Answer: Only that the key is probably in the set; it could be a false positive at rate about p. A false answer is certain. See How it works.

2 — How many bits per key does a 1% false positive rate need, and what is the optimal k? Important ​

Answer

Answer: About 9.6 bits per key (1.44 log2(100)), k = 0.693 * 9.6, about 7. See Sizing.

3 — Why can a standard Bloom filter not have false negatives, and how can a counting filter get one? Important ​

Answer

Answer: Bits only go from 0 to 1, so every added key's bits stay set. A counting filter decrements counters on delete; deleting a key that was never inserted lowers counters shared with real keys, which can later read 0. See Counting.

4 — Why does RocksDB confine a key's probes to one cache line, and what does it cost? Good to know ​

Answer

Answer: One cache miss per probe set; the cost is slightly higher FPR (about 0.95% vs 0.84% at 10 bits per key, from the RocksDB wiki). See k hashes.

5 — When is a Cuckoo filter better than a Bloom filter, and what can go wrong? Important ​

Answer

Answer: When you need deletion or a low target FPR. Inserts can fail when the table is full, and deleting an item never inserted can remove another item's fingerprint. See Cuckoo.

6 — What error does HyperLogLog have in Redis and how much memory does it use? Important ​

Answer

Answer: Standard error 0.81% (1.04/sqrt(16384)); up to 12 KB per key. See HyperLogLog.

7 — You want weekly unique visitors from seven daily HyperLogLogs. How? Important ​

Answer

Answer: PFCOUNT d1 ... d7 or PFMERGE week d1 ... d7 then PFCOUNT week. Summing seven PFCOUNTs double counts people who visited on several days.

8 — A Count-Min estimate says 25 for a key that you think appeared twice. Is the sketch broken? Important ​

Answer

Answer: No. Errors are up to eps*N in total stream size; low counts are noise. The sketch never underestimates and is for heavy hitters. See Count-Min.

9 — When does a PostgreSQL BRIN index skip nothing? Important ​

Answer

Answer: When the column is not correlated with the physical row order (random inserts, heavy updates), so every block range contains the whole value range. Check pg_stats.correlation. See BRIN.

10 — Why do Cassandra and RocksDB need Bloom filters at all? Must-know ​

Answer

Answer: A key can be in any of many immutable SSTables; without a filter a miss reads a block from each. A filter makes most files skippable in RAM. See LSM filters.

11 — Why is the PostgreSQL bloom index slower than six single-column btrees yet still useful? Good to know ​

Answer

Answer: It scans all signatures and rechecks the heap, but it is one index of about a third of the size, serving any combination of equality predicates. See PostgreSQL bloom index.

12 — When must you not rely on a Bloom filter? Must-know ​

Answer

Answer: When a wrong "yes" is harmful and there is no exact recheck: uniqueness, permissions, money. See When not to use.

Glossary ​

TermMeaning
Bloom filterBit array and k hashes giving "definitely not" or "probably yes"
False positiveThe filter says present for a key that was never added
False negativeThe filter says absent for a key that was added; impossible in a plain Bloom filter
FPRFalse positive rate, p
Bits per element / per keym / n; for optimal k, 1.44 log2(1/p)
k hash functionsNumber of bit positions set per key; optimal k = (m/n) ln 2
Double hashingDeriving k probes from two hashes: h1 + i*h2
Scalable Bloom filterA chain of filters that grows with the data (Redis EXPANSION, NONSCALING)
Counting Bloom filterCounters instead of bits; supports delete; about 4x memory
Cuckoo filterTable of fingerprints in two candidate buckets; supports delete
Partial-key cuckoo hashingComputing the alternate bucket from the first bucket and the fingerprint
Quotient filterCompact hash table of remainders with metadata bits; mergeable
Xor filter / binary fuse filterImmutable filters, smaller and faster than Bloom
Ribbon filterImmutable filter solving a linear system; ~30% less space (RocksDB)
HyperLogLogFixed-memory distinct-count estimator, error 1.04/sqrt(m)
RegisterOne of m small counters in HyperLogLog holding a maximum rank
PFADD / PFCOUNT / PFMERGERedis HyperLogLog commands
Count-Min sketchGrid of counters estimating frequencies; never underestimates
Heavy hitterA frequent key; what Count-Min is good at finding
t-digestMergeable percentile sketch, accurate at the tails
MinHashSignature estimating Jaccard similarity of sets
LSHLocality-sensitive hashing; bands of signatures to find similar items
SSTableImmutable sorted file in an LSM engine; owns one filter
bloom_filter_fp_chanceCassandra table option for the SSTable filter FPR
bloom extensionPostgreSQL index access method with row signatures
SignatureLossy per-row bit pattern in a PostgreSQL bloom index
BRINBlock Range Index: per-page-range summaries
pages_per_rangeBRIN storage parameter: pages summarised together (default 128)
minmax-multiBRIN operator class storing several intervals per range
Semi-join reductionDropping rows of a big table that cannot join, using a filter from the small side
Runtime / dynamic filterA filter built during execution and pushed to a scan
Partition pruningExact exclusion of partitions by bounds (not a Bloom filter)
TinyLFUCache admission policy using a Count-Min sketch and a doorkeeper
DoorkeeperSmall Bloom filter absorbing one-hit wonders
Cache penetrationRequests for keys that exist nowhere, always missing the cache
Read amplificationExtra reads per lookup; what SSTable filters reduce

References ​

Built by Morteza Negahi