SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Bloom Filters
  • Cuckoo Filter
  • Skip Lists
  • Count-Min Sketch
  • HyperLogLog
  • Merkle Trees
  • MinHash
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Probabilistic and Other Structures

Cuckoo Filter

Like a Bloom filter, but you can also delete items.

โฑ 12 min readAdvancedHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A cuckoo filter is a small structure, like a Bloom filter, that answers "is this item in the set?" with "definitely not" or "maybe yes". The big difference: it can also delete items.

  • It stores a short fingerprint of each item in a table of small buckets, instead of switching on bits.
  • Every item has exactly two possible buckets. A lookup checks only those two, so it is quick.
  • When both buckets are full, it kicks out a resident fingerprint to its other bucket, like a cuckoo bird pushing eggs out of a nest.

02Concept: What is it?

For each item the filter computes a short fingerprint (for example 8 bits) and two bucket numbers. The first bucket is a hash of the item. The second is the first bucket combined (XOR) with a hash of the fingerprint:

Where does an item live?
fingerprint = short_hash(item)
bucket1     = hash(item) % number_of_buckets
bucket2     = bucket1 XOR hash(fingerprint)

Because XOR works both ways, bucket1 = bucket2 XOR hash(fingerprint) too. So given only a bucket and the fingerprint stored in it, the filter can find the other bucket without knowing the original item. That is what makes kicking out possible.

Insert, and what happens when buckets are full
Free slot found
๐Ÿ”‘new fingerprint
โ†“bucket 1 or 2 has space
โœ…stored
Both buckets full
๐Ÿ”‘new fingerprint
โ†“take a slot, push the owner out
๐Ÿฆevicted fingerprintmoves to its other bucket
โ†“repeat until a free slot (or give up)
A new fingerprint takes a free slot in either bucket. If both are full, it pushes a resident one out, and that one moves to its own other bucket.
๐Ÿง Fingerprints, not items
The filter never stores the item. So it cannot tell two different items with the same fingerprint and bucket apart. That is the source of false positives. Longer fingerprints mean fewer of them.

03Real-Life Example

๐ŸตThe Coat Check With Two Hooks
A small coat check has numbered racks, and each rack holds a few tags. When you hand in a coat, the attendant writes a short code from your name on a tag. Your name points to two racks, and the tag can go on either. If both racks are full, the attendant puts your tag on one of them anyway and moves the old tag to its other rack. That one may push another, until each tag has a place. To check if a coat is there, the attendant only looks at your two racks for a tag with your code. To return a coat, they take the tag off. A different person with the same short code could fool the check now and then, but nobody is ever told a real coat is missing.
Coat check
Cuckoo filter
A rack that holds a few tags
A bucket with a few slots
A short code from your name
The fingerprint
Your name points to two racks
Two candidate buckets
Moving an old tag to its other rack
Kicking out (relocation)
Only looking at two racks to check
A lookup touches two buckets only
Taking your tag off when you leave
Delete
Someone with the same code fools the attendant
A false positive

04Why Do We Need It?

๐Ÿ—‘๏ธDelete works
Remove a fingerprint to remove an item. A Bloom filter cannot do this without extra counters.
โšกTwo places only
A lookup reads at most two buckets, which are close in memory. Few cache misses.
๐Ÿ“‰Compact at low error
For false positive rates below about 3%, it often needs fewer bits per item than a Bloom filter.
โœ…No false negatives
As long as only items that were inserted are deleted, nothing real is ever missing.
๐Ÿ”ขCount-free
No counters like a counting Bloom filter. Space stays small.
๐Ÿ”Changing sets
A good fit when items come and go, such as sessions or recently seen IDs.
If your set changes over time and you want a tiny "have I seen this?" check, a cuckoo filter gives you delete without a big space cost.

05Where Do We Use It?

๐Ÿ”„Sets that change
Track active sessions, recent request IDs or items in a cart, where entries are added and removed.
๐ŸงนDe-duplication
Remember recent message IDs to skip duplicates, and forget old ones.
๐Ÿ›ก๏ธBlocklists with updates
A list of bad IDs that gets entries added and removed all the time.
๐ŸŒNetwork devices
Packet and flow lookups that need a tiny, fast membership test.
๐ŸŸฅRedis Stack
Offers a cuckoo filter type next to the Bloom filter type.
๐Ÿ“šLibraries
Available in most languages as a small library.

06Types / Parts / How It Works

How it is laid out

