Mooncake icon indicating copy to clipboard operation
Mooncake copied to clipboard

[RFC]: Lightweight Best-Effort Group Semantics for Mooncake Store Objects

Open yokinoshitayoki opened this issue 6 months ago • 8 comments

Changes proposed

Background

This is a follow-up design proposal to Issue #1887, which describes a common problem in Mooncake Store: several physical objects may represent one logical cache unit.

Examples include:

  • In KV cache, the K tensor and V tensor may be stored as separate objects.
  • In SGLang PP/TP deployments, the KV cache for the same token span may be split across ranks or layers.
  • In DSA-like designs, one logical cache unit may include both KV objects and indexer objects.

This RFC refers to these related objects as belonging to the same group.

Today, Mooncake Store manages lifecycle at object granularity. Objects in the same logical group can be uploaded, accessed, leased, and evicted independently. As discussed in Issue #1887, this means an originally complete group may later become partial after object-level eviction removes only some of its members.

For upper layers such as KV cache systems, a partial group is often not useful: if only K remains without V, or only one TP rank keeps a token span, the logical cache entry cannot be safely reused.

Motivation

Issue #1887 lays out the broader design space for group semantics, including:

  • group_id
  • group_size
  • group_index
  • group-aware existence checks
  • group-level eviction
  • sharding strategy
  • metadata design
  • remove semantics
  • SSD offloading compatibility
  • fault tolerance
  • relation to prefix-aware eviction

This RFC focuses on a smaller implementation subset within that design space. The intent is to address the common eviction-fragmentation case first, while leaving stronger completeness semantics and prefix-aware policy decisions to follow-up discussion.

To understand the practical impact, we ran end-to-end experiments with real SGLang HiCache + Mooncake L3 traffic. The goal was to answer a question:

Under real long-running HiCache traffic, does current Mooncake object-level eviction create a meaningful amount of eviction-fragmented partial logical groups?

The result is:

  • Yes, object-level eviction does create partial logical groups.
  • However, the bad-cache live-byte ratio drops to around 1% once L3 capacity reaches 64GB and above.

Based on the measured impact and the implementation complexity of stronger completeness semantics, this RFC proposes a lightweight, best-effort initial implementation.

The goal is not to provide transactional group semantics. The goal is to reduce the common case where eviction leaves useless partial groups behind, while keeping the design simple and backward compatible.

Experimental Data

Workload

The experiments used a full SGLang HiCache + Mooncake L3 path:

  • SGLang server with HiCache enabled.
  • Mooncake Store as the L3 backend.
  • benchmark/hicache/bench_mix.py as a long-running multi-turn conversation workload.
  • Model: Qwen3-8B.
  • Tensor parallelism: TP=2.
  • Mooncake memory eviction enabled.

In this TP=2 setup, a logical KV group usually has four Mooncake objects:

  • rank 0_k
  • rank 0_v
  • rank 1_k
  • rank 1_v

The benchmark produces long-running multi-turn traffic with reusable prefixes, which continuously writes KV cache into Mooncake L3 and eventually triggers Mooncake eviction.

Metric

The main metric is:

bad cache live-byte ratio = fragmented_live_bytes / live_bytes_at_end

Where:

  • live_bytes_at_end: total live bytes in Mooncake L3 at the end of the run.
  • fragmented_live_bytes: live bytes that belong to groups that became partial because of object-level eviction.

Only eviction-fragmented partial groups are counted.

Main Result: High Watermark=95%, Around 80 Eviction Cycles

It uses Mooncake's default-like watermark configuration and tries to align the number of eviction cycles across capacities.

Common parameters:

Parameter Value
Model Qwen3-8B
TP 2
Traffic SGLang benchmark/hicache/bench_mix.py
num_clients 32
num_rounds 3
mean_new_tokens 256
mean_return_tokens 16
Mooncake high watermark 95%
Mooncake eviction ratio 5%
max_total_tokens 120000
hicache_size 10GB
Store mode standalone Mooncake store service
Target eviction cycles about 80

