Repository navigation
Description
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-openai2.0.4,streamEventsAPI, 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)
ReActAgent.modelCallStream(~L2649) pipes the model flux through two serialconcatMapstages:- stage 1 (~L2657):
concatMap(chunk -> checkInterrupted().thenReturn(chunk))— the inner work is a single atomic-flag read, but it is wrapped in aMono+concatMap, so every chunk pays an asynchronous boundary; - stage 2 (~L2658):
Flux.deferContextual(...)per chunk doingReasoningContext.processChunk,hookDispatcher.fireReasoningChunk(...).subscribe()(a fire-and-forget side subscription created per chunk) andFlux.fromIterable(events)to flatten generated events.
Together with the surroundingFlux.createsinks, a chunk crosses roughly 5–6 queue-drain boundaries before it reaches the consumer.
- stage 1 (~L2657):
LegacyHookDispatcher.fireReasoningChunk(~L75–80) unconditionally constructs an "accumulated"MsgviaTextAccumulator.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 thestreamEventspath where hooks are a legacy mechanism.- The deprecated
stream()API additionally produces legacyEvents in parallel withAgentEvents and drains/discards one of the two streams internally (observed in 2.0.0; themodelCallStreamstructure 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)
ExecutionConfig.MODEL_DEFAULTSsetsmaxAttempts(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. (NoteTOOL_DEFAULTSusesmaxAttempts(1).)- The default JDK-HttpClient model transport funnels all connections through a single shared
HttpClient/SelectorManagerthread. 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. InMemoryAgentStateStoregrows 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.jarIn 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
AtomicBooleanread). - Avoid creating an inner
Flux(and a side.subscribe()) per chunk; a synchronous transform +concatMapIterablepreserves 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
[-]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)[/+]xihongshichaojidan8 commentedon Nov 3, 2026
我在当前 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,总耗时也上升,因此已撤回该候选。
这些结果来自单机、单轮模型调用的本地测试,并非原报告完整环境。目前不建议直接关闭请求调度或增加预取。
想请维护者确认:这个问题更希望优先改善高并发总耗时,还是保持首文本响应和读取公平性?是否有建议采用的基准场景?我可以提供测试代码和详细结果。
wahllllll commentedon Nov 4, 2026
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 infireReasoningChunkandfireSummaryChunkbeforecontext.getAccumulatedText()runs, and the same infireActingChunk.ReActAgentskip thecontextWrite(...).subscribe()entirely when no hook is registered, so theMonoallocation 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 theFlux.fromIterable(empty)that already yieldedMono.empty().Test:
LegacyHookDispatcherChunkTestassertsReasoningContext.getAccumulatedText()is never invoked with no hooks (fails onmainwith 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
concatMapfor a synchronous check and flattening the per-chunk innerFluxviaconcatMapIterablechange 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 recordedrequest/preparedevents for one call, which would surprise anyone reading a session journal after a retry.InMemoryAgentStateStoregrowth 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.realreus319 commentedon Nov 9, 2026
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:
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:
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.
perf(core): skip the per-chunk hook snapshot when no hook is register…
fix(core): check interruption synchronously between streamed chunks (#…
juruoO-o commentedon Nov 12, 2026
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.
wahllllll commentedon Nov 12, 2026
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?realreus319 commentedon Nov 14, 2026
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):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.
wahllllll commentedon Nov 15, 2026
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.