A table of buckets, each with a few slots
bucket 03A ยท ยท
bucket 1C1 7F ยท
bucket 2ยท ยท ยท
bucket 39D 04 B2
has space full mostly empty
Each cell holds one short fingerprint, or is empty. The two buckets of one item are bucket1 and bucket1 XOR hash(fingerprint).

The main operations

OperationWhat it doesCost
InsertPut the fingerprint in a free slot of bucket 1 or 2. If both are full, kick one out and relocate it, repeat up to a limit.Fast on average. Slower when the table is nearly full. May fail.
LookupCheck the slots of the two buckets for the fingerprint.At most two bucket reads.
DeleteIf the fingerprint is in one of the two buckets, clear one copy.At most two bucket reads. Only delete items you inserted.

Knobs you can turn

SettingEffectNote
Fingerprint size (f bits)Longer means fewer false positives, but more memoryFalse positive rate is roughly 2 x slots / 2^f
Slots per bucketMore slots allow a fuller tableFour slots per bucket can reach around 95% full. One slot only about half.
Number of bucketsSets capacityOften kept as a power of two so XOR stays inside the table
Max kicksHow hard to try before giving upA few hundred is common. After that the insert fails and the table is too full.
โš ๏ธSame item twice
Inserting the same item many times puts many copies of one fingerprint in the same two buckets, and they can fill up. Many designs avoid duplicate inserts or limit the copies.
VisualizerInsert, kick out and delete fingerprintsAdd words until the table is nearly full and watch kicks and failures. Try 4-bit fingerprints to see false positives rise, then delete a word and look it up again.
Slots per bucket
Fingerprint size
8 buckets x 2 slots. Each cell holds a 8-bit fingerprint in hex (ยท = empty). Amber = the two buckets of "alice", green = a matching fingerprint.
bucket 0d1ยท
bucket 13cd3
bucket 28f68
bucket 3ebยท
bucket 47c41
bucket 5ยทยท
bucket 68660
bucket 7ยทยท
"alice" is in the filter. Its fingerprint 8f sits in bucket 1 or bucket 2, the only two places it can ever be.
Load factor
63%
10 of 16 slots
Kicks so far
8
fingerprints moved away
Wrong yes on 400 unseen words
1.3%
measured false positives
Upper bound
1.6%
2 x slots / 2^bits

Bucket 2 is bucket 1 XOR hash(fingerprint), so a kicked fingerprint can find its other home without the original word. Each word uses the same fixed hash, so the picture repeats. Delete is safe only for a word that really was inserted.

07How to Use It / Steps / Implementation

Using a cuckoo filter well

  1. 1
    Estimate how many items
    Choose the number of buckets so the table is at most about 90% to 95% full at the largest size.
  2. 2
    Pick a fingerprint size
    Start with 8 to 12 bits. Longer fingerprints reduce false positives, and you pay in memory.
  3. 3
    Choose slots per bucket
    Four is a common choice. It balances space use and lookup cost.
  4. 4
    Insert with a kick limit
    Try both buckets, then relocate up to a set number of times. If it still fails, treat the filter as full.
  5. 5
    Handle a failed insert
    Build a bigger filter and re-insert, or add a second filter. You cannot grow it by just adding buckets, because the second bucket depends on the table size.
  6. 6
    Delete only what you inserted
    Deleting an item that was never added can remove another item's fingerprint, and then that item gets a false 'no'.
  7. 7
    Keep the real data as the truth
    A 'maybe yes' needs a check against the real store when mistakes matter.
The idea in a few lines of pseudocode
insert(item):
  f = fingerprint(item);  i1 = hash(item) % B;  i2 = i1 XOR hash(f)
  if bucket[i1] or bucket[i2] has a free slot: store f there; return ok
  i = pick i1 or i2
  repeat up to MAX_KICKS:
    swap f with a random fingerprint in bucket[i]
    i = i XOR hash(f)                 // the evicted one goes to its other bucket
    if bucket[i] has a free slot: store f; return ok
  return full
๐Ÿ’กWhy XOR?
With XOR, the move from one bucket to the other is the same both ways, and it needs only the fingerprint. So a kicked-out fingerprint finds its other home without the original item.

08Key Terms to Know

TermMeaning in easy words
Cuckoo filterA compact set-membership structure that stores fingerprints in buckets and supports delete
FingerprintA short hash of an item (for example 8 bits) stored in place of the item
BucketA small group of slots. Each item can live in one of two buckets
SlotOne cell in a bucket that holds a single fingerprint
Cuckoo hashingA hash table idea where an item has two homes and can push another one out of its place
Eviction / kickPushing a stored fingerprint out of its bucket to make room
RelocationMoving the evicted fingerprint to its other bucket
Partial-key hashingFinding the other bucket from the fingerprint alone: bucket XOR hash(fingerprint)
Load factorThe share of slots that are in use. High load makes inserts slow and may make them fail
False positiveA 'maybe yes' for an item that was never inserted, caused by an equal fingerprint in the same buckets
Max kicksThe limit on how many relocations an insert may try before it fails