max_total_tokens limits SGLang L1 GPU KV cache. hicache_size limits SGLang L2 host HiCache. These limits were needed to avoid L1/L2 consuming too much HBM or host memory before Mooncake L3 reached the target capacity.

Results:

L3 capacity Eviction cycles Live bytes at end Fragmented live bytes Bad cache live-byte ratio
8GB 75 7.26 GiB 0.30 GiB 4.09%
16GB 81 14.93 GiB 0.36 GiB 2.44%
32GB 79 30.26 GiB 0.65 GiB 2.14%
64GB 74 58.43 GiB 0.76 GiB 1.30%
128GB 84 120.50 GiB 1.22 GiB 1.01%
256GB 85 236.21 GiB 2.08 GiB 0.88%

Observations:

  • Object-level eviction creates partial groups.
  • Small capacities amplify the bad-cache ratio.
  • The bad-cache live-byte ratio decreases as capacity increases.
  • At 64GB and above, the measured ratio is around 1%.

Caveats

The current data should be treated as motivation for a lightweight design, not as a final production estimate.

Limitations:

  • Only Qwen3-8B was tested.
  • TP was limited to 2.
  • The largest tested Mooncake L3 capacity was 256GB.
  • The tests used L1/L2 limiting parameters to avoid local OOM.
  • Production deployments may use TP=8 and TB-level Mooncake L3 capacity.

TP=8 may increase the number of objects per logical group and increase the chance that an eviction touches only part of a group. However, production L3 capacity is also commonly much larger than 256GB, and the observed trend shows that larger capacity reduces the final bad-cache live-byte ratio in this workload.

A reasonable hypothesis is that TP=8 with TB-level L3 capacity will still have some partial-group leftovers, but the final live-byte waste ratio may not be very high. This needs to be validated on production-scale machines.

This is the main reason for proposing a best-effort initial implementation instead of starting with a transactional design.

Desired Behavior

For grouped objects, Mooncake should try to make the lifecycle of objects in the same group closer to a single logical unit:

  1. If one member is accessed, the group should be treated as recently used.
  2. If eviction selects one member, Mooncake should try to evict the currently known safe-to-evict members of the same group.
  3. If a member cannot be safely evicted, Mooncake should skip that member.
  4. Existing object-level APIs should continue to work for users that do not pass group metadata.

This is a deliberately scoped subset of the complete group semantics discussed in Issue #1887.

In this initial best-effort implementation, Mooncake does not need to know whether a group is complete. Mooncake also does not guarantee atomic group creation, atomic group visibility, or atomic group deletion.

Proposed Design

1. API

Add an optional group_id to put/upsert metadata.

For C++:

struct ReplicateConfig {
    size_t replica_num{1};
    bool with_soft_pin{false};
    bool with_hard_pin{false};
    std::vector<std::string> preferred_segments{};
    std::string preferred_segment{};
    bool prefer_alloc_in_same_node{false};
    ObjectDataType data_type{ObjectDataType::UNKNOWN};

    // Optional. Empty means current object-level behavior.
    std::string group_id{};
};

For Python, expose the same field through the existing ReplicateConfig binding:

config = ReplicateConfig()
config.group_id = "logical-kv-page-123"
store.put_from(key, buffer_ptr, size, config)

For batch put/upsert, the group ID should be per object. A single ReplicateConfig.group_id for the whole batch would incorrectly force all keys in that batch into the same group.

Possible API:

store.batch_put_from_grouped(keys, buffer_ptrs, sizes, group_ids, config)

Rules:

  • group_ids.size() == keys.size().
  • Empty group ID means the corresponding key is ungrouped.
  • Existing put, put_from, batch_put_from, and batch_put_from_multi_buffers keep their current behavior.
  • C++ and Python can be the first supported APIs. C, Go, and Rust bindings can be added later after the core semantics are reviewed.
  • For an existing object key, group membership is immutable while the object exists.

2. Sharding

For ungrouped objects, keep current sharding behavior:

metadata_shard = hash(object_key)

For grouped objects:

metadata_shard = hash(group_id)

This colocates all group members in the same metadata shard. It avoids cross-shard group metadata and avoids acquiring multiple metadata shard locks for one group operation.

This has an obvious tradeoff:

  • Pro: much simpler metadata management and eviction logic.
  • Con: hot or very large groups may create more lock contention on one shard.

For KV cache, this is expected to be a low risk in practice because groups are usually small and have similar size. For other workloads, especially if a user puts many objects into the same group_id or repeatedly accesses one very hot group, this contention may become more visible.

For the initial implementation, the simplicity is preferred.

Because existing read/remove APIs only take object keys, the master should also maintain a lightweight object-to-group routing index:

object_key -> group_id or group_shard

Lookup flow:

  1. Check whether object_key is known as grouped.
  2. If yes, route metadata lookup to hash(group_id).
  3. If no, route metadata lookup to hash(object_key) as before.

The routing index is metadata only. It can be updated on put/remove and rebuilt by scanning object metadata during snapshot restore or master recovery.

Physical allocation policy does not need to change in the initial implementation. This proposal is about metadata lifecycle and eviction grouping, not forcing all replicas of a group into the same memory segment.

3. Group Metadata

For each group, maintain lightweight metadata:

group_id
object_keys
group_lease_timeout
optional group_soft_pin_timeout

The group does not track expected size or completeness.

This is intentional. The group is simply the set of currently known objects that declared the same group_id.

4. Lease Behavior

For ungrouped objects, keep current per-object lease behavior.

For grouped objects:

  • Successful metadata lookup of any member refreshes the group lease.
  • ExistKey, GetReplicaList, and successful read-path metadata lookup should all refresh the group lease.
  • Eviction checks the group lease before evicting grouped members.
  • If any member was recently accessed, the whole group is protected from eviction until the group lease expires.

This still does not make the group transactional. It only means that normal lease refresh and normal eviction selection use the same group boundary.

5. Eviction Behavior

For ungrouped objects, keep current object-level eviction.

For grouped objects:

  1. If eviction selects any member of a group, treat the group as the eviction candidate.
  2. If the group lease is still active, skip the group.
  3. If the group lease has expired, scan the group's current members in the same shard.
  4. Evict each member that is currently safe to evict.
  5. Skip members that are not currently safe to evict.

"Safe to evict" should reuse existing object-level checks, for example:

  • memory replica exists,
  • replica is complete,
  • replica refcount is zero,
  • object is not hard-pinned,
  • object has no incompatible replication or offloading state.

If one member is currently in put or otherwise not safe to evict, the initial implementation does not need to block the whole group. It can evict the safe members and skip the unsafe ones.

6. Remove Behavior

For the initial implementation, keep existing Remove(key) semantics:

  • Remove(key) removes only that object.
  • It does not remove the whole group.
  • If the removed object was grouped, remove it from the group member set and from the object-to-group routing index.
  • If the group becomes empty, delete the group metadata.

A future RFC can add:

RemoveGroup(group_id)

This avoids changing existing key-level API semantics.

Prefix-Aware Eviction

Issue #1887 also discusses the relation between group semantics and prefix-aware eviction.

This RFC intentionally does not propose a prefix-aware eviction policy. The proposed behavior is local to Mooncake Store metadata.

If Mooncake later adds prefix-aware eviction, this best-effort group metadata can still be useful as a lower-level primitive: prefix-aware policy can select a logical cache entry, and group-aware eviction can remove the physical objects belonging to that entry together.

Non-Goals

This RFC does not propose:

  • group completeness tracking,
  • group_size or group_index,
  • group-aware exists semantics,
  • atomic group put,
  • atomic group visibility,
  • atomic group eviction,
  • distributed transactions,
  • cross-shard group operations,
  • RemoveGroup,
  • prefix-aware eviction,
  • SSD offload-aware group policy changes.

These can still be added later if production data shows that stronger semantics are necessary.

Fault Tolerance and Best-Effort Cases

The initial implementation should keep Mooncake safe at object level, but it does not try to repair or guarantee group completeness.

Examples that this proposal does not solve:

  • Group A puts object 1.
  • Group A is evicted.
  • Group A later puts object 2.
  • A client fails after putting only part of a group.
  • Some group members are skipped during eviction because they are being put, leased, pinned, refcounted, or waiting for offload.
  • A group becomes partial for reasons other than eviction.

In these cases, Mooncake should avoid data corruption and preserve current object-level safety.

Compatibility

Backward compatibility is a core requirement:

  • Existing APIs continue to work when group_id is empty.
  • Existing object-level exists, get, and remove semantics remain valid.
  • Existing applications do not need to pass group metadata.
  • Group semantics are opt-in.
  • The first implementation can focus on C++ and Python APIs.

SGLang HiCache integration can be discussed separately after the Mooncake Store API and semantics are accepted.

Possible Implementation Plan

If this direction looks reasonable, we may start with a staged implementation:

  1. Add the opt-in group metadata path
  • Add optional group_id metadata to put/upsert paths.
  • Route grouped object metadata by hash(group_id).
  • Add a lightweight object-to-group routing index so existing read/remove APIs can still take object keys.
  • Track only the current member set for each group in the master.
  1. Add shared lifecycle behavior
  • Refresh a group-level lease when any member is accessed.
  • Make automatic memory eviction expand a grouped candidate to the group's current members.
  • Reuse the existing object-level safety checks during eviction.
  • Skip members that are not currently evictable.
  1. Add tests, metrics, and integration notes
  • Add tests for backward compatibility, routing, lease refresh, best-effort eviction, remove cleanup, and snapshot/recovery rebuild.
  • Add basic metrics such as grouped object count, group count, skipped member count, and grouped eviction freed bytes.
  • Document how SGLang HiCache or other inference frameworks can map their logical KV cache unit to group_id.

This staging keeps the initial implementation small and backward compatible, while leaving stronger semantics to follow-up discussion.

Before submitting a new issue...

  • [x] Make sure you already searched for relevant issues and read the documentation

yokinoshitayoki avatar May 18 '26 10:05 yokinoshitayoki

Thanks a lot for the detailed benchmark results and the design write-up. They provide a lot of useful insight into the actual tradeoffs here.

One concern with placing all items from the same group into the same shard is potential lock contention when those items are accessed almost concurrently. This is especially relevant for inference workloads, where read-side latency is quite sensitive. That said, since the current implementation already uses read/write locks and get / exists only take read locks, the contention on the read path should be much less severe. The lease update is also protected separately by a spin lock, so it should not block the shard read lock directly.

For the API, one simple and forward-compatible option might be to add an optional field to the replica config, for example:

std::optional<std::vector<std::string>> group_ids;

This way, both batch and non-batch APIs can remain unchanged. Callers that do not need grouping can simply omit the field, while grouped objects can provide the corresponding group_id through the replica config.

ykwd avatar May 19 '26 04:05 ykwd

Thanks a lot for the suggestion.

I agree that this API shape is much cleaner,using std::optional<std::vector<std::string>> group_ids in ReplicateConfig sounds better than adding a separate grouped batch API.

One possible semantic definition could be:

  • If group_ids is not set, keep the current ungrouped behavior.
  • For single-object put/upsert, if group_ids is set, it should contain exactly one element.
  • For batch put/upsert, if group_ids is set, group_ids.size() should match the number of keys.
  • group_ids[i] is the group id for keys[i].
  • For an existing object key, group membership should remain immutable while the object exists.

The lock contention concern also makes sense to me.My assumption was that this should be acceptable for the first implementation because KV-cache groups are usually small. Your point about the lease update being protected separately by a spin lock also helps clarify why same-shard grouping may be reasonable for the initial version.

I can update the proposal along this direction.

yokinoshitayoki avatar May 19 '26 10:05 yokinoshitayoki

this makes sense. I’ll align the initial implementation with the std::optional<std::vector<std::string>> group_ids direction in ReplicateConfig, instead of adding a separate grouped batch API.

A narrow staged plan I’m considering:

  1. API/routing first: validate group_ids, route grouped metadata by hash(group_id), maintain an object_key -> group shard index, keep existing key-level Get/Remove behavior, and rebuild the routing index on restore.
  2. Group lease next: accessing any member refreshes protection for the current group members.
  3. Best-effort eviction last: when eviction selects a grouped member, expand to current group members but evict only members that pass existing object-level safety checks.

I’ll keep stronger completeness tracking, atomic group operations, RemoveGroup, and SGLang integration as follow-ups unless maintainers prefer a different split.

One small semantic point to confirm: when group_ids is present, should an empty string mean “ungrouped”, or should it be treated as invalid input?

CAICAIIs avatar May 20 '26 18:05 CAICAIIs

@CAICAIIs Thanks for your interest, this plan looks good to me. The staged split is aligned with the intended scope of this RFC.

When group_ids is present, I would prefer that an empty string should mean “ungrouped”. This keeps mixed grouped / ungrouped batch puts possible without requiring callers to split batches. It also matches the current RFC where an empty group ID means the corresponding key is ungrouped.

One validation detail: if group_ids is present but the vector size does not match the number of keys, that should be rejected as invalid input. An empty vector with a non-empty batch should also be invalid.

cc @ykwd PTAL when you have time.

yokinoshitayoki avatar May 21 '26 03:05 yokinoshitayoki

@CAICAIIs Thanks for your interest, this plan looks good to me. The staged split is aligned with the intended scope of this RFC.

When group_ids is present, I would prefer that an empty string should mean “ungrouped”. This keeps mixed grouped / ungrouped batch puts possible without requiring callers to split batches. It also matches the current RFC where an empty group ID means the corresponding key is ungrouped.

One validation detail: if group_ids is present but the vector size does not match the number of keys, that should be rejected as invalid input. An empty vector with a non-empty batch should also be invalid.

cc @ykwd PTAL when you have time.

To maintain forward compatibility, I’d suggest making group_ids an optional parameter in ReplicaConfig. By default, users should not need to set group_ids, or it could default to an empty vector to indicate that no group is specified. The parameter should only be validated and used when it is explicitly set.

ykwd avatar May 21 '26 03:05 ykwd

Thanks for the clarification and suggestions. I’ll keep group_ids as an optional field in ReplicateConfig, preserve the default ungrouped behavior, treat empty string entries as ungrouped for mixed batches, and validate the vector only when it is explicitly provided.

I don’t have further questions on the API semantics for now. Would it be okay if I start with PR1 focusing on API/routing and key-level compatibility?

cc @ykwd: do you prefer keeping this as three smaller PRs (API/routing, group lease, best-effort eviction), or would one or two tighter PRs be easier to review for this RFC?

CAICAIIs avatar May 21 '26 05:05 CAICAIIs

Since the current approach has already been simplified significantly, I expect the overall changes won’t be too large. It might be more convenient to submit it directly as one PR for review.

ykwd avatar May 21 '26 06:05 ykwd

Since the current approach has already been simplified significantly, I expect the overall changes won’t be too large. It might be more convenient to submit it directly as one PR for review.

Got it, thanks. I’ll proceed with a single PR and keep the scope limited to the current RFC semantics.

CAICAIIs avatar May 21 '26 06:05 CAICAIIs