Skip to content

[serve][llm] Enable ingress request router session affinity and tokenizer caching - #67940

Merged
jeffreywang88 merged 5 commits into
masterfrom
serve-llm-kv-session-token-cache
Nov 19, 2026
Merged

jeffreywang88 merged 5 commits into
masterfrom
serve-llm-kv-session-token-cache

Conversation

@jeffreywang88

@jeffreywang88 jeffreywang88 commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Description

Multi-turn requests can reach different LLMRouter replicas and repeatedly tokenize shared conversation prefixes. This PR routes a session to a stable ingress router and configures fastokens’ native segment cache to reuse tokenized segments across turns and branches.

  • Use HAProxy’s native hash-type consistent (algorithm) sdbm (hash function) avalanche (post-processing). Deterministic server IDs derived from replica names keep mappings consistent across HAProxy processes, regardless of server ordering or local IP rewriting.
  • Route consultations with session IDs through a private Unix-socket listener (see diagram below) so the existing Lua request flow can use HAProxy’s native backend selection.
  • Requests without a session use local round robin. Cross-process affinity requires matching router membership, weights, and health views.
sequenceDiagram
    participant C as Client
    box One HAProxy process
        participant P as Public listener / Lua
        participant B as Private Unix listener + hash backend
    end
    participant R as LLMRouter
    participant S as LLMServer / vLLM

    C->>P: Inference request + session ID
    Note over P: Original request waits

    P->>B: Consultation over local Unix socket
    B->>R: Hash session ID, POST /internal/route
    Note over R: Reuse tokenized segments<br/>Choose an LLMServer
    R-->>B: Selected replica ID + routing headers
    B-->>P: Consultation result

    P->>S: Forward original inference request
    S-->>P: Generated tokens
    P-->>C: Stream response
Loading

Configurations

  • Default FASTOKENS_SEGMENT_CACHE to 1024 MiB per native cache. Configuration in LLMConfig.runtime_env.env_vars takes precedence over the inherited environment. Fastokens enablement remains controlled by VLLM_USE_FASTOKENS, keeping the router and engine on the same tokenizer backend.

Benchmark

1. AgentX + mocker engines

Setup follows #67917. This PR optimizes work at the ingress router, so the benefits shouldn't compound as the deployment scales. I'm sweeping across deployment sizes to confirm this.

Screenshot 2026-11-07 at 12 20 31 AM

Note: We use mocker engines to filter optimization candidates and realistic LLM deployments below to validate the benefits brought by the optimization.

2. AgentX + 8 replicas across 2 nodes with DSV4.1-Flash on B200s

Setup

Results

Concurrency per replica Configuration Throughput p90 TTFT p90 TPOT
64 Master 1318.1 708 8.22
+ Replica mesh #67917 1319.7 691 8.23
+ Tokenization cache #67940 1329.2 608 8.15
+ KV-router CPU #67981 1334.8 570 8.11
128 Master 2009.9 3296 15.70
+ Replica mesh #67917 2008.1 3106 15.69
+ Tokenization cache #67940 2055.0 2313 15.56
+ KV-router CPU #67981 2069.3 2109 15.50

Tokenization cache alone, with replica mesh as the baseline, results in up to 25% p90 TTFT reduction (c128).

Related issues

Follow-up to #67917, adding ingress affinity and tokenization reuse on top of the replica mesh and lifecycle work.

Additional information

Validation

  • Determinism: 100,000 session IDs across three HAProxy processes and 1,000 configured routers; zero mismatches over 400,000 requests, including restart. Varied addresses, ordering, and thread counts.
  • Failover and recovery: Both proxies excluded a stopped router and restored its original session assignments after recovery.

Comment thread python/ray/serve/_private/haproxy.py Resolved
@jeffreywang88
jeffreywang88 marked this pull request as ready for review November 9, 2026 08:22
@jeffreywang88
jeffreywang88 requested review from a team as code owners November 9, 2026 08:22
@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Nov 9, 2026

@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 session affinity at the ingress level using HAProxy consistent hashing to route requests with the same session ID to the same ingress request router, enabling tokenized conversation prefix reuse across turns. It also configures fastokens segment caching for the KV-aware router and updates HAProxy templates and Lua scripts to support routing via a Unix socket. The feedback suggests capping the HAProxy ingress request router weight at 256 to prevent startup failures, correcting the documented environment variable name for HAProxy retries, and moving the fastokens patch import inline in tests to avoid import-time and offline CI failures.

Comment thread python/ray/serve/_private/constants.py Resolved
from transformers import AutoTokenizer
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.completion.protocol import CompletionRequest
from vllm.tokenizers.fastokens import apply_fastokens_patch

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

Remove the top-level import of apply_fastokens_patch to prevent import-time failures when fastokens is not installed.

@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.

Stale Bugbot comment from a previous run.

@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Nov 9, 2026
@jeffreywang88
jeffreywang88 force-pushed the serve-llm-kv-session-token-cache branch from 077857a to 7cda0c2 Compare November 10, 2026 01:14

@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 using default effort and found 2 potential issues.

There are 3 total unresolved issues (including 1 from previous review).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 7cda0c2. Configure here.

