Sub topic 12
Incremental rehashing: trading amortised for worst-case bounds
This chapter assumes you know how a chained hash table works, what the load factor is, and why doubling the bucket array gives O(1) amortised insertion. Earlier chapters showed that bound. Here we look at what it hides and how to remove the hidden cost.
The problem with one big rehash
A doubling hash table is cheap on average. The insert that crosses the load-factor threshold, however, rehashes every entry in one step. With n entries, that single put costs Θ(n).
Many programs can ignore this. A latency-sensitive server cannot. If one request in a million stalls for 200 ms while a table of 50 million entries rehashes, the p99.99 latency suffers, and the average hides it.
The idea: spread the work
Incremental rehashing keeps two tables during a resize. A resize starts by allocating the new, larger table. Each following operation then moves a small, fixed number of old buckets into the new table. When the old table is empty, it is discarded.
While migrating, the rules are:
- Inserts go to the new table, except an update of a key that still sits in an unmigrated old bucket.
- Lookups check the new table first, then the old one.
- Every
putfirst moves a fixed number of old buckets.
An implementation
class IncrementalHashTable:
MAX_LOAD = 0.75
MIGRATE_PER_OP = 2 # old buckets moved per put
def __init__(self):
self._new = [[] for _ in range(8)]
self._old = None
self._next = 0 # next old bucket to migrate
self._size = 0
self.max_moved = 0 # most entries moved by a single put
def _step(self):
if self._old is None:
return
moved = 0
for _ in range(self.MIGRATE_PER_OP):
if self._next >= len(self._old):
break
for k, v in self._old[self._next]:
self._new[hash(k) % len(self._new)].append((k, v))
moved += 1
self._old[self._next] = []
self._next += 1
if self._next >= len(self._old):
self._old = None
self.max_moved = max(self.max_moved, moved)
def put(self, key, value):
self._step()
if self._old is not None:
bucket = self._old[hash(key) % len(self._old)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket = self._new[hash(key) % len(self._new)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self._size += 1
if self._old is None and self._size > self.MAX_LOAD * len(self._new):
self._old = self._new
self._new = [[] for _ in range(2 * len(self._old))]
self._next = 0
def get(self, key, default=None):
for table in (self._new, self._old):
if table is not None:
for k, v in table[hash(key) % len(table)]:
if k == key:
return v
return default
table = IncrementalHashTable()
for i in range(10000):
table.put(i, i * i)
assert all(table.get(i) == i * i for i in range(10000))
assert table.max_moved < 10
print("largest single-put migration:", table.max_moved)With plain doubling, the worst put in this run would move thousands of entries. Here no put moves more than a handful.
Why migration always finishes
Suppose the old table has m buckets. A resize begins when it holds more than 0.75m entries. The new table has 2m buckets, so the next resize cannot begin until it holds more than 1.5m entries. That takes at least 0.75m further inserts. At 2 buckets per insert, the migration needs only about m/2 inserts to move all m old buckets. It always finishes first, so the code never has three tables alive.
What you trade
| Property | Single rehash | Incremental rehash |
|---|---|---|
| Worst-case `put` | Θ(n) | O(1) buckets moved, plus bucket length |
| Amortised `put` | O(1) | O(1) |
| Lookup | One table | Up to two tables |
| Memory during resize | Old plus new, briefly | Old plus new, for the whole migration |
| Code complexity | Low | Higher: two tables, extra invariants |
The amortised cost stays constant. You are paying a small constant on every operation to avoid one huge payment.
Real systems use this technique. Redis's main dictionary rehashes incrementally, and Go's built-in map evacuates old buckets gradually as it grows.
Exercise
In the implementation above, why must get check the old table as well as the new one, and why can put of an existing key not simply append to the new table?
Show answer
Entries in old buckets that have not been migrated yet exist only in the old table, so a lookup that checks only the new table would miss them. If put appended an existing key to the new table without checking the old bucket, the key would exist twice, with a stale value still in the old table. Migration would later copy the stale value into the new table and create a duplicate. Updating the old entry in place avoids this.