Skip to content

[Store] Parallelize DFS BatchRead for adapters without batch I/O - #5283

Open
zuozhubinge wants to merge 4 commits into
kvcache-ai:mainfrom
zuozhubinge:dfs-batch-read-parallel
Open

zuozhubinge wants to merge 4 commits into
kvcache-ai:mainfrom
zuozhubinge:dfs-batch-read-parallel

Conversation

@zuozhubinge

@zuozhubinge zuozhubinge commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Description

Problem

For filesystem adapters that do not implement batch I/O (today: POSIX),
DistributedStorageBackend::BatchRead executes the validated requests one after
another through ExecuteSingleIo. A batch of N reads issues N positional reads back to
back, so the filesystem sees one outstanding request at a time.

The 3FS adapter already avoids this by submitting the whole batch through
BatchReadAt (#4497, #4498, #4510). This PR covers the adapters that do not have a
batch interface.

Change

BatchRead keeps its existing validation loop unchanged. After validation:

  • Adapters with SupportsBatchIo() (3FS) take the existing batched path. Nothing
    changes for them, and the pool is never created.
  • Other adapters run the validated ops through ExecuteSingleIo from a shared atomic
    cursor. The calling thread and up to MOONCAKE_DFS_READ_THREADS pool workers claim
    ops with fetch_add until the cursor passes the end; the caller then waits for the
    in-flight ops to finish.
  • One task is enqueued per worker (not per request), and at most n - 1 workers join a
    batch of n ops. In bucket layout the caller plus workers are also kept within
    kMaxOpenBucketsPerBatch (64), since each bucket read holds its own fd. With the pool
    disabled or a single request, the code path is the original serial loop.
  • Helper jobs still waiting in the pool queue are capped across calls at
    64 × MOONCAKE_DFS_READ_THREADS; a job frees its slot when a worker picks it up.
    When the cap is reached, the call enqueues no more helpers and reads the rest itself.
  • The object-storage path is unchanged.

Design notes

  • The caller participates. If the caller only waited, the pool size would cap
    concurrency across all callers: N threads calling BatchRead at once would drop from
    N concurrent reads on the serial path to the pool size. An earlier revision of this
    change worked this way and ran at 0.66x of serial with 8 callers on a 4-worker pool.
    Draining the same cursor from the caller keeps every setting at or above serial.
  • Shared state lives on the heap. The cursor, counter, mutex and condition variable
    are held in a shared_ptr owned by every task. A queued task may start after
    BatchRead returns (for example when the pool is busy with another caller); it then
    only sees next_index >= total and exits without touching ops or results.
  • Queued jobs are bounded. Without a bound, jobs left over from earlier calls could
    pile up in the pool's unbounded queue on a busy pool. The cap counts only jobs not yet
    started, because capping running jobs as well let the first concurrent call take
    every slot (on GPFS with 8 callers: 8884 vs 11650 MB/s, p99 118.7 vs 41.2 ms). It is
    set at 64× so the loads measured here stay at or below it: a cap of 8× raised p99 by
    18-43% at 16-64 callers, while with 64× throughput and p99 were within 2% of no cap
    (see Benchmark). Above the cap, later calls get fewer helpers.
  • Results. Each op is claimed exactly once and writes only results[op.index]. The
    decrement uses acq_rel and the waiter checks the counter with acquire, so the
    caller sees every result before returning.
  • Exceptions do not escape a worker. An exception from ExecuteSingleIo fails only
    that request with FILE_READ_FAIL. This keeps a pool thread from terminating the
    process and guarantees the completion counter always reaches zero. If enqueue throws
    because the pool is stopping, the caller drains the remaining ops itself.
  • Locking is unchanged. ExecuteSingleIo still holds the per-shard mutex, which
    [Store] Reopen DFS shard once on POSIX I/O failure before surfacing error #4512 needs for reopen-on-failure. Reads on the same shard therefore still serialize;
    the parallelism comes from different shards (shard layout) or different bucket files
    (bucket layout).

Configuration

MOONCAKE_DFS_READ_THREADS (new, in DistributedStorageEnvironmentVariables) sets the
number of extra workers in addition to the calling thread.

value behavior
unset 16 for the posix adapter, 1 (serial) for other adapters
<= 1 serial, no pool is created
2..128 pool with that many workers
> 128 clamped to 128 with a warning

The pool is only created for adapters without SupportsBatchIo(), with
MOONCAKE_DFS_READ_THREADS threads in either layout. In bucket layout at most 63 of
them join a single call, so one call holds at most 64 bucket fds; concurrent calls can
use the remaining workers.

Behavior changes

  • POSIX deployments use parallel reads by default. Set MOONCAKE_DFS_READ_THREADS=1 to
    restore the previous serial behavior.
  • Each backend keeps up to MOONCAKE_DFS_READ_THREADS (default 16) resident worker
    threads.
  • An exception thrown while executing one read now fails only that request with
    FILE_READ_FAIL instead of propagating out of BatchRead.
  • In bucket layout a BatchRead call may hold up to min(workers + 1, 64) bucket fds at
    once instead of one.
  • Requests in one batch must use non-overlapping destination buffers. On the serial
    path overlapping buffers ended with the last request's data; with the pool the
    result is unspecified. BatchGet already passes one buffer per key.

Scope

Client::BatchGet and range reads go through multi-request BatchRead calls and
benefit. Single-key Client::Get reads a DFS replica through ReadDfsReplica, which
passes one request to BatchRead, so it stays serial. BatchWrite is unchanged.

Related work

Follow-ups (separate PRs)

  • A shared lock for same-shard reads (exclusive only for reopen-on-failure), so that
    reads on the same shard can run concurrently.
  • Parallel BatchWrite using the same scheme.

Suggested Merge Priority

  • P0 — Urgent
  • P1 — High
  • P2 — Normal: Routine bug fix, validated performance/compatibility improvement, or new feature for a confirmed use case
  • P3 — Low

Module

  • Mooncake Store (mooncake-store)
  • Common (mooncake-common)
  • Docs

Type of Change

  • Performance improvement

How Has This Been Tested?

Test commands:

cd build && ctest -R dfs --output-on-failure

Test results:

  • Unit tests pass
  • Integration tests pass (if applicable)
  • Manual testing done (describe below)

Unit tests

ctest -R dfs: all 8 DFS test binaries pass (dfs_posix_test,
dfs_immutable_bucket_backend_test, dfs_immutable_bucket_client_test,
dfs_immutable_bucket_allocator_test, dfs_sync_client_test, dfs_read_checksum_test,
dfs_enablement_config_test, master_service_dfs_scenario_test).

New tests in DfsBackendParallelTest (POSIX adapter, real files in a temp directory):

  • MatchesSerialAndPreservesOrder: writes 256 objects striped over 8 shards and reads
    them back in one batch with MOONCAKE_DFS_READ_THREADS=1 and =8. Every index must
    succeed and match its source byte for byte. The =1 run covers the serial path,
    which POSIX no longer uses by default.
  • MapsPerIndexErrorsByDescriptor: mixes valid reads with an invalid shard index, a
    file name that is not a shard file, and an unaligned offset. Under concurrency each
    invalid index fails with INVALID_PARAMS and the valid ones return correct data.
  • EmptyAndSingleRequestWithPoolEnabled: an empty batch and a single-request batch with
    the pool enabled.
  • ConcurrentCallersWithSmallPool: 8 threads call BatchRead at the same time on a
    2-worker pool, each over its own range. Every caller must get exactly its own data.

DfsBackendTest.BatchReadPreservesPerKeyErrors now runs with 8 workers. Its failures
are injected by file offset, so it checks hard read failures, short reads and
reopen-on-failure on the parallel path.

In dfs_immutable_bucket_backend_test:

  • PosixKeepsPerRequestBucketHandles checks that one bucket fd is open at a time, which
    only holds on the serial path, so it now sets MOONCAKE_DFS_READ_THREADS=1.
  • PosixParallelReadsBoundOpenBuckets (new) reads 2 × 64 objects, one per bucket, with
    128 workers through an adapter with atomic counters. It checks the data, that every
    opened bucket is closed, that more than one bucket was open at once, and that at most
    64 were open at once.

ThreadSanitizer

-fsanitize=thread, 30 runs each of the full dfs_posix_test and
dfs_immutable_bucket_backend_test binaries (60/60 pass): no reports in the new code.
The only report seen is a pre-existing race inside glog 0.6.0
LogMessageTime::CalcGmtOffset() (strdup/free of a temporary) when two threads log at
the same time. It is triggered by the error-mapping test logging from several workers
and was suppressed with race:google::LogMessageTime::CalcGmtOffset.

Benchmark

Method: a standalone harness (not part of this PR) calls BatchRead directly on a POSIX
DistributedStorageBackend in shard layout, without master or client. It writes the
dataset once with BatchWrite, then for each thread setting builds a fresh backend and
issues batches over strided offsets. Latency columns are per BatchRead call (one whole
batch), not per object. All runs had 0 errors.

GPFS (201 TB, accessed over TCP; the filesystem we deploy DFS on), 1 MiB objects,
batch 32 (32 MiB per call). GPFS caches were not cleared between runs (the GPFS
pagepool is not affected by drop_caches).

8 callers, 16 shards, 25 GiB, this PR's code (a668fb6), medians of 3 runs:

threads=1 16 p50 per call (1 → 16) p99 per call (1 → 16)
2645 MB/s 8683 (3.28×) 90.2 → 28.3 ms 196.1 → 55.4 ms

In the same session, alternated with these runs, the first revision of this PR
(e9c416f, no bound on queued jobs) gave 9736 MB/s at 16 workers with p99 52.0 ms. The
serial baseline, which is the same code in both builds, ranged from 2571 to 3428 MB/s
across runs.

More callers, 64 shards × 2 GiB, 16 workers, medians of 3 runs alternated with the first
revision of this PR (e9c416f, no bound on queued jobs):

callers dataset threads=1 16, this PR p99 (1 → 16), this PR 16, e9c416f p99 at 16, e9c416f
16 50 GiB 3721 MB/s 9080 (2.44×) 215.3 → 87.5 ms 9022 89.3 ms
32 100 GiB 6042 MB/s 7621 (1.26×) 240.1 → 182.6 ms 7630 183.7 ms
64 100 GiB 8728 MB/s 9217 (1.06×) 331.6 → 277.7 ms 9232 276.8 ms

The numbers below were measured on the first revision (e9c416f), one run per
configuration. 8 callers × 16 helpers per call is 128, an eighth of the 1024 bound.

callers dataset threads=1 8 16 p50 per call (1 → 16) p99 per call (1 → 16)
8 25 GiB 2494 MB/s 7035 (2.82×) 8544 (3.43×) 100.2 → 27.6 ms 175.2 → 59.6 ms
1 9.4 GiB 5486 MB/s 12765 (2.33×) 12594 (2.30×) 5.4 → 0.9 ms 7.8 → 23.6 ms
  • With one caller, p99 rises with the pool (29.2 ms with 8 workers, 23.6 ms with 16)
    while p50 drops. With 8 callers both p50 and p99 drop.
  • With one caller, throughput is 12.2-13.5 GB/s for 4-16 workers and is the same with
    16 and 32 shards.

Local NVMe (for comparison only; our DFS deployments do not place shards on a local
disk; measured on the first revision, one run per configuration). 1 MiB objects, batch
64 (64 MiB per call), 1 caller, 3.2 GiB dataset,
posix_fadvise(DONTNEED) between sweeps:

shards threads=1 4 8 16
8 731 MB/s 2712 (3.71×) 3203 (4.38×) 3162 (4.33×)
32 551 MB/s 2190 (3.97×) 3127 (5.67×) 4171 (7.57×)
  • With 8 shards throughput stops growing at 8 threads; with 32 shards it keeps growing
    up to 16.
  • 8 concurrent callers, 8 shards: 4745 MB/s serial, 4941 MB/s with 8 workers (1.04×);
    with 16 workers p99 rises from 169 to 210 ms.
  • 64 KiB objects, 8 shards: 1.33× with 4 workers, 1.18× with 8, 1.04× with 16.

Default

The default is 16 workers for POSIX, chosen from the GPFS 8-caller run on the first
revision: 16 workers gave 3.43× and cut per-call p99 from 175 to 60 ms, versus 2.82×
with 8 workers. On this PR's code, 16 workers give 3.28× with p99 196 → 55 ms. The cost is
up to 16 resident threads per backend and, in bucket layout, up to 17 bucket fds per
call. Deployments that prefer fewer threads can lower MOONCAKE_DFS_READ_THREADS, and
=1 restores serial reads.

Checklist

  • Every commit I contribute includes my Signed-off-by trailer certifying the DCO
  • I have performed a self-review of my own code
  • I have formatted my code using ./scripts/code_format.sh
  • I have run pre-commit on the files changed in this PR and all hooks pass
  • I have updated the documentation (if applicable)
  • I have added tests to prove my changes are effective
  • For changes >500 LOC: I have filed an RFC issue

AI Assistance Disclosure

  • No AI tools were used
  • AI tools were used (specify below)

An AI coding assistant helped adapt the change to the current BatchRead structure,
resolve rebase conflicts, review the code, trim the tests, and draft this description.
I reviewed every changed line, ran the tests and benchmarks myself, and take
responsibility for the change.

Adapters without batch I/O (POSIX) executed BatchRead requests one by one.
Add an optional worker pool (MC_STORE_DFS_READ_THREADS) so the calling thread
and pool workers drain validated reads from a shared cursor. Adapters that
support batch I/O (3FS) keep the existing batched path.

Signed-off-by: zuozhubinge <260291091@qq.com>
@zuozhubinge
zuozhubinge force-pushed the dfs-batch-read-parallel branch from d23b968 to e9c416f Compare November 5, 2026 11:52
@github-actions github-actions Bot added size/M 100-1000 changed lines (additions + deletions) documentation Improvements or additions to documentation run-ci Store Common labels Nov 5, 2026

@fcczzz fcczzz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could we bound outstanding helper jobs across calls, or wait for every submitted job before returning? remaining only tracks reads, so the caller can finish a batch while its queued drain jobs still retain shared state. Repeated calls can accumulate these jobs while the workers are busy.

Also, PosixKeepsPerRequestBucketHandles still expects peak_open == 1, and its adapter counters are not thread-safe. With parallel reads enabled by default, this can fail or race. Could we explicitly keep that test serial, or synchronize the counters and update the expectations?

BatchRead returned once every read finished, while helper jobs still in the
pool queue kept the call's shared state alive. Repeated calls with busy
workers could pile up such jobs. Cap queued or running helper jobs at
MOONCAKE_DFS_READ_THREADS across calls; without a free slot the caller reads
the rest itself.

PosixKeepsPerRequestBucketHandles expects one open bucket at a time and uses
plain counters, so run it with MOONCAKE_DFS_READ_THREADS=1.

Signed-off-by: zuozhubinge <260291091@qq.com>
@zuozhubinge

Copy link
Copy Markdown
Contributor Author

@fcczzz Thanks for the review, both points make sense.

  1. I'll bound the helper jobs across calls rather than wait for every submitted job:
    on a busy pool, waiting would make a caller depend on other callers' work, which
    can end up slower than the serial path.
  2. I'll pin PosixKeepsPerRequestBucketHandles to the serial path, check the other
    DFS tests for the same assumption, and run them under TSan with the pool enabled.

I'll push the update this week.

The parallel read tests only covered shard layout. Add a bucket-layout test
with MOONCAKE_DFS_READ_THREADS=128 that reads one object per bucket and checks
content, balanced opens and closes, overlapping reads, and that one call holds
at most kMaxOpenBucketsPerBatch bucket fds.

Signed-off-by: zuozhubinge <260291091@qq.com>
@zuozhubinge

Copy link
Copy Markdown
Contributor Author

@fcczzz Pushed the fixes:

  • f70fd6f bounds helper jobs across calls. The backend counts helper jobs that are
    queued or running and caps them at MOONCAKE_DFS_READ_THREADS; a job releases its
    slot when it finishes. With at most as many jobs as pool threads, an enqueued job
    starts right away instead of waiting behind stale ones. When no slot is free the
    caller reads the rest itself.
  • PosixKeepsPerRequestBucketHandles now pins MOONCAKE_DFS_READ_THREADS=1, since
    its peak-open check and plain counters assume one read at a time. I checked the
    other DFS tests that read through custom POSIX adapters; their counters are atomic.
  • 5cdebf5 adds PosixParallelReadsBoundOpenBuckets, so bucket layout is covered with
    the pool enabled: 128 threads, one object per bucket, checks content, balanced
    opens/closes, overlapping reads, and at most kMaxOpenBucketsPerBatch fds per call.

Tests: ctest -R dfs (8 tests) passes. TSan: 30 runs each of dfs_posix_test and
dfs_immutable_bucket_backend_test, no reports apart from the known glog 0.6.0
CalcGmtOffset race, which is suppressed.

Capping queued plus running helper jobs at the pool size let the first of
several concurrent BatchRead calls hold every slot until its jobs finished;
later calls got no helpers. On GPFS with 8 callers and 16 workers this cut
throughput from 11650 to 8884 MB/s and raised per-call p99 from 41.2 to
118.7 ms.

A job now frees its slot when a worker picks it up, and only queued jobs are
capped, at 64x MOONCAKE_DFS_READ_THREADS. A cap of 8x still raised p99 by
18-43% once 16 to 64 callers reached it, so the cap is sized as a safeguard
that normal load does not reach; outstanding jobs stay bounded.

Signed-off-by: zuozhubinge <260291091@qq.com>
@zuozhubinge

Copy link
Copy Markdown
Contributor Author

@fcczzz A correction to my previous reply: the bound I pushed in f70fd6f lowered throughput and raised tail latency with concurrent callers, so a668fb6 replaces it.

What went wrong. f70fd6f capped queued plus running helper jobs at the pool size, and a job held its slot until it finished. With several concurrent BatchRead calls, the first call took every slot and later calls got no helpers, so they read serially. Same-session A/B on GPFS (8 callers, 16 shards, batch 32 × 1 MiB, 16 workers, medians of 3 runs per build):

MB/s p99 per call
e9c416f (no bound) 11650 41.2 ms
f70fd6f 8884 118.7 ms
f70fd6f + slot freed when a worker starts the job 10287 115.2 ms

What a668fb6 does. A job frees its slot when a worker picks it up, so the counter covers only jobs still waiting in the queue, and that count is capped at 64 × MOONCAKE_DFS_READ_THREADS (1024 with the default 16). Running jobs are already bounded by the thread count. When the cap is reached, the call enqueues no more helpers and reads the rest itself.

This gives up what my previous reply said, that an enqueued job starts right away: a job can now wait behind up to 1024 queued jobs. A job whose call has already finished exits after one fetch_add on the cursor.

Why 64×. Any cap that the measured loads reached raised p99. A cap of 8 × threads was fine at 8 callers, but on a larger dataset (64 shards × 2 GiB) it raised p99 from 92 / 186 / 273 ms to 132 / 251 / 321 ms at 16 / 32 / 64 callers. With the 64× cap, same setup, medians of 3 runs alternated between builds:

callers e9c416f MB/s / p99 a668fb6 MB/s / p99
16 9022 / 89.3 ms 9080 / 87.5 ms
32 7630 / 183.7 ms 7621 / 182.6 ms
64 9232 / 276.8 ms 9217 / 277.7 ms

64 callers × 16 helpers per call is 1024, the cap itself, so these runs cover loads up to the cap; they do not measure behavior above it. Above it, later calls get fewer helpers and their tail latency rises, but the queue stays bounded.

Tests on a668fb6: ctest -R dfs 8/8 pass; TSan, 30 runs each of dfs_posix_test and dfs_immutable_bucket_backend_test, 60/60 with no reports (same glog suppression as before). I updated the PR description with the bound and the new GPFS numbers.

zxpdemonio added a commit to zxpdemonio/Mooncake that referenced this pull request Nov 18, 2026
Let capable filesystem adapters share cached-shard read ownership while
keeping writes, lazy opening, and descriptor repair exclusive. POSIX opts
in; adapters with per-read state retain serialized reads by default.

Use a shard admission gate so new reads cannot bypass a writer or reopen
that already owns admission. Release failed readers before acquiring
exclusive ownership for the existing reopen/retry path.

Add regressions for overlap, adapter opt-out, writer exclusion, and safe
reopen. Complements the intra-batch read work in kvcache-ai#5283 without adding a
worker pool or changing configuration defaults.

Refs: kvcache-ai#5458
Signed-off-by: Cruz Zhao <CruzZhao@linux.alibaba.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Common documentation Improvements or additions to documentation run-ci size/M 100-1000 changed lines (additions + deletions) Store

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants