Skip to content

ReActAgent streaming pipeline: per-chunk serial handoffs inflate end-to-end latency ~2x at 500 concurrent streams (measured; repro + patch directions) #3929

Open

Description

@realreus319

Summary

When many ReActAgent streaming calls run concurrently, end-to-end latency grows far beyond what CPU usage can explain. The JVM stays at roughly 1 core while each stream waits. By source inspection (tag v2.0.4) and per-change A/B measurements on a fork, we traced most of the inflation to the per-chunk path in ReActAgent.modelCallStream: every model chunk crosses two concatMap stages and several Flux.create sink boundaries, and every chunk additionally triggers a legacy-hook dispatch that unconditionally builds the full accumulated message text — even when the consumer uses streamEvents and no hook needs the accumulated content.

This is a "death by a thousand handoffs" problem: each handoff is microseconds of work when threads are idle, but at 500 concurrent streams on a 4-core machine each boundary becomes a scheduling round-trip, and ~300 chunks per call × 10 calls per agent chain accumulate seconds of pure queueing per chain. Latency roughly doubles while CPU does not move.

Environment

  • AgentScope Java 2.0.4 (also present in 2.0.0), agentscope-extensions-model-openai 2.0.4, streamEvents API, JDK 21 and Temurin 27 (same behavior)
  • 4 vCPU VM, PostgreSQL 18 for chain-result persistence in the harness
  • Model: local stub server (OpenAI-compatible SSE), deterministic workload, no real LLM involved
  • Workload per agent chain: 10 model calls × 300 streamed tokens at 50 tok/s, with 9 tool calls in between (alternating trivial tools), i.e. ~61 s per chain unloaded by construction, exactly 3000 output tokens

Measured results (full benchmark harness)

Mean end-to-end chain time, 500 concurrent chains, 2 repeats per cell, 100% completion, 0 errors:

Variant Per-token delivery 100 ms burst delivery*
Stock 2.0.4 (streamEvents, JDK 27) 153.9 s 125.1 s
Locally patched build (3 small changes, §4) 113.4 s 87.6 s
Unloaded single chain (all variants) ~61 s ~61 s

* Real LLM APIs do not flush one SSE event per token; delivery is bursty (engine frames every few tens of ms, proxies coalesce further). We test both shapes; the burst shape is the realistic one. The pipeline overhead is large under both.

Reference numbers, same 500-concurrent-chain workload, burst delivery: other agent frameworks on the same harness finished at 149.9 s (multi-process) and 156.1 s (Node.js), so AgentScope is competitive — this issue is about the remaining ~2x gap to its own unloaded time, most of which appears recoverable inside the streaming pipeline.

JVM CPU during the 500-chain runs: ~1.0 core of 4. Thread dumps during the runs show 216–242 virtual threads parked in socket readLine waiting for the next SSE line, zero BLOCKED threads, no lock queues. This is queueing latency, not contention or computation.

Root-cause analysis (source: tag v2.0.4)

  1. ReActAgent.modelCallStream (~L2649) pipes the model flux through two serial concatMap stages:
    • stage 1 (~L2657): concatMap(chunk -> checkInterrupted().thenReturn(chunk)) — the inner work is a single atomic-flag read, but it is wrapped in a Mono + concatMap, so every chunk pays an asynchronous boundary;
    • stage 2 (~L2658): Flux.deferContextual(...) per chunk doing ReasoningContext.processChunk, hookDispatcher.fireReasoningChunk(...).subscribe() (a fire-and-forget side subscription created per chunk) and Flux.fromIterable(events) to flatten generated events.
      Together with the surrounding Flux.create sinks, a chunk crosses roughly 5–6 queue-drain boundaries before it reaches the consumer.
  2. LegacyHookDispatcher.fireReasoningChunk (~L75–80) unconditionally constructs an "accumulated" Msg via TextAccumulator.getAccumulatedText() — a full copy of all text received so far — before dispatching to hooks. For incremental consumers this copy is pure waste (quadratic total copying over a stream), and it is built even when no registered hook reads accumulated content, and on the streamEvents path where hooks are a legacy mechanism.
  3. The deprecated stream() API additionally produces legacy Events in parallel with AgentEvents and drains/discards one of the two streams internally (observed in 2.0.0; the modelCallStream structure is unchanged in 2.0.4).

