Sub topic 12
Incremental Rehashing: Trading Amortised for Worst-Case Bounds
This chapter assumes you know the chained hash table and resize-on-load-factor design from the previous chapters. It also assumes you can read the amortised argument for doubling: total resize work over n inserts is O(n), so each insert costs O(1) amortised. You should be comfortable reading short Python programs.
The spike that amortisation hides
The doubling hash table has a good amortised bound, but a single insert can still be expensive. When the load factor crosses 0.75, one put rehashes every entry. With 98,305 entries in the table, that one call touches 98,305 entries. The other calls touch about one.
The amortised guarantee allows this. It bounds the total over a sequence of operations, not any individual operation. For many programs that is fine. It is not fine when each operation has a deadline, as in a request handler with a latency target, a game loop that must finish a frame, or a real-time controller. One slow insert can break the deadline even though the average is excellent.
Incremental rehashing keeps the total work the same and spreads it across many operations. Each operation does a small, bounded amount of migration. This replaces an amortised O(1) bound on insertion with a worst-case bound on the resize work done by any single operation. The next sections build it and then look at what the bound does and does not cover.
Idea: keep two tables and move a few buckets at a time
When the load factor passes the threshold, do not rebuild. Instead:
- Keep the current bucket array as the old table.
- Allocate a new table with twice as many buckets.
- On every subsequent
put, move a fixed number of old buckets (the step) into the new table. - When every old bucket has been moved, discard the old table.
While the migration is running, the table is in a two-table state. The rules for that state are:
- Lookups check the new table first, then the old table.
- Inserts and updates write only to the new table. If the key still lives in the old table, remove it from there first, so that no key exists in both tables.
- Migration moves whole buckets, in index order, from old to new.
Implementation
The program below compares a stop-the-world table with an incremental one. Both count how many entries a single operation moves between buckets. The largest such count is stored in max_work.
class StopTheWorldTable:
MAX_LOAD = 0.75
def __init__(self):
self._buckets = [[] for _ in range(8)]
self._size = 0
self.max_work = 0 # most entries moved by one operation
def put(self, key, value):
bucket = self._buckets[hash(key) % len(self._buckets)]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self._size += 1
if self._size > self.MAX_LOAD * len(self._buckets):
self._grow()
def _grow(self):
new_buckets = [[] for _ in range(2 * len(self._buckets))]
moved = 0
for bucket in self._buckets:
for k, v in bucket:
new_buckets[hash(k) % len(new_buckets)].append((k, v))
moved += 1
self._buckets = new_buckets
self.max_work = max(self.max_work, moved)
class IncrementalTable:
MAX_LOAD = 0.75
STEP = 2 # old buckets migrated per put
def __init__(self):
self._new = [[] for _ in range(8)]
self._old = None
self._next = 0 # index of the next old bucket to migrate
self._size = 0
self.max_work = 0
def _migrate(self):
if self._old is None:
return 0
moved = 0
for _ in range(self.STEP):
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 # migration finished
return moved
def put(self, key, value):
moved = self._migrate()
self.max_work = max(self.max_work, moved)
if self._old is not None:
old_bucket = self._old[hash(key) % len(self._old)]
for i, (k, _) in enumerate(old_bucket):
if k == key:
del old_bucket[i]
self._size -= 1 # re-counted when added to new
break
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 None:
continue
for k, v in table[hash(key) % len(table)]:
if k == key:
return v
return default
n = 100000
plain = StopTheWorldTable()
incremental = IncrementalTable()
for i in range(n):
plain.put(i, i * i)
incremental.put(i, i * i)
assert incremental.get(i) == i * i # correct even mid-migration
for i in range(n):
assert incremental.get(i) == i * i
assert incremental.max_work <= 4
print("stop-the-world max entries moved in one put:", plain.max_work)
print("incremental max entries moved in one put:", incremental.max_work)The stop-the-world table prints 98305, the size of the table when it last grew. The incremental table prints a number of at most 2, because integer keys spread evenly and each old bucket holds at most one entry.
Why the bounds hold
Two claims need support: the per-operation bound, and the claim that migration always finishes in time.
Work per operation
Each put migrates at most STEP buckets, so it moves at most STEP times the longest chain it touches. With a reasonable hash function and a load factor below 0.75, chain length is O(1) in expectation. The resize work per operation is therefore bounded by a constant, not by n.
Migration must finish before the next growth
Say the old table has N buckets. Growth starts when the table holds about 0.75N entries. The next growth would start when the new table (2N buckets) exceeds 0.75 × 2N = 1.5N entries. That means at least 0.75N more inserts happen before the next growth is due.
Migrating N buckets at STEP buckets per put takes N / STEP puts. The migration finishes in time when
N / STEP ≤ 0.75N, which gives STEP ≥ 4/3.
The smallest integer step that satisfies this is 2, so STEP = 2 is the minimum that works with this threshold. With STEP = 1, migration would take N puts, longer than the 0.75N inserts available. The load factor of the new table could then reach about 0.875 before the migration ended. The self._old is None guard in the code prevents a second growth from starting mid-migration, but chains would get longer in the meantime.
The total work does not shrink
Incremental rehashing does not make resizing cheaper. Each entry is still moved once per growth, so the total migration work over n inserts is still O(n), and the amortised cost per insert is still O(1). What changes is the shape of the cost: the big spike becomes a small constant added to many operations.
Costs and edge cases
The better worst case has costs of its own.
- Slower lookups during migration. A miss in the new table forces a second probe in the old table. Lookups for absent keys always pay both.
- Higher peak memory. Both bucket arrays exist at once, so memory use briefly reaches about 3N bucket slots instead of 2N.
- More complex code. Every operation must handle the two-table state. Deletion is the hardest case: a delete must look in both tables, and it must not leave a stale copy behind.
- Reads that do not migrate. In the code above only
putmigrates. A workload that stops inserting leaves the table in the two-table state indefinitely. Production designs often migrate on reads and deletes too, or run migration from a background step. - Pacing depends on the workload. The proof above assumes the operations that trigger growth are also the ones that drive migration. If migration only happens on inserts but the table can also shrink or have deletions, the pacing argument has to be redone.
Where else this idea appears
The same technique works for other structures with a rebuild step. A dynamic array can be grown incrementally by allocating the larger array and copying a few elements per append, with reads checking both arrays. Some well-known hash table implementations use the same approach, notably in-memory databases that cannot afford a pause on a large dictionary. The trade is always the same: extra memory, slower reads during migration, and more code, in exchange for no single long pause.
Choosing between the two designs
| Question | Stop-the-world resize | Incremental rehashing |
|---|---|---|
| Worst-case resize work in one operation | O(n) | O(1) (chain length permitting) |
| Amortised cost per insert | O(1) | O(1) |
| Peak memory during resize | Old plus new arrays | Old plus new arrays, for longer |
| Lookup cost during resize | Unchanged | Up to two table probes |
| Implementation complexity | Low | Higher, two-table invariants |
| Fits latency-sensitive code | Poorly | Well |
Use the simple version when only throughput matters, such as batch jobs or tools that run to completion. Use incremental rehashing when a single slow operation is a defect, and when you can afford the extra memory and test the two-table state carefully.
Exercises
Exercise
In the incremental table, suppose the growth threshold stays at a load factor of 0.75 and each growth doubles the bucket count. What is the smallest whole number of old buckets that must be migrated per put to finish before the next growth is due? Explain the calculation.
Show answer
With N old buckets, migration needs N / STEP puts. The next growth is due after at least 0.75N more inserts, because the new table has 2N buckets and grows at 1.5N entries while growth started at 0.75N. So N / STEP ≤ 0.75N, which gives STEP ≥ 4/3. The smallest whole number is 2.
Exercise
A caller does put(5, "a") while the key 5 sits in a not-yet-migrated old bucket. Describe what the code does, and what would go wrong if put skipped the removal from the old table.
Show answer
put finds key 5 in the old bucket, deletes it there and decrements the size, then adds the new value to the new table and increments the size. If the removal were skipped, key 5 would exist in both tables. A later migration of that old bucket would append the stale value to the new table, creating a duplicate entry whose stale copy could be read in preference to the update, and the size count would be too high.