09Pros, Cons and Trade-offs

โœ… Pros
  • Supports delete
  • A lookup reads at most two buckets
  • Often smaller than a Bloom filter at low error rates
  • No false negatives for items that were inserted
  • No counters needed
โš ๏ธ Cons
  • An insert can fail when the table is nearly full
  • Inserts can be slower than a Bloom filter (moves)
  • Cannot grow by simply adding buckets
  • Deleting something that was never inserted can cause a false negative
  • More complex to write and to get right

Trade-offs

ChoiceWe gainWe lose
Longer fingerprintsFewer false positivesMore memory per item
More slots per bucketHigher load before failingMore comparisons per lookup, and slightly more false positives
Higher max kicksFewer failed insertsSome inserts become slow
Cuckoo vs BloomDelete, and often less space at low errorMore complex, and inserts can fail
Cuckoo vs counting BloomLess memory, simpler lookupsA hard capacity limit
Run it nearly fullBest use of memorySlow inserts and a risk of failure

10Common Problems and Mistakes

Common mistakes

  1. Deleting items that were never inserted. It can remove another item's fingerprint and cause a false "no".
  2. Ignoring failed inserts. If an insert fails and nobody notices, items are silently missing.
  3. Too-short fingerprints. A 4-bit fingerprint gives a high false positive rate.
  4. Running the table too full. Past about 95% the kicks get long and failures become common.
  5. Inserting the same item many times. The copies fill the same two buckets.
  6. Resizing by adding buckets. The second bucket formula depends on the table size, so old fingerprints would be in the wrong places.

Things to watch

๐Ÿ“ŠLoad factor
Watch it. Rising load means longer kick chains.
๐ŸงฏInsert failures
Alert on them, and have a plan to rebuild into a larger filter.
๐Ÿ”Hash quality
Use a good hash for both the item and the fingerprint.
๐ŸงตConcurrency
Kicking moves several fingerprints at once, so shared use needs locks or a careful design.

11Real-World Examples

๐ŸŸฅRedis Stack
Provides a cuckoo filter type with add, exists and delete commands.
๐ŸงพRecent-ID tracking
A service remembers recently processed request IDs to skip repeats, and removes old IDs when they expire.
๐Ÿ›’Session and cart sets
A compact 'is this session active?' check where sessions end and must be removed.
๐ŸŒPacket filters
Fast flow lookups in network software, where the structure is checked for every packet.
๐Ÿ”ŽPre-checks for stores
Check a small filter before a costly lookup, with entries that come and go.
๐ŸงชResearch
Introduced as a practical alternative to Bloom filters that supports deletion.
๐Ÿ“Note
Defaults, such as fingerprint size, bucket size and the maximum number of kicks, differ between libraries. Read the documentation of the one you use.
Mini case: forgetting an expired session
๐Ÿ”‘Session ends
โ†’โ†“
๐ŸฆCuckoo filterdelete fingerprint
โ†’โ†“later check
โœ…'Not active'
A Bloom filter would keep the old session forever. A cuckoo filter can forget it.

12Related Topics to Read Next

Bloom Filtersโ†’

The simpler filter that this one improves on, and the best place to start.

Count-Min Sketchโ†’

Another small structure that trades exactness for memory.

HyperLogLogโ†’

Estimates how many different items, in tiny memory.

Consistent Hashingโ†’

Another idea built on hashing items to places.

Skip Listsโ†’

A different way to keep data fast to find.

Key-Value Databasesโ†’

Where small filters often guard lookups.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a table of buckets holding short fingerprints. "Definitely not" or "maybe yes".
  • โœ”Two homes: bucket1 = hash(item), bucket2 = bucket1 XOR hash(fingerprint).
  • โœ”Insert: free slot in either bucket, else kick one out and move it, up to a limit.
  • โœ”Lookup: check at most two buckets.
  • โœ”Delete: remove one copy of the fingerprint. Only for items you inserted.
  • โœ”Error: about 2 x slots / 2^f. Longer fingerprints, fewer false positives.
  • โœ”Limit: it can become full and an insert can fail. It cannot grow by just adding buckets.
  • โœ”One line: โ€œA Bloom filter that can forget.โ€
โ† Previous
Bloom Filters
Next โ†’
Skip Lists