Skip to content

Pre-allocate the slab in reserve() - #123

Merged
arthurprs merged 1 commit into
masterfrom
reserve-slab-capacity
Jun 24, 2026
Merged

arthurprs merged 1 commit into
masterfrom
reserve-slab-capacity

Conversation

@arthurprs

Copy link
Copy Markdown
Owner

Problem

Cache::reserve() only reserved the internal hash table, not the LinkedSlab Vec that holds the actual entries. The slab is the structure that reallocates as the cache grows.

During a large insert burst, when a shard's slab fills, Vec::push reallocates by doubling — allocating a new buffer (2×) and memcpying the old contents — all while the shard's exclusive write lock is held. Every concurrent get on that shard needs the shared read lock and blocks for the full duration. With ~80-byte entries this is hundreds of MB copied per growth at large sizes, producing multi-hundred-ms to second-level reader stalls at power-of-two thresholds. See #119.

Because reserve() didn't touch the slab, pre-reserving did nothing to prevent these stalls — only the (much smaller) hash table was actually pre-allocated.

Fix

CacheShard::reserve now also pre-allocates the slab via a new LinkedSlab::reserve. The reservation is sized for the requested entries plus the bounded ghost-key space (capacity_non_resident) rather than the previous fixed +50% guess (which only matched the default ghost_allocation of 0.5).

With this, the slab is allocated once up front and inserts no longer reallocate/copy under the lock — the page-fault cost is paid lazily and incrementally per insert.

Tests

  • New LinkedSlab::reserve unit test asserting no reallocation occurs for inserts up to the reserved capacity.
  • Full lib suite passes (52 tests), clippy clean.

reserve() only grew the hash table, not the LinkedSlab Vec that holds the
actual entries. Under a large insert burst, that Vec doubled and memcpy'd
hundreds of MB while the shard write lock was held, stalling all concurrent
readers on that shard (issue #119).

Now reserve() also pre-allocates the slab, sized for the requested entries
plus the bounded ghost-key space (capacity_non_resident) instead of a fixed
50% guess.
@arthurprs arthurprs changed the title Pre-allocate the slab in reserve() to avoid reallocation stalls Pre-allocate the slab in reserve() Jun 24, 2026
@arthurprs
arthurprs merged commit 993f4f3 into master Jun 24, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant