Repository navigation
[HLD] add per-slot memory design with phased rollout plan - #3880
eifrah-aws wants to merge 2 commits into
Conversation
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>
π WalkthroughWalkthroughThis pull request adds a design document for Phase 1 per-slot logical data size tracking in Valkey clusters. It defines the ChangesPer-Slot Memory Tracking Feature Design
Estimated code review effortπ― 1 (Trivial) | β±οΈ ~5 minutes π₯ Pre-merge checks | β 5β Passed checks (5 passed)
βοΈ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
π§Ή Nitpick comments (1)
design-docs/PER_SLOT_MEMORY.md (1)
22-24: β‘ Quick winAdd 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) 2048Also 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
π Files selected for processing (1)
design-docs/PER_SLOT_MEMORY.md
| 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. | ||
|
|
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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:
- lookupKeyWrite(src)
- lookupKeyWrite(dst)
- listTypePop(src)
- lmoveHandlePush(dst) -> signalModifiedKey(c, db, dst)
- listElementsRemoved(src) -> signalModifiedKey(c, db, src)
For commands that do many lookups, then many mutations, we need to keep many snapshots around.
There was a problem hiding this comment.
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.
| ### 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. |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 | |
There was a problem hiding this comment.
Should we force modules to opt-in? It's possible that the module reported size function is expensive
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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>
|
@valkey-io/core-team feel free to review when you the time ππ½ |
|
The key-level accounting design (snapshot at However, I have concerns about the internal per-data-structure 1. Overhead of maintaining running counters needs to be quantifiedThe HLD proposes embedding 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" riskThe 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 standardizeThe 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 SuggestionI think we should produce a detailed specification for each data structure's tracking approach β covering the exact mutation points where |
The concern is valid for merges into unstable, so we've structured the rollout to avoid exactly This removes the per-PR "point of no return" - there is no asymmetric commitment, because no
the per-type specification - agreed, and we'll satisfy it incrementally: each per-type PR
Agreed we can't enforce correctness on arbitrary module-reported sizes. Instead, modules participate Policy by module category:
The design doc is updated #3966 |
|
Closing this PR. It is superseded by this one: |
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