Skip to content

[HLD] add per-slot memory design with phased rollout plan - #3880

Closed
eifrah-aws wants to merge 2 commits into
valkey-io:unstablefrom
eifrah-aws:per-slot-memory-epic
Closed

eifrah-aws wants to merge 2 commits into
valkey-io:unstablefrom
eifrah-aws:per-slot-memory-epic

Conversation

@eifrah-aws

@eifrah-aws eifrah-aws commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

I am uploading this PR for discussion reference (A PR so people are able to comment on the doc).

This HLD addresses this issue: #852

For convenience reading, use this link: https://github.com/eifrah-aws/valkey/blob/per-slot-memory/design-docs/PER_SLOT_MEMORY.md

cc: @ranshid

Document phase-1 single aggregate data_bytes counter per slot, with the
per-type breakdown as an optional layer. Add the O(1)-per-type sizing
plan (one PR per data type), the wire-last rollout, and the rationale
for splitting the work into multiple PRs.

Signed-off-by: Eran Ifrah <eifrah@amazon.com>
@coderabbitai

coderabbitai Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

πŸ“ Walkthrough

Walkthrough

This pull request adds a design document for Phase 1 per-slot logical data size tracking in Valkey clusters. It defines the data-bytes metric, specifies DB-primitive and snapshot+signalModifiedKey accounting, documents correctness across data paths, describes storage and external exposure, and provides a phased implementation roadmap with developer guidance.

Changes

Per-Slot Memory Tracking Feature Design

Layer / File(s) Summary
Metric definition and accounting mechanisms
design-docs/PER_SLOT_MEMORY.md
Introduces data-bytes metric as an aggregate of per-key logical sizes with per-type value-size functions. Describes DB-primitive hooks (create/overwrite/delete/load/flush) and snapshot + signalModifiedKey mechanism for in-place mutations; notes encodings that need running counters.
Correctness, data paths, and module/rename rules
design-docs/PER_SLOT_MEMORY.md
Specifies correctness across normal writes, lazy/async deletes, RDB load (streams/listpack/quicklist), replication apply, FLUSHDB/FLUSHALL, CONFIG RESETSTAT, slot-ownership-change handling, module API expectations, RENAME/COPY cross-slot rules, and SWAPDB restriction in cluster mode.
Storage model and API exposure
design-docs/PER_SLOT_MEMORY.md
Extends slotStat with aggregate data_bytes (phase 1) and provides overhead estimates. Documents CLUSTER SLOT-STATS exposure with scalar data-bytes and ORDERBY data-bytes, and describes optional future per-type breakdown.
Implementation roadmap and developer guide
design-docs/PER_SLOT_MEMORY.md
Outlines multi-PR rollout (scaffolding β†’ per-type O(1) sizing β†’ wiring), cost-gating when cluster disabled, and a checklist for adding new data types (sizing implementation points, slotStatsObjectSize() cases, mutation signaling, RDB-load maintenance, and integration tests).

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

πŸš₯ Pre-merge checks | βœ… 5
βœ… Passed checks (5 passed)
Check name Status Explanation
Title check βœ… Passed The title '[HLD] add per-slot memory design with phased rollout plan' directly and clearly describes the main change: adding a high-level design document for per-slot memory tracking with implementation phases.
Docstring Coverage βœ… Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check βœ… Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check βœ… Passed Check skipped because no linked issues were found for this pull request.
Description check βœ… Passed The pull request description clearly relates to the changeset. It explains that the PR is uploading a design document (HLD) for discussion purposes that addresses issue #852, and provides context about the work being phased with implementation details.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
design-docs/PER_SLOT_MEMORY.md (1)

22-24: ⚑ Quick win

Add language identifiers to fenced code blocks to satisfy markdown linting.

Line 22, Line 76, Line 209, and Line 234 use unlabeled fenced blocks. Please tag them (for example, text) so MD040 passes consistently.

Proposed doc diff
-```
+```text
 sdslen(key) + type_specific_value_size(val)

- +text
lookupKeyWrite(db, key)
β†’ captures (slot, size_before) on client struct
@@
β†’ clears snapshot


-```
+```text
CLUSTER SLOT-STATS SLOTSRANGE 0 0
1) 1) (integer) 0
@@
      ...

- +text
3) "data-bytes"
4) 1) "string" 2) (integer) 1024
@@
13) "stream" 14) (integer) 2048

Also applies to: 76-86, 209-218, 234-243

πŸ€– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@design-docs/PER_SLOT_MEMORY.md` around lines 22 - 24, Add language
identifiers (e.g., "text") to the unlabeled fenced code blocks in
PER_SLOT_MEMORY.md so markdown lint MD040 passes; specifically update the blocks
containing "sdslen(key) + type_specific_value_size(val)", the example starting
with "lookupKeyWrite(db, key)", the CLUSTER output block beginning "CLUSTER
SLOT-STATS SLOTSRANGE 0 0", and the slot-stats blob that lists keys like
"data-bytes" (these appear around the shown snippets) by replacing the leading
triple backticks with triple backticks plus the language label (e.g., ```text)
for each unlabeled fence.
πŸ€– Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@design-docs/PER_SLOT_MEMORY.md`:
- Around line 102-105: Edit the wording around the β€œzero cost” claim so it no
longer asserts β€œno function calls, no branches taken”: replace or rephrase the
sentence that references lookupKey and server.cluster_enabled to say there is
β€œno effective accounting work” when dataBytesAccountingEnabled(slot) returns
false, and update the related passage around the maintenance-path gating (the
lines referencing maintenance paths) to consistently state that the paths are
gated (implying lightweight checks) rather than implying absolutely no branches
or calls.

---

Nitpick comments:
In `@design-docs/PER_SLOT_MEMORY.md`:
- Around line 22-24: Add language identifiers (e.g., "text") to the unlabeled
fenced code blocks in PER_SLOT_MEMORY.md so markdown lint MD040 passes;
specifically update the blocks containing "sdslen(key) +
type_specific_value_size(val)", the example starting with "lookupKeyWrite(db,
key)", the CLUSTER output block beginning "CLUSTER SLOT-STATS SLOTSRANGE 0 0",
and the slot-stats blob that lists keys like "data-bytes" (these appear around
the shown snippets) by replacing the leading triple backticks with triple
backticks plus the language label (e.g., ```text) for each unlabeled fence.
πŸͺ„ Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
βš™οΈ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f9beddb3-9d63-4152-b105-b9b8d67bf898

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 01034bf and 933262c.

πŸ“’ Files selected for processing (1)
  • design-docs/PER_SLOT_MEMORY.md

Comment on lines +102 to +105
Zero. The `lookupKey` snapshot is gated on `server.cluster_enabled`.
The db-primitive hooks call `dataBytesAccountingEnabled(slot)` which
returns false immediately. No function calls, no branches taken.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟑 Minor | ⚑ Quick win

Clarify the β€œzero cost” claim to avoid contradicting the later cost section.

Line 104 says β€œNo function calls, no branches taken,” but Line 385-Line 387 later says maintenance paths are gated (which still implies checks/branches exist on those paths). Suggest softening the earlier wording to β€œno effective accounting work” for consistency.

Also applies to: 385-387

πŸ€– Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@design-docs/PER_SLOT_MEMORY.md` around lines 102 - 105, Edit the wording
around the β€œzero cost” claim so it no longer asserts β€œno function calls, no
branches taken”: replace or rephrase the sentence that references lookupKey and
server.cluster_enabled to say there is β€œno effective accounting work” when
dataBytesAccountingEnabled(slot) returns false, and update the related passage
around the maintenance-path gating (the lines referencing maintenance paths) to
consistently state that the paths are gated (implying lightweight checks) rather
than implying absolutely no branches or calls.


```
lookupKeyWrite(db, key)
β†’ captures (slot, size_before) on client struct

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably an array of snapshots - right? This was multi-key commands don't have to worry about ordering of sequential lookupKeyWrite and signalModifiedKey calls

e.g. it looks like LMOVE does:

  1. lookupKeyWrite(src)
  2. lookupKeyWrite(dst)
  3. listTypePop(src)
  4. lmoveHandlePush(dst) -> signalModifiedKey(c, db, dst)
  5. listElementsRemoved(src) -> signalModifiedKey(c, db, src)

For commands that do many lookups, then many mutations, we need to keep many snapshots around.

@eifrah-aws eifrah-aws Jun 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed one snapshot isn't enough.
I would keep a small per-client set keyed by the key's robj* pointer (keys can be large, so no-copying), matched by a key (index or robj* raw pointer). The core concept stands: snapshot in lookupKeyWrite, apply the delta in signalModifiedKey.

Comment thread design-docs/PER_SLOT_MEMORY.md Outdated
Comment on lines +153 to +157
### Slot ownership changes (CLUSTER ADDSLOTS / DELSLOTS)

- `clusterSlotStatReset(slot)` zeroes the entire `slotStat` struct including
`data_bytes`. This is correct because keys migrate with the slot β€” the new
owner will rebuild the counters as keys arrive via RESTORE/MIGRATE.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Atomic slot migration probably will need special handling. It calls clusterDelSlot/clusterAddSlot during the slot takeover, which notably happens after the keys are added to the DB. Before this was fine since all slot stats were cumulative, but now you have a gauge metric which should not get reset.

In fact - if you forget to handle this - we may end up underflowing the counters

Worth a callout in this section

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

underflowing the counters

I think there are a few cases you may need to handle where slot ownership is lost but we still have keys. Maybe worth considering keeping the counter and letting the DB-level deletions bring it back down to zero.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch β€” since it's a gauge and not a cumulative counter, we shouldn't clean it in the ownership-change reset; I'll exclude it and let the key add/delete hooks keep it accurate (which also avoids the underflow). Updated the doc to call this out.

| Set (hashtable) | Ξ£ member_len per entry | Requires incremental tracking |
| ZSet (listpack) | `lpBytes(val->ptr)` | Single listpack encoding |
| ZSet (skiplist) | Ξ£ (member_len + 8) per entry | 8 bytes for the score double |
| Module | Module-reported size | Via module type API callback |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we force modules to opt-in? It's possible that the module reported size function is expensive

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can provide an API for modules to report their size (based on slot) and basically shift the responsibility of reporting to the module.

(e.g. APPEND, INCR, XADD on existing stream, LPUSH, SADD, HSET):

