Sub topic 12
Incremental Resizing to Avoid Latency Spikes
This chapter assumes you know how a simple resize works: when the load factor passes a threshold, you allocate a bigger array and rehash every entry. It also assumes you can read Python.
The problem with a full resize
A full resize is O(n). Doubling makes the amortized cost of an insert O(1), but amortized cost is an average. The one insert that triggers the resize still moves every entry, so it takes far longer than the others.
For a batch job this does not matter. For a server with a response-time target, it does. A table with 50 million entries can stall a single request for hundreds of milliseconds. That request shows up as a tail-latency spike (p99 or p99.9), even though the average looks fine. Because the whole table is rebuilt at once, a single-threaded system such as a cache also blocks every other client during the rebuild.
The idea: spread the work out
Incremental resizing keeps two bucket arrays during a resize. The new array is allocated empty. After that, each operation on the table moves a few buckets from the old array into the new one. Once the old array is empty, it is dropped.
The total work is the same as in a full resize. What changes is the worst case for a single operation, which is now a small constant number of bucket moves.
Rules while two arrays exist
Entries now live in one of two places, so every operation needs a rule:
- Lookup: check the new array first, then the old one.
- Insert or update: write only to the new array. If the key is still in the old array, delete it there so no stale copy remains.
- Size: count entries across both arrays, so the load factor stays meaningful.
- No second resize: do not start another resize until the current one finishes.
A working implementation
class IncrementalTable:
def __init__(self, capacity=8, max_load=0.75, step=2):
self._new = [[] for _ in range(capacity)]
self._old = None
self._next = 0 # next old bucket to migrate
self._size = 0
self._max_load = max_load
self._step = step # old buckets moved per operation
@property
def migrating(self):
return self._old is not None
def _migrate(self):
if self._old is None:
return
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))
self._old[self._next] = []
self._next += 1
if self._next >= len(self._old):
self._old = None
def put(self, key, value):
self._migrate()
if self._old is not None:
ob = self._old[hash(key) % len(self._old)]
for i, (k, _) in enumerate(ob):
if k == key:
del ob[i]
self._size -= 1
break
nb = self._new[hash(key) % len(self._new)]
for i, (k, _) in enumerate(nb):
if k == key:
nb[i] = (key, value)
return
nb.append((key, value))
self._size += 1
if self._old is None and self._size / len(self._new) > self._max_load:
self._old = self._new
self._new = [[] for _ in range(len(self._old) * 2)]
self._next = 0
def get(self, key, default=None):
self._migrate()
for k, v in self._new[hash(key) % len(self._new)]:
if k == key:
return v
if self._old is not None:
for k, v in self._old[hash(key) % len(self._old)]:
if k == key:
return v
return default
table = IncrementalTable()
for i in range(1000):
table.put(i, i * i)
print(all(table.get(i) == i * i for i in range(1000)))
print(table.migrating)The check prints True, which means every key is found even though resizes happened in the middle of the inserts.
Choosing the step size
The step size must be large enough that migration finishes before the new array reaches its own threshold. Say the old array has C buckets and the resize started at load 0.75. With a step of 2, migration takes C/2 operations. In that time the new array (2C buckets) gains at most 0.5C entries, so its load rises from about 0.375 to about 0.625, still under 0.75. A step of 1 would not be safe under a doubling policy with this threshold.
A larger step finishes sooner but makes each operation slower. The step size trades off peak latency against how long you pay for the second array.
Costs and gotchas
- Memory: both arrays exist during a resize, so peak memory is higher than the final size suggests.
- Slower reads: a lookup that misses in the new array also probes the old one.
- Complexity: iteration, deletion, and concurrent access must all handle two arrays. Deletion must check both.
Real systems use this technique. Redis keeps two hash tables and a rehash index, and moves buckets during normal commands. Go's built-in map also grows by evacuating old buckets gradually.
Exercise
In the code above, why does put() delete the key from the old array before writing to the new one?
Show answer
If the key stayed in the old array, the migration step would later copy the stale value into the new array. That could create a duplicate entry or overwrite the fresh value. Deleting the old copy first keeps exactly one entry per key and keeps the size count correct.