Comment thread python/ray/serve/_private/haproxy.py Resolved
@jeffreywang88
jeffreywang88 force-pushed the serve-llm-kv-replica-mesh-zmq branch from 0af82ed to d944e28 Compare November 10, 2026 17:35
@jeffreywang88
jeffreywang88 force-pushed the serve-llm-kv-replica-mesh-zmq branch from d944e28 to 0af82ed Compare November 10, 2026 17:40
@eicherseiji
eicherseiji removed request for a team November 10, 2026 19:15

@eicherseiji eicherseiji 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.

(How) does this design generalize to multi-model application sets? I.e. application sets using @celinaky's control application?

@jeffreywang88
jeffreywang88 changed the base branch from serve-llm-kv-replica-mesh-zmq to master November 13, 2026 19:55
@jeffreywang88
jeffreywang88 force-pushed the serve-llm-kv-session-token-cache branch from 7cda0c2 to 777a788 Compare November 13, 2026 19:55
@jeffreywang88

Copy link
Copy Markdown
Contributor Author

Rebasing onto master to merge independently of #67917

@jeffreywang88

Copy link
Copy Markdown
Contributor Author

(How) does this design generalize to multi-model application sets?

As of #67218, each router application replica holds one Tokenizer per KV-aware model. today HAProxy round robins each request to a router application replica. that replica reads model from the body and tokenizes with that model's tokenizer.

To use the token cache, we apply the same consistent hashing on session ID when HAProxy selects the router application replica, and set FASTOKENS_SEGMENT_CACHE on router application replicas.

Tracking with #68146.

… hop cost

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
jeffreywang88 added a commit that referenced this pull request Nov 19, 2026
## Description
Reduce per-request CPU overhead in `LLMRouter`:

- Parse JSON with `msgspec` instead of `json.loads`. `msgspec` is faster
because it parses UTF-8 bytes directly. `json.loads(body)` first decodes
the entire byte buffer into a python string, adding an allocation and
processing pass. [msgspec reads the buffer
directly](https://github.com/msgspec/msgspec/blob/main/src/msgspec/_core.c),
while [CPython performs that conversion
first](https://github.com/python/cpython/blob/3.12/Lib/json/__init__.py#L307).
- Encode token IDs with `array.array("I")` instead of constructing a
numpy array. `array.array("I", ids)` allocates a flat buffer and
converts the integers in one C loop. `np.asarray(ids, dtype="<u4")`
first discovers the input’s shape, then allocates and fills the array
through its general conversion machinery.
- Return vLLM’s token list directly, avoiding concatenation and copying
for single-prompt requests (multi-prompt requests aren't supported
anyways).

These changes optimize existing behavior, so they reuse existing
correctness coverage:

- `test_tokenizer_exactness.py` compares chat/completion tokens against
transformers and exercises Anthropic token staging and reuse.
- `test_token_channel.py` verifies token IDs survive encoding, ZMQ
delivery, decoding, and forwarding to the selected replica.
- Existing router tests cover request-body parsing and routing.

## Benchmark
### 1. Mocker engine
Setup follows #67917. This PR's
optimization results in **7-10 ms TTFT reduction**.

|  | Client TTFT p50 / p90 (ms) | Client → engine arrival p50 / p90 (ms)
| -- | -- | -- |
| N=1 (this PR) | 67.0 / 289 | 13.8 / 34.0 |
| N=1 (pre-PR) | 74.3 / 294 | 19.3 / 52 |
| N=16 (this PR) | 76.7 / 441.3 | 15.1 / 38.4 |
| N=16 (pre-PR) | 86.3 / 448.2 | 20.9 / 59.2 |

Client TTFT: from the AgentX client sending the request to receiving the
first token.

### 2. Realistic LLM deployments: AgentX + 8 replicas across 2 nodes
with DSV4.1-Flash on B200s
| Concurrency per replica | Configuration | Throughput | p90 TTFT | p90
TPOT |
| --- | --- | --- | --- | --- |
| 64 | Master | 1318.1 | 708 | 8.22 |
| | + Replica mesh #67917 | 1319.7 | 691 | 8.23 |
| | + Tokenization cache #67940 | 1329.2 | 608 | 8.15 |
| | + KV-router CPU #67981 | **1334.8** | **570** | **8.11** |
| 128 | Master | 2009.9 | 3296 | 15.70 |
| | + Replica mesh #67917 | 2008.1 | 3106 | 15.69 |
| | + Tokenization cache #67940 | 2055.0 | 2313 | 15.56 |
| | + KV-router CPU #67981 | **2069.3** | **2109** | **15.50** |

KV-router CPU overhead reduction alone results in **9% p90 TTFT
reduction** on top of tokenization cache.

## Related issues
> Link related issues: "Fixes #1234", "Closes #1234", or "Related to
#1234".

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

Signed-off-by: Jeffrey Wang <[email protected]>
@jeffreywang88
jeffreywang88 merged commit 9be0dbc into master Nov 19, 2026
6 checks passed
@jeffreywang88
jeffreywang88 deleted the serve-llm-kv-session-token-cache branch November 19, 2026 18:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants