Skip to content

[serve][release] Add TTFT and inter-token jitter metrics to streaming microbench - #63391

Closed
kouroshHakha wants to merge 4 commits into
ray-project:masterfrom
kouroshHakha:kh/serve-microbench-streaming-ttft-jitter
Closed

kouroshHakha wants to merge 4 commits into
ray-project:masterfrom
kouroshHakha:kh/serve-microbench-streaming-ttft-jitter

Conversation

@kouroshHakha

Copy link
Copy Markdown
Contributor

Summary

Adds two new per-request metric families to the existing streaming setups in pytest_serve_microbenchmarks:

  • TTFT (time-to-first-token): client-side delta from request issue to the first chunk delivered by iter_chunks() (HTTP) / first yield from the handle stream generator (handle). Reports p50 / p90 / p95 / p99 in ms.
  • Inter-token / inter-chunk latency: time between successive chunk arrivals, flattened across all requests in the pass. Reports p50 / p90 / p99 / p99.9 — captures the jitter that Nagle on loopback would inflate.

Both metric families are emitted at two concurrencies per streaming setup:

  • bs=1 × 20 trials — clean per-stream signal; isolates server-side first-token + emission cadence.
  • bs=64 × 5 trials — same metrics under moderate client concurrency; checks whether jitter stays bounded under load.

Metric naming: <setup>_ttft_p{50,90,95,99}_{bs1,bs64} and <setup>_inter_token_p{50,90,99,999}_{bs1,bs64}. Applied to all three existing streaming setups: http_streaming, http_intermediate_streaming, handle_streaming. 48 new perf metrics total. All LATENCY type, default alert priority.

Motivation

The current streaming microbenchmarks only emit aggregate end-to-end latency and tokens-per-second. Neither catches a regression in per-token emission cadence: a deploy could double inter-token jitter while keeping total stream time and TPS roughly unchanged, and nightly would not see it. The motivating concrete case is RAY_SERVE_HAPROXY_TCP_NODELAY (#63353) — Nagle delays bunch up the inter-chunk gap distribution without necessarily moving the mean. Sibling to #63386, which adds the HAProxy variant of these microbenchmarks; together, the new metrics will automatically ride the .aws.haproxy row and surface the TCP_NODELAY signal under HAProxy.

No release_tests.yaml change is required — the new metrics piggyback on the existing pytest_serve_microbenchmarks* rows.

Implementation

  • python/ray/serve/_private/benchmarks/common.py
    • do_single_http_streaming_with_per_chunk_timing(url, batch_size) mirrors do_single_http_batch(stream=True) but records per-chunk arrival timestamps and returns (ttft_ms_per_request, flattened_inter_chunk_ms, total_ms_per_request). The existing do_single_http_batch is unchanged so the throughput metrics keep their meaning.
    • Benchmarker.run_streaming_with_per_chunk_timing(batch_size, num_trials) and _do_single_stream_with_timing() are the handle-path equivalents — recording arrival timestamps from the handle stream generator.
  • release/serve_tests/workloads/microbenchmarks.py
    • convert_per_chunk_timings_to_perf_metrics(name, bs_suffix, ttft_ms, inter_chunk_ms) builds the eight perf metrics for one pass.
    • _run_http_per_chunk_timing_passes() / _run_handle_per_chunk_timing_passes() run the bs=1 and bs=64 passes against the already-running app, before the existing serve.shutdown_async() call — so no extra deployment churn.

Caveats / things to be aware of

  • Loopback under-reports Nagle's true cost. Even with TCP_NODELAY=0, Linux loopback has a much shorter effective delayed-ACK than a real WAN. This benchmark gives a directional signal (NODELAY=0 vs =1), not a production estimate. Documented inline in the metric converter docstring. Adding tc netem was considered and rejected as too unstable on shared CI.
  • bs=64 inter-token p99.9 will be 10-100× the bs=1 number even on a healthy system, because asyncio is interleaving 64 streams at the client. That's the intended signal (jitter under load), not a regression — the two bs values are reported separately so a regression in one doesn't get hand-waved by the other.

Test plan

  • Local: with RAY_SERVE_ENABLE_HA_PROXY=1, compare RAY_SERVE_HAPROXY_TCP_NODELAY=0 vs =1. Expect measurably higher inter_token_p99 / p999 (and possibly TTFT) at =0. If the metric doesn't flip directionally, the benchmark isn't exercising what we claim — revisit before merge.
  • Two BK release runs on this branch, same approach as [serve] Default RAY_SERVE_HAPROXY_TCP_NODELAY to 1 #63353's validation — one with TCP_NODELAY=0, one with =1, to confirm the metric flips under the gated condition end-to-end on release infra.
  • Sanity check that iter_chunks() is yielding per server-send and not buffer-flush-coalesced before trusting absolute numbers (one-time, on a local run).

Alerts: new metrics inherit the default alert setting on the existing test rows. Intent is to gather 2–3 weeks of baseline before considering tightening any of TTFT p99 / inter-token p99.9 to stability-class.

🤖 Generated with Claude Code

… microbench

Adds per-chunk timing passes (TTFT + inter-token gap percentiles) to the
existing pytest_serve_microbenchmarks streaming setups. Two batch sizes per
setup: bs=1 isolates the clean per-stream signal, bs=64 measures whether
jitter stays bounded under moderate client concurrency. Reuses the existing
Streamer/IntermediateRouter workload — no new deployment shapes, no
release_tests.yaml change.

The new metrics ride the existing test rows automatically, so the
.aws.haproxy variant will surface TTFT/jitter numbers under HAProxy, which
is where the Nagle signal lives. Metrics are emitted at default alert
priority; intent is to gather 2-3 weeks of baseline before tightening.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@kouroshHakha
kouroshHakha requested a review from a team as a code owner May 16, 2026 02:23

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces per-chunk timing benchmarks for Ray Serve streaming to measure Time To First Token (TTFT) and inter-token jitter across HTTP and internal handles. The changes include new measurement utilities and the integration of these metrics into existing microbenchmarks. Feedback focuses on improving resource management by ensuring the aiohttp session takes ownership of its connector to prevent leaks and adopting more idiomatic pandas usage for filtering missing values.

Comment on lines +146 to +149
connector = aiohttp.TCPConnector(limit=batch_size)
async with aiohttp.ClientSession(
connector=connector, raise_for_status=True
) as session:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The aiohttp.TCPConnector is created outside the ClientSession and is not explicitly closed. In aiohttp, when a connector is passed to ClientSession, the session does not take ownership of its lifecycle by default, which can lead to resource leaks (unclosed file descriptors) and warnings.

You can fix this by passing connector_owner=True to the ClientSession constructor or by nesting the connector creation directly in the session's async with block.

Suggested change
connector = aiohttp.TCPConnector(limit=batch_size)
async with aiohttp.ClientSession(
connector=connector, raise_for_status=True
) as session:
async with aiohttp.ClientSession(
connector=aiohttp.TCPConnector(limit=batch_size),
connector_owner=True,
raise_for_status=True,
) as session:

under-report Nagle's true cost. The benchmark is intended to give a
directional signal (NODELAY=0 vs =1), not a production estimate.
"""
ttft_series = pd.Series([x for x in ttft_ms if x == x]) # drop NaN

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Using a list comprehension with x == x to filter out NaN values is less idiomatic in a codebase that already leverages pandas. Using dropna() is more readable and standard for this purpose.

Suggested change
ttft_series = pd.Series([x for x in ttft_ms if x == x]) # drop NaN
ttft_series = pd.Series(ttft_ms).dropna()

kouroshHakha and others added 2 commits May 15, 2026 19:32
…ypass)

Adds a fourth streaming setup, direct_streaming, that exercises the same
ingress_request_router topology Ray Serve LLM uses under
RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING: HAProxy POSTs /internal/route to a
generic CPU-only DirectStreamingRouter to pick a backend replica, then
forwards the request body directly to that replica's backend HTTP port.
Tokens stream back from the replica to the proxy without traversing the
router.

This lets CI regression-test the optimal-path combination (HAProxy +
TCP_NODELAY=1 + OPTIMIZED_THROUGHPUT=1 + direct streaming) without GPUs
or LLM dependencies, by exercising the generic Serve infrastructure
under the same env shape. Only emits under RAY_SERVE_ENABLE_HA_PROXY=1 —
ingress_request_router requires HAProxy and Serve refuses to build the
app otherwise; in the default (non-haproxy) variant the setup is silently
skipped.

Emits direct_streaming_{avg_tps, throughput_std, p50_latency, p90_latency,
p95_latency, p99_latency, ttft_p*_bs{1,64}, inter_token_p*_bs{1,64}} —
same shape as the other three streaming setups.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…run-direct-streaming flag

Two changes:

1. DirectStreamingRouter.route() now passes _reserve=False to
   choose_replica. The router only returns the picked replica's endpoint
   to HAProxy; HAProxy forwards the request body directly to that replica
   and we never call dispatch() through this handle. Without _reserve=False
   the slot is reserved but never consumed, leaking reservations.

2. Split direct_streaming out from --run-streaming into its own
   --run-direct-streaming flag, nested under run_http (so the structure
   reads as: `if run_http: if run_direct_streaming: ...`). Excluded from
   --run-all by default since it requires RAY_SERVE_ENABLE_HA_PROXY=1;
   intended to be opted into by the haproxy variant's release_tests.yaml
   command line.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 63a9563. Configure here.

or run_latency
or run_throughput
or run_streaming
or run_direct_streaming

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

--run-direct-streaming alone silently runs nothing

Medium Severity

Passing --run-direct-streaming alone produces zero metrics with no error. The flag is included in the "none-set?" guard (line 753), preventing run_all from activating, but the if run_direct_streaming: block (line 481) is nested inside if run_http:, which remains False. The benchmark silently completes with empty perf_metrics.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 63a9563. Configure here.

# to HAProxy, which forwards the request body directly. We never call
# dispatch() on this handle, so reserving a slot would leak (the slot
# is normally consumed by dispatch() and we have nothing to consume it).
async with self._handle.choose_replica(_reserve=False) as selection:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

_reserve=False kwarg silently ignored by choose_replica

Low Severity

The _reserve=False kwarg passed to self._handle.choose_replica() is not a recognized parameter. The choose_replica API accepts *args, **kwargs and forwards them as request kwargs into PendingRequest. The router still calls _pick_and_reserve_replica, so a slot IS reserved. The code works only because the context manager's finally block releases the slot on exit — not because _reserve=False prevents reservation as the comment claims.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 63a9563. Configure here.

…--run-direct-streaming

The direct_streaming setup now errors fast if the production env var
RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1 is not set, in addition to the
existing RAY_SERVE_ENABLE_HA_PROXY=1 requirement. Both must be present
along with the --run-direct-streaming flag — this guarantees the
microbench measures the exact configuration shape Ray Serve LLM ships
with, so regressions in any of the four optimal-path flags (HAProxy +
TCP_NODELAY + THROUGHPUT_OPTIMIZED + DIRECT_STREAMING) surface against
the right baseline.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@kouroshHakha
kouroshHakha marked this pull request as draft May 16, 2026 03:13
akyang-anyscale pushed a commit to kouroshHakha/ray that referenced this pull request May 20, 2026
Adds RAY_SERVE_LLM_ENABLE_DIRECT_STREAMING=1 to the haproxy variant's
runtime_env and --run-direct-streaming to the command line, so the
nightly haproxy row exercises the optimal-latency configuration end to
end: HAProxy + TCP_NODELAY=1 (default in ray-project#63353) + THROUGHPUT_OPTIMIZED=1
+ direct streaming via ingress_request_router bypass.

Depends on ray-project#63391, which defines --run-direct-streaming and
DirectStreamingRouter. Without ray-project#63391 merged, this command line will
fail at click parse time.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: akyang-anyscale <[email protected]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label May 30, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

@github-actions github-actions Bot closed this Jun 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant