Cuckoo Hashing
Chaining and open addressing give expected lookups, but an unlucky key may sit in a long chain or at the end of a long probe sequence; with keys in slots the longest chain is with high probability. Cuckoo hashing (Pagh and Rodler, 2001; journal version 2004) guarantees that every lookup reads at most two slots, in the worst case, while insertions take expected amortized time. The price is a load factor below and an insertion procedure that occasionally rebuilds the table.
The structure
Two tables and of slots each and two hash functions . Invariant: every key is stored either in or in .
- LOOKUP: check those two slots. Two probes, worst case.
- DELETE: find it and clear the slot. Worst case .
- INSERT: put in . If the slot was occupied by , is kicked out (like a cuckoo chick pushing an egg out of the nest) and moves to its other slot, , possibly kicking out a third key, and so on. If the chain of evictions exceeds a limit of steps, assume it is cycling: pick new hash functions and rehash everything.
INSERT(x)
1 if LOOKUP(x) return
2 i = 0
3 repeat MAX-LOOP times
4 swap x with T[i][h_i(x)] // place x, pick up the previous occupant
5 if x == NIL return // the slot was free
6 i = 1 - i // the evicted key goes to its other table
7 REHASH with new h_0, h_1, then INSERT(x)The cuckoo graph and the load threshold
Think of the slots as vertices and of each key as an edge between and : the cuckoo graph, a random bipartite multigraph. A set of keys can be stored if and only if every connected component of this graph has at most one cycle (a component with vertices can hold at most keys, one per slot). Insertion walks along the component of the new edge.
For random edges on vertices, random graph theory says that while , components are small (logarithmic size) trees or unicyclic with high probability, and a component with two cycles appears with probability . At , a giant component appears and failure becomes likely. So the load threshold is
Theorem (Pagh and Rodler). If for a constant , and the hash functions are drawn from a family with sufficient independence (-wise independent suffices for their proof; for practical functions it holds empirically), then INSERT takes expected amortized time, including rehashes, and LOOKUP and DELETE take worst-case time.
Why insertions are $O(1)$ expected (sketch)
The number of evictions of an insertion is at most the size of the component of the new edge, times 2 (the walk can traverse a cycle and come back). In a random graph with edges on vertices, the probability that a given vertex lies in a component of size at least decays exponentially in , so the expected walk length is . A rehash happens only when some component has two cycles, with probability per insertion, and costs expected, adding to the expectation.
An implementation
The program uses two tables of 5000 slots, seeded splitmix64 hash functions and a rehash on failure. It inserts 4500 keys (load ) and reports the average number of evictions per insertion as the load grows.
import random
MASK = (1 << 64) - 1
def mix64(x):
x = (x + 0x9E3779B97F4A7C15) & MASK
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
return x ^ (x >> 31)
class Cuckoo:
"""Cuckoo hashing (Pagh and Rodler): two tables of r slots; x lives in T[0][h0(x)] or T[1][h1(x)]."""
def __init__(self, r, rng, max_kicks=None):
self.r, self.rng = r, rng
self.max_kicks = max_kicks or 6 * max(1, r.bit_length())
self._new_functions()
self.T = [[None] * r, [None] * r]
self.n = self.kicks = self.rehashes = 0
def _new_functions(self):
self.seeds = (self.rng.getrandbits(64), self.rng.getrandbits(64))
def _h(self, i, x):
return mix64(x ^ self.seeds[i]) % self.r
def contains(self, x): # at most 2 probes, worst case
return self.T[0][self._h(0, x)] == x or self.T[1][self._h(1, x)] == x
def insert(self, x):
if self.contains(x): return True
i = 0
for _ in range(self.max_kicks):
slot = self._h(i, x)
x, self.T[i][slot] = self.T[i][slot], x # put x here, pick up the previous occupant
if x is None:
self.n += 1; return True
self.kicks += 1
i = 1 - i # the evicted key goes to its other table
return False # probably a cycle: caller rehashes
def rehash_insert(self, x):
while not self.insert(x): # x is the key left homeless
self.rehashes += 1
keys = [k for t in self.T for k in t if k is not None] + [x]
self._new_functions()
self.T, self.n = [[None] * self.r, [None] * self.r], 0
x = None
for k in keys:
if not self.insert(k):
x = k; break # failed again: rehash again
if x is None: return
rng = random.Random(2001)
r = 5000 # 10000 slots in total
c = Cuckoo(r, rng)
keys = rng.sample(range(10 ** 9), int(0.45 * 2 * r))
checkpoints = {int(f * 2 * r): f for f in [0.1, 0.2, 0.3, 0.4, 0.45]}
for j, x in enumerate(keys, 1):
c.rehash_insert(x)
if j in checkpoints:
print(f"load {checkpoints[j]:.2f}: {c.kicks / j:.3f} evictions per insert so far, rehashes {c.rehashes}")
assert all(c.contains(x) for x in keys)
absent = sum(c.contains(x) for x in range(10 ** 9, 10 ** 9 + 20000))
print(f"{len(keys)} keys stored, every lookup probes at most 2 slots; false hits on 20000 absent keys: {absent}")load 0.10: 0.109 evictions per insert so far, rehashes 0
load 0.20: 0.200 evictions per insert so far, rehashes 0
load 0.30: 0.308 evictions per insert so far, rehashes 0
load 0.40: 0.465 evictions per insert so far, rehashes 0
load 0.45: 0.556 evictions per insert so far, rehashes 0
4500 keys stored, every lookup probes at most 2 slots; false hits on 20000 absent keys: 0
Evictions stay below one per insertion on average, growing as the load approaches the threshold. The next program fills tables until the first failure (no rehashing), for three table sizes and five random runs each.
import random
MASK = (1 << 64) - 1
def mix64(x):
x = (x + 0x9E3779B97F4A7C15) & MASK
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
return x ^ (x >> 31)
class Cuckoo:
"""Cuckoo hashing (Pagh and Rodler): two tables of r slots; x lives in T[0][h0(x)] or T[1][h1(x)]."""
def __init__(self, r, rng, max_kicks=None):
self.r, self.rng = r, rng
self.max_kicks = max_kicks or 6 * max(1, r.bit_length())
self._new_functions()
self.T = [[None] * r, [None] * r]
self.n = self.kicks = self.rehashes = 0
def _new_functions(self):
self.seeds = (self.rng.getrandbits(64), self.rng.getrandbits(64))
def _h(self, i, x):
return mix64(x ^ self.seeds[i]) % self.r
def contains(self, x): # at most 2 probes, worst case
return self.T[0][self._h(0, x)] == x or self.T[1][self._h(1, x)] == x
def insert(self, x):
if self.contains(x): return True
i = 0
for _ in range(self.max_kicks):
slot = self._h(i, x)
x, self.T[i][slot] = self.T[i][slot], x # put x here, pick up the previous occupant
if x is None:
self.n += 1; return True
self.kicks += 1
i = 1 - i # the evicted key goes to its other table
return False # probably a cycle: caller rehashes
def rehash_insert(self, x):
while not self.insert(x): # x is the key left homeless
self.rehashes += 1
keys = [k for t in self.T for k in t if k is not None] + [x]
self._new_functions()
self.T, self.n = [[None] * self.r, [None] * self.r], 0
x = None
for k in keys:
if not self.insert(k):
x = k; break # failed again: rehash again
if x is None: return
# The load threshold: fill tables with random keys until the first insertion fails (no rehashing).
rng = random.Random(7)
for r in [100, 1000, 10000]:
loads = []
for trial in range(5):
c = Cuckoo(r, rng, max_kicks=500)
while c.insert(rng.getrandbits(40)):
pass
loads.append(c.n / (2 * r))
print(f"r = {r:5} slots per table: first failure at load " + ", ".join(f"{x:.3f}" for x in loads))r = 100 slots per table: first failure at load 0.735, 0.600, 0.645, 0.645, 0.550
r = 1000 slots per table: first failure at load 0.536, 0.576, 0.538, 0.573, 0.565
r = 10000 slots per table: first failure at load 0.508, 0.515, 0.522, 0.521, 0.480
Small tables survive beyond load by luck; as grows, the failure point concentrates near , the threshold of the random graph.
In C++
A cuckoo set with std::optional slots for a million slots in total, loaded to 0.45, with an explicit rehash loop for the rare failure.
#include <cstdint>
#include <cstdio>
#include <optional>
#include <random>
#include <utility>
#include <vector>
std::uint64_t mix64(std::uint64_t x) {
x += 0x9E3779B97F4A7C15ULL;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL;
return x ^ (x >> 31);
}
class CuckooSet {
std::size_t r;
std::vector<std::optional<std::uint64_t>> T[2];
std::uint64_t seed[2];
std::mt19937_64& rng;
std::size_t h(int i, std::uint64_t x) const { return mix64(x ^ seed[i]) % r; }
bool try_insert(std::uint64_t x) {
int i = 0;
for (int step = 0; step < 200; ++step) {
auto& slot = T[i][h(i, x)];
if (!slot) { slot = x; return true; }
std::swap(x, *slot); // evict the occupant, carry it on
++kicks;
i = 1 - i;
}
pending = x; // the key left without a slot
return false;
}
void rehash() {
++rehashes;
std::vector<std::uint64_t> keys{pending};
for (auto& t : T) for (auto& s : t) if (s) keys.push_back(*s);
for (;;) {
seed[0] = rng(); seed[1] = rng();
for (auto& t : T) t.assign(r, std::nullopt);
bool ok = true;
for (auto k : keys) if (!try_insert(k)) { ok = false; break; }
if (ok) return;
++rehashes;
}
}
std::uint64_t pending = 0;
public:
long kicks = 0, rehashes = 0;
CuckooSet(std::size_t slots_per_table, std::mt19937_64& g) : r(slots_per_table), rng(g) {
seed[0] = rng(); seed[1] = rng();
for (auto& t : T) t.assign(r, std::nullopt);
}
bool contains(std::uint64_t x) const { return T[0][h(0, x)] == x || T[1][h(1, x)] == x; }
void insert(std::uint64_t x) { if (!contains(x) && !try_insert(x)) rehash(); }
};
int main() {
std::mt19937_64 rng(2001);
const std::size_t r = 500000;
CuckooSet s(r, rng);
std::vector<std::uint64_t> keys;
for (std::size_t i = 0; i < 450000; ++i) keys.push_back(rng() >> 1); // load 0.45 of 2r slots
for (auto k : keys) s.insert(k);
std::size_t found = 0, false_hits = 0;
for (auto k : keys) found += s.contains(k);
for (int i = 0; i < 100000; ++i) false_hits += s.contains((rng() >> 1) | (1ULL << 63));
std::printf("%zu keys at load 0.45: %.3f evictions per insert, %ld rehashes\n",
keys.size(), double(s.kicks) / keys.size(), s.rehashes);
std::printf("found %zu of %zu, false hits %zu; every lookup reads 2 slots\n", found, keys.size(), false_hits);
}450000 keys at load 0.45: 0.554 evictions per insert, 0 rehashes
found 450000 of 450000, false hits 0; every lookup reads 2 slots
Raising the load factor
A load below 50% wastes half the space. Two generalizations push the threshold up, at the cost of more probes per lookup, still worst case:
| Variant | Lookup probes (worst case) | Load threshold |
|---|---|---|
| 2 tables, 1 key per slot (Pagh and Rodler) | 2 | |
| hash functions, 1 key per slot (Fotakis, Pagh, Sanders and Spirakis, 2005) | 3 | about |
| hash functions | 4 | about |
| 2 hash functions, buckets of 4 slots (Dietzfelbinger and Weidling, 2007) | 8 slots in 2 buckets | about |
The thresholds for were determined exactly around 2009 to 2010 by several groups (Dietzfelbinger, Goerdt, Mitzenmacher, Montanari, Pagh and Rink; Fountoulakis and Panagiotou; Frieze and Melsted). A stash of a few extra slots (Kirsch, Mitzenmacher and Wieder, 2009) reduces the failure probability from to with a stash of size . Bucketed cuckoo hashing is the basis of cuckoo filters (Fan et al. 2014), which replace Bloom filters when deletions are needed, and of many hardware and network lookup tables, because a lookup touches exactly two cache lines.
Test yourself
How many table slots does a cuckoo hashing lookup read in the worst case?
- 1
- 2
In the cuckoo graph, when can a set of keys be stored?
- When the graph is a tree
- When every connected component has at most one cycle
- When the graph is bipartite
- When no two keys share a slot under
With two tables of slots each, which load keeps the expected insertion time ?
- , a load below of the slots
- Any load