```
lookupKeyWrite(db, key)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm going back and forth - not sure - but part of me is concerned this may be a violation of https://en.wikipedia.org/wiki/Principle_of_least_astonishment

Although it lowers the touch points, adding this side effect to lookupKeyWrite feels like it may introduce bugs later. A function called lookup really should be side-effect free.

The alternative would be explicit functions. I guess it's a tradeoff between boilerplate and side-effects.

(I will say Valkey doesn't do a good job here today)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. I am not a big fan of this as well. Ideally, I would change the return value of this function to something like KeyHandle lookupKeyWrite(..) where KeyHandle will hold both the robj* and the snapshot, but this changes the code in way too many places and is a very intrusive change - so I fallback to this solution (combined with "resetClient" as our safety-net)

Explain that data_bytes must be excluded from the ownership-change reset:
unlike the cumulative slot stats, it tracks current data and stays accurate
via the key add/delete hooks. Note the atomic-migration ordering (keys
imported before ownership is claimed) and the underflow that a blanket
reset would cause.

Signed-off-by: Eran Ifrah <eifrah@amazon.com>
@eifrah-aws

Copy link
Copy Markdown
Contributor Author

@valkey-io/core-team feel free to review when you the time πŸ™πŸ½

@soloestoy

Copy link
Copy Markdown
Member

The key-level accounting design (snapshot at lookupKeyWrite + delta at signalModifiedKey, complemented by db-primitive hooks) looks sound β€” the two-mechanism approach covers the full key lifecycle cleanly, and the O(1) sizing requirement is well-motivated.

However, I have concerns about the internal per-data-structure tracked_data_bytes counters that the O(1) sizing relies on, and I think these deserve more upfront discussion before implementation begins:

1. Overhead of maintaining running counters needs to be quantified

The HLD proposes embedding tracked_data_bytes fields on hashtable (hash/set), skiplist (zset), quicklist (list), and rax (stream) structures, with incremental updates on every mutation. While each individual update is cheap, the aggregate cost is not zero: every HSET field add/overwrite/delete, every LPUSH node insert, every XADD listpack append, every SADD member insert, etc. now carries extra arithmetic. The memory cost is also non-trivial β€” every large-encoded hash, set, zset, list, and stream object gains an 8-byte field, and in deployments with millions of such keys this adds up.

It would be valuable to see an explicit analysis of: (a) the per-mutation CPU overhead (even if small, it's on the hot path for every write), and (b) the total memory overhead at representative scales (e.g., 1M keys with large encodings). Without this, we're committing to a permanent per-operation tax on every data structure without knowing the cost.

2. The phased rollout creates a "point of no return" risk

The multi-PR strategy is well-intentioned for reviewability, but it introduces an asymmetric commitment: once the scaffolding PR and the first few per-type counter PRs (e.g., string, hash) are merged, we can't realistically halt the feature if a later data structure (e.g., stream, module) turns out to be prohibitively difficult or expensive to instrument correctly. The already-landed types will already carry their maintenance overhead β€” both in struct size and in per-mutation cost β€” even if the feature never reaches full coverage across all types.

In other words, each merged PR is a sunk cost that cannot be recovered by stopping. This means we should have high confidence in the feasibility and cost of every type's approach before merging the first PR.

3. Module size reporting is particularly hard to standardize

The HLD proposes a "module type-API size callback" for module-reported sizes, but module authors have no standardized way to compute or report their memory footprint. Some modules may report logical size, others physical size, and many may simply not implement the callback at all (or implement it incorrectly). Unlike built-in types where we control the implementation, we have no way to enforce correctness or consistency for module-reported sizes. This could lead to data_bytes being silently inaccurate for any slot containing module-type keys, undermining trust in the metric.

Suggestion

I think we should produce a detailed specification for each data structure's tracking approach β€” covering the exact mutation points where tracked_data_bytes is updated, the overhead analysis, and edge cases (e.g., defrag, active rehashing, listpack-to-hashtable conversion) β€” and get community alignment on all of them before any implementation PR is merged. Having the full picture upfront ensures we're making an informed commitment rather than discovering blockers mid-rollout.

@eifrah-aws

eifrah-aws commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor Author
  1. The phased rollout creates a "point of no return" risk
    The multi-PR strategy is well-intentioned for reviewability, but it introduces an asymmetric commitment: once the scaffolding PR and the first few per-type counter PRs (e.g., string, hash) are merged, we can't realistically halt the feature if a later data structure (e.g., stream, module) turns out to be prohibitively difficult or expensive to instrument correctly. The already-landed types will already carry their maintenance overhead β€” both in struct size and in per-mutation cost β€” even if the feature never reaches full coverage across all types.
    In other words, each merged PR is a sunk cost that cannot be recovered by stopping. This means we should have high confidence in the feasibility and cost of every type's approach before merging the first PR.

The concern is valid for merges into unstable, so we've structured the rollout to avoid exactly
that: all PRs land on a dedicated side-branch, not unstable. Nothing reaches the trunk until the
feature is complete and proven across every type, at which point we do a single merge side-branch ->
unstable.

This removes the per-PR "point of no return" - there is no asymmetric commitment, because no
per-type counter ships to users until the whole picture exists. If a later type (stream, module)
turns out prohibitively hard or expensive, it's reworked or dropped on the side-branch with zero
overhead paid in unstable. The single unstable merge is the one and only commitment, and it's made
with full knowledge of every type's feasibility and cost - which is exactly the "high confidence
before committing" bar you're asking for.

It would be valuable to see an explicit analysis of: (a) the per-mutation CPU overhead (even if small, it's on the hot path for every write), and (b) the total memory overhead at representative scales (e.g., 1M keys with large encodings). Without this, we're committing to a permanent per-operation tax on every data structure without knowing the cost.

the per-type specification - agreed, and we'll satisfy it incrementally: each per-type PR
carries its own spec + benchmarks (exact mutation points updated, whether a stored counter is needed vs. an O(1) lookup, overhead numbers, and edge cases β€” defrag, active rehashing, encoding conversion). Since everything lands on the side-branch first, the full picture across all types is assembled there before the single merge to unstable, so the final commitment is still made with complete information.

  1. Module size reporting is particularly hard to standardize
    The HLD proposes a "module type-API size callback" for module-reported sizes, but module authors have no standardized way to compute or report their memory footprint. Some modules may report logical size, others physical size, and many may simply not implement the callback at all (or implement it incorrectly). Unlike built-in types where we control the implementation, we have no way to enforce correctness or consistency for module-reported sizes. This could lead to data_bytes being silently inaccurate for any slot containing module-type keys, undermining trust in the metric.

Agreed we can't enforce correctness on arbitrary module-reported sizes. Instead, modules participate
through a delta API: the module reports +n/-n against the per-slot counter on its own allocations
and frees. That's exact when used (not an estimate), and it's the same incremental mechanism the
built-in types use, so a participating module is accounted with the same fidelity as a native type.

Policy by module category:

  • Old/legacy modules - not supported; their keys simply don't contribute to memory-bytes.
  • External modules (not maintained by Valkey) - opt-in via the delta API; using it correctly is the module's responsibility.
  • Official modules (Search, Bloom, JSON, ...) - we do the wiring ourselves by using the exact same API that we provide for "external modules".

The design doc is updated #3966
Lets continue any discussion on that PR.

@eifrah-aws

Copy link
Copy Markdown
Contributor Author

Closing this PR. It is superseded by this one:
#3966

@eifrah-aws eifrah-aws closed this Jul 1, 2026
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.

3 participants