Points already excluded by measurement: per-chunk state persistence (saveStateToSession is per-call), GC/heap (except the §5 note), tool execution, the network stub (a raw probe client sustains 24,010 tok/s against the same stub, 96% of the theoretical rate), and TCP/Nagle effects.

What we changed in a fork (directions, with per-change A/B attribution)

Same-session A/B, per-token delivery, one change at a time, each preceded by an unloaded calibration run (~61 s, exact 10/9/3000 counts):

Change Effect on 500-chain mean
Guard fireReasoningChunk: skip the accumulated-Msg construction (and the side subscription) when no hook consumes it −5.7 s
Replace the interruption-check concatMap with a synchronous check (handle/map) −5.1 s
Make event generation synchronous per chunk and flatten with concatMapIterable instead of an inner Flux per chunk −7.2 s

The three framework changes together recovered ~18 s of chain time under per-token delivery; under burst delivery the patched build leads stock by ~37 s (87.6 s vs 125.1 s). Ordering/backpressure semantics were preserved in each case (sequential per-chunk processing, no reordering, completion/error behavior unchanged; all runs 100% completion, exact token/tool counts).

We are not submitting these as a PR because they were made against a benchmark deadline and deserve a design review first — but they show the headroom is real and the fixes are local to the chunk path.

Secondary observations (smaller, arguably unreasonable defaults)

  1. ExecutionConfig.MODEL_DEFAULTS sets maxAttempts(3) (ExecutionConfig ~L145): a transient error mid-stream silently re-issues the entire streaming request, duplicating model calls and tokens. We only discovered this while auditing why request counts could exceed the issued count. For streaming calls, retry-by-default seems dangerous; at minimum it deserves a prominent doc warning. (Note TOOL_DEFAULTS uses maxAttempts(1).)
  2. The default JDK-HttpClient model transport funnels all connections through a single shared HttpClient / SelectorManager thread. In our earlier 2.0.0 runs this was a visible global coupling point at high stream counts; switching the transport to the OkHttp implementation was worth −16% end-to-end in that configuration. A single selector thread for hundreds of concurrent SSE streams is a fragile default.
  3. InMemoryAgentStateStore grows without bound — a second consecutive 500-chain batch in the same JVM degraded catastrophically (heap 1005/1024 MB, ~160 s in GC). The docs already position it as test-grade, so this is a sharp edge rather than a bug; an explicit capacity/eviction note (or a warning log) would help, since it is the store every quickstart example ends up using.

Reproduction

Minimal self-contained demo (stub SSE server + streamEvents driver, no external services): https://github.com/realreus319/agentscope-streaming-repro

mvn -q package -DskipTests
# quick smoke (finishes in seconds)
java -Dchains=5 -Dstub.tokens.per.call=30 -Dstub.token.interval.ms=2 -jar target/agentscope-streaming-repro-1.0.0.jar
# full repro: ~61 s per chain at 5 concurrency; watch the mean grow at 500
java -Dchains=500 -jar target/agentscope-streaming-repro-1.0.0.jar

In the demo itself (stub and agents share one JVM, no HTTP front-end or DB) the observed inflation is milder — 5 chains ≈ 61 s, 500 chains ≈ 80–83 s mean — while the table above is from the full harness. Both show the same shape: exact counts, zero errors, low CPU, latency up.

The effect scales with the concurrency-to-core ratio; on a many-core machine use more chains (or pin fewer cores, e.g. taskset -c 0-3) to reproduce the 4-core numbers above.

Suggestions

  • Short-circuit the hook dispatch when no hooks are registered / none consume accumulated content; never build the accumulated message speculatively per chunk.
  • Collapse the interruption check into the synchronous chunk path (it is an AtomicBoolean read).
  • Avoid creating an inner Flux (and a side .subscribe()) per chunk; a synchronous transform + concatMapIterable preserves order and backpressure.
  • Reconsider maxAttempts(3) as the default for streaming model calls, or document the duplication risk prominently.
  • Consider making the OkHttp transport the documented recommendation for high-concurrency streaming, or parallelizing the JDK transport's selector handling.

Happy to provide the full benchmark harness, raw data, or to test a patched build if maintainers want to explore any of these directions.

Activity

  1. changed the title [-]ReActAgent streamEvents latency inflates at high concurrency (500 chains: mean 61s -> 80s, eff. 49 -> 37 tok/s)[/-] [+]ReActAgent streaming pipeline: per-chunk serial handoffs inflate end-to-end latency ~2x at 500 concurrent streams (measured; repro + patch directions)[/+] on Nov 2, 2026
  2. xihongshichaojidan8 commented on Nov 3, 2026

    @xihongshichaojidan8
    Contributor

    我在当前 main(55013a429)上用本地 SSE 服务进行了对照测试,发现逐 chunk 的背压请求与模型、JDK transport 两层 subscribeOn 存在调度放大:500 个并发请求、每请求 300 个文本 chunk,产生约 151,000 次 request(1),而纯模型路径只有 500 次需求请求。这里统计的是 Reactive Streams 的需求请求,不是 HTTP 请求;各组 HTTP 请求数均为 500,输出完整。

    我尝试保留订阅调度、关闭模型层的 request 重调度。虽然消除了往返调度,但出现性能取舍:集中发送场景下,首文本平均延迟从约 82–120ms 增至 1047–1093ms,总耗时也上升,因此已撤回该候选。

    这些结果来自单机、单轮模型调用的本地测试,并非原报告完整环境。目前不建议直接关闭请求调度或增加预取。

    想请维护者确认:这个问题更希望优先改善高并发总耗时,还是保持首文本响应和读取公平性?是否有建议采用的基准场景?我可以提供测试代码和详细结果。

  3. wahllllll commented on Nov 4, 2026

    @wahllllll
    Contributor

    Took the first of your three directions in #3961: skip the accumulated snapshot and the per-chunk subscription when no hook is registered.

    What it does:

    • LegacyHookDispatcher.hasHooks(), with an early return in fireReasoningChunk and fireSummaryChunk before context.getAccumulatedText() runs, and the same in fireActingChunk.
    • The reasoning and summary chunk stages in ReActAgent skip the contextWrite(...).subscribe() entirely when no hook is registered, so the Mono allocation and context copy per chunk are gone too.

    With a hook registered nothing changes: same accumulated Msg, same incremental chunk, same order — the early return only replaces the Flux.fromIterable(empty) that already yielded Mono.empty().

    Test: LegacyHookDispatcherChunkTest asserts ReasoningContext.getAccumulatedText() is never invoked with no hooks (fails on main with Mockito's "Never wanted here... But invoked here"), for both the reasoning and summary shapes, and that a registered hook still sees the snapshot. That is not your −5.7 s measurement — it is the invariant behind it — so a re-run of your harness against the branch would be the number worth having, and I would rather your benchmark confirm it than my assertion.

    I deliberately left the other two changes out. Swapping the interrupt-check concatMap for a synchronous check and flattening the per-chunk inner Flux via concatMapIterable change the pipeline shape; you asked for a design review first, and bundling them would make each one unverifiable in isolation. If you want to fold them in, the same test file is the place to pin ordering and backpressure.

    Two notes on your secondary observations, since they are separate defects rather than part of this fix:

    • ExecutionConfig.MODEL_DEFAULTS.maxAttempts(3) on a streaming call re-issuing the whole request also duplicates the recorded request/prepared events for one call, which would surprise anyone reading a session journal after a retry.
    • The InMemoryAgentStateStore growth you saw in the second batch is worth its own issue; the docs position it as test-grade but nothing fails loudly when it is used as the default in a long-lived process.
  4. realreus319 commented on Nov 9, 2026

    @realreus319
    Author

    Thanks to both of you for digging in — @xihongshichaojidan8 for the independent reproduction (151k request(1) calls against 500 model requests matches our reading of the pipeline) and for actually testing the request-scheduling direction, and @wahllllll for PR #3961.

    On the priority question (total time vs first-token latency / fairness): our data argues for total time at high concurrency as the primary target, with first-token latency as a guardrail rather than the objective, for two reasons:

    1. The inflation is queueing, not starvation. In our runs the JVM sits at ~1 core, thread dumps show streams parked on socket reads with zero lock contention, and chains progress together — the P95/mean ratio stays tight (e.g. 89.1 s / 87.9 s in the burst-delivery runs). No stream is being starved; every stream is slowed by the same per-chunk handoffs. Removing handoffs (as perf(core): skip the per-chunk hook snapshot when no hook is registered #3961 does) improved total time in our measurements with no first-token penalty beyond noise.
    2. First-token latency is extremely sensitive to how the model delivers tokens, and real providers do not emit one SSE event per token — delivery is bursty (engine frames every few tens of ms, proxies coalesce further). TTFT measured against a per-token metronome stream looks artificially good. With 2.0.4 under 100 ms burst delivery, TTFT at 500 concurrency measured 3.23 s in our latest runs. We would suggest judging TTFT only under bursty delivery, otherwise the benchmark rewards the wrong thing.

    Suggested benchmark scenario (what we use; happy to standardize on it): one agent chain = 10 streaming model calls × 300 tokens at 50 tok/s, with 9 local tool calls in between (~61 s per chain unloaded); N chains concurrently (5 / 50 / 100 / 500) against a deterministic stub server (no real LLM); report mean/P95 chain time, TTFT, completion rate, and exact model-call/tool-call/token counts. Self-contained repro: https://github.com/realreus319/agentscope-streaming-repro

    Fresh data since this issue was filed — we re-ran the full comparison under burst delivery and added Go and Rust reference frameworks. Same workload, same 4-vCPU machine, mean chain time at 500 concurrent chains:

    Framework 500 chains
    Rig (Rust, rig-core 0.46.0) 68.4 s
    Eino (Go, v0.9.22) 87.5 s
    AgentScope 2.0.4 + the three local patches from this issue (reference, not stock) 87.6 s
    AgentScope 2.0.4 stock 125.1 s
    Pi multi-process (Node.js) 149.9 s
    Mastra (Node.js) 156.1 s
    Pi single-process (Node.js) 228.3 s

    Two takeaways: stock AgentScope is already the fastest of the JVM/Node frameworks we tested — the remaining gap is to the native rows, whose per-chunk handoff cost is evidently much lower; and the patched build closes most of the gap to Go's Eino, which is why we think the changes in this issue are worth pursuing beyond the first one in #3961.

  5. juruoO-o commented on Nov 12, 2026

    @juruoO-o
    Collaborator

    Status update: #3961 and #4088 (both merged) landed the first two of the three measured changes (skip the per-chunk hook snapshot when no hook is registered; synchronous interruption check between streamed chunks). The third change remains open.

  6. wahllllll commented on Nov 12, 2026

    @wahllllll
    Contributor

    Both of the first two changes are merged now — #3961 (the per-chunk hook-snapshot guard, measured at −3.6 s per chain on main by @realreus319's harness) and #4088 (the synchronous interruption check, which stops the interrupt on the in-flight chunk; timing flat, no regression).

    That leaves the third item — synchronous event generation with concatMapIterable. #4088's measurements suggest this family's wins on current main are smaller than the original 2.0.4 numbers implied, and this one reshapes the chunk path rather than removing waste, so I would not open it without a reason. @realreus319 is it still wanted on your side, and would you rather measure it first or have us prototype it for your harness to judge?

  7. realreus319 commented on Nov 14, 2026

    @realreus319
    Author

    Update: re-ran the benchmark on current main (head 36cabf4a, 2026-11-13) after both PRs landed, same harness and delivery as v4 (burst delivery, 500 chains max, fresh JVMs; the 500 group ran twice):

    concurrency 2.0.4 (v4) current main fork reference (v4)
    5 62.16 s 61.82 s 61.67 s
    50 64.67 s 63.99 s 63.95 s
    100 68.75 s 67.08 s 66.17 s
    500 125.05 s 112.17 s (115.15 / 109.20) 87.56 s

    So main is ~12.9 s faster at 500 (−10.3%), TTFT essentially unchanged (3.71 s vs 3.23 s in v4, within session drift), and low concurrency is at the unloaded floor. Two caveats: the −12.9 s is a cross-session comparison, not a per-change attribution (the two 500 groups in this session alone differed by ~6 s); and the remaining gap to the fork reference (24.6 s) is the unmerged third change plus our own harness-side batching, which was never a framework change. The 75 s target is still 37.2 s away at 500. The third change (concatMapIterable) is still the open piece.

  8. wahllllll commented on Nov 15, 2026

    @wahllllll
    Contributor

    Thanks for the re-run — main at −10.3% on the 500-chain mean with flat TTFT and the low-concurrency floor unchanged is exactly the evidence trail worth having, and the cross-session caveat is noted.

    We picked up the third change: #4197 flattens both chunk paths (reasoning and summary) to synchronous per-chunk event generation via concatMapIterable. The subscriber context is constant along the chunk chain, so hook delivery now captures it once per stream instead of once per chunk — ordering and completion semantics are unchanged and pinned by tests. Your harness is the judge on the number: if it moves the 500-chain mean toward your fork reference, that closes out all three directions in #3929; if it doesn't, we would rather know now.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions