Skip to content

[Bug] Fix tokenizer pool failures and double tokenization in prefix-cache routing - #3035

Merged
varungup90 merged 5 commits into
vllm-project:mainfrom
theminjunchoi:perf/prefix-cache-tokenize-once
Oct 13, 2026
Merged

varungup90 merged 5 commits into
vllm-project:mainfrom
theminjunchoi:perf/prefix-cache-tokenize-once

Conversation

@theminjunchoi

@theminjunchoi theminjunchoi commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request Description

Fixes the four tokenizer problems in prefix-cache routing from #3034. Blended routing gets about 42% faster, and there are no config, API or metric changes.

Changes (one commit each)

  1. KV sync tokenizes chat requests the same way everywhere.
    ScoreAll and PostRouteUpdate now use the same helper as Route: chat template first, plain text as the fallback. Their tokens now match the engine's KV events.
  2. Each request is tokenized once.
    The tokens are cached on RoutingContext (PrefixTokens, cleared on reset) and shared by ScoreAll, Route and PostRouteUpdate. Only successful results are cached.
  3. Health probes run without the pool lock.
    performHealthCheck copies the entries under a read lock and probes them unlocked. It writes back only if the entry is still in the pool.
  4. The pool follows the ready pods.
    An entry found through pod discovery remembers its pod IP. If that IP is no longer among the ready pods, GetTokenizer creates a tokenizer on a ready pod right away. ModelServiceMap entries are unaffected.

Results

Blended routing time, main vs this PR (n=8, prefix-cache scorer, two pods):

Tokenizer / prompt main this PR
tiktoken, ~1K words 1.72ms 0.99ms −42%
tiktoken, ~4K words 6.83ms 4.00ms −41%
tiktoken, ~16K words 29.8ms 17.1ms −43%
remote (2ms /tokenize, 4K tokens) 6.85ms 4.02ms −41%

Memory per request drops 48% and allocations drop 50%. Remote /tokenize calls go from 2 to 1 per request.

benchstat output
                       │     main      │            this PR                 │
                       │    sec/op     │   sec/op     vs base               │
BlendedTiktoken/1k-12    1716.1µ ±  3%   991.8µ ± 3%  -42.21% (p=0.000 n=8)
BlendedTiktoken/4k-12     6.828m ±  6%   3.995m ± 2%  -41.49% (p=0.000 n=8)
BlendedTiktoken/16k-12    29.78m ±  2%   17.06m ± 3%  -42.70% (p=0.000 n=8)
BlendedRemote-12          6.845m ± 16%   4.016m ± 1%  -41.33% (p=0.000 n=8)

                       │     B/op      │     B/op      vs base               │
geomean                   2.774Mi        1.431Mi       -48.40%

                       │   allocs/op   │  allocs/op   vs base               │
geomean                    36.64k        18.37k       -49.87%

BlendedRemote: tokenize_calls/op 2 → 1

The other cases from the issue:

Case main this PR
KV sync: ScoreAll after Route on the same chat request [0 0] [100 0]
GetTokenizer while another model's probe hangs 4.9s 38µs
Route after the pinned pod is deleted 503 every request routes normally

Tests

Test Checks Fails on main
TestKVSyncPrefixCacheTokenizesChatRequestsLikeRoute Route, PostRouteUpdate and ScoreAll all use chat-template tokens yes
TestBlendedPrefixCacheRouteTokenizesOnce one /tokenize call per blended request (local index and KV sync) yes
TestTokenizerPoolHealthCheckDoesNotBlockLookups GetTokenizer returns while another probe is blocked yes
TestTokenizerPoolMovesOffAPodThatLeft the tokenizer moves to the remaining pod n/a (new return value)

go test -race ./pkg/plugins/... ./pkg/types/... ./pkg/utils/... and golangci-lint run (v2.13.1) on the changed packages pass.

Related Issues

Resolves: #3034

Route renders chat requests through the chat template so the hashes match the blocks vLLM reports in KV events, but ScoreAll and PostRouteUpdate tokenized the plain prompt text. In a blended strategy the prefix score never matched the engine's cache, and the post-route update indexed hashes no request would look up.

Signed-off-by: MinJun Choi <[email protected]>
A blended strategy scores pods with ScoreAll and then calls PostRouteUpdate on the winner, and both tokenized the prompt. With a remote tokenizer that was two round trips to vLLM per request, and with tiktoken it added about 70% to the routing time. The tokens are now kept on the routing context for the rest of the request.

Signed-off-by: MinJun Choi <[email protected]>
performHealthCheck held the pool's write lock while it called each remote tokenizer, with a 5s timeout per model. GetTokenizer takes the same lock on every prefix-cache request, so a single slow vLLM endpoint stalled routing for all models until the probes finished.

Signed-off-by: MinJun Choi <[email protected]>
A tokenizer found through pod discovery stays pinned to that pod's IP. After the pod was deleted in a rollout or scale-down, every prefix-cache request still called it, failed after the client retries, and returned 503 until the next health check marked it unhealthy (30s by default). GetTokenizer now replaces the tokenizer as soon as its pod is missing from the ready pods it is given. ModelServiceMap endpoints are unaffected.

Signed-off-by: MinJun Choi <[email protected]>
@theminjunchoi theminjunchoi changed the title [Bug] Fix the tokenizer hot path in prefix-cache routing [Bug] Fix tokenizer pool failures and double tokenization in prefix-cache routing Oct 13, 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 optimizes prefix tokenization and tokenizer management. It introduces caching for prefix tokens in RoutingContext to avoid redundant tokenization calls, and refactors TokenizerPool to track pod IPs so it can dynamically migrate away from terminated pods. Additionally, the tokenizer health checker is updated to run probes without holding the main lock, preventing unresponsive endpoints from blocking lookups. Feedback on the changes suggests using a value receiver instead of a pointer receiver for the new tokenize method on prefixCacheRouter to maintain consistency with other routing methods.

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

Reviewed the diff and ran go test -race ./pkg/plugins/gateway/algorithms/ ./pkg/types/ on the PR head (both pass). I found no blocking bugs.

  • Chat tokenization in KV sync: kvSyncPrefixCacheRouter.tokenize is now the single place that applies the chat template first and falls back to plain text, and Route, ScoreAll and PostRouteUpdate all go through it, so the hashes they use match the engine's KV events. The nil-tokenizer error is raised inside the closure, so it is not cached.
  • Tokenize once: cachedPrefixTokens stores only successful results on the RoutingContext, and reset clears them, so a pooled context cannot leak tokens into the next request.
  • Health checks: performHealthCheck snapshots the entries under a read lock, probes without any lock, and writes the result back only if the same entry is still in the pool, so a replaced or removed entry is not resurrected. The log and counter for a healthy-to-unhealthy transition are emitted outside the lock.
  • Moving off a departed pod: an entry found by pod discovery remembers its pod IP and is replaced when that IP is not among the ready pods; ModelServiceMap entries have no pod IP and are unaffected. Replacing an entry closes the old tokenizer, which only calls CloseIdleConnections() on its HTTP client, so requests still using it are not interrupted.

I read the code and did not run the benchmarks; the numbers in the description are the PR's own.

Overall: approve, with non-blocking notes.

  1. PrefixTokens() uses nil to mean "not cached", so a legitimately empty tokenization result (a nil slice) is tokenized again on the next call. That is harmless, but a separate "cached" flag would make the intent explicit.
  2. The pool entry is keyed by model but now validated against whichever pod list the caller passes. Today the prefix-cache routers pass the model's ready pods, so this is stable. If another caller ever passed a different subset for the same model (for example only prefill pods), the entry would be replaced back and forth, with a health probe and a tokenizer rebuild on the request path each time. A comment on GetTokenizer stating that the list must be the model's full ready set would guard against that.
  3. The health check now probes entries one after another, each with up to a 5-second timeout. That no longer blocks lookups, but with many models and several unhealthy endpoints one round can run longer than the check interval; probing in parallel, or skipping a round when the previous one is still running, would bound it.

Generated by Claude Code

An empty result was stored as nil, which reads as "not cached", so it was tokenized again. GetTokenizer also needs every ready pod of the model, or it replaces a pinned tokenizer that is still valid.

Signed-off-by: MinJun Choi <[email protected]>
@theminjunchoi

theminjunchoi commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for taking a close look!

Pushed 8227d92 for the first two. An empty tokenization now gets stored as an empty slice so it's cached like anything else, and the GetTokenizer comment now says callers have to pass all of the model's ready pods.

On the health check, rounds can't actually pile up. The checker runs on a single goroutine and time.Ticker drops ticks while it's busy, so a slow round just pushes the next one back. Probing was already sequential before this PR (it just held the lock the whole time), so I'd rather leave parallel probes for a follow-up if it ever shows up in practice.

@cursor

cursor Bot commented Oct 13, 2026

Copy link
Copy Markdown

Design simplification review

Verdict: Approve (nits / optional follow-ups only)

Head reviewed: 8227d927. Resolves #3034 with four focused fixes and no config, API, or metric surface changes.

What works well

  1. Request-scoped cache, not a new pool abstraction. cachedPrefixTokens + RoutingContext.prefixTokens (cleared in reset) is the right place to share tokens across ScoreAll → route → PostRouteUpdate on a blended path. No second tokenizer registry or request-keyed map.
  2. One KV-sync tokenize path. Pulling chat-template-first logic into kvSyncPrefixCacheRouter.tokenize removes the Route-only special case that made ScoreAll/PostRouteUpdate hash plain text. Intent stays clear: all three callers must use the same helper.
  3. usable(pods) on the entry. Pod-IP pinning + “still among ready pods?” is a small method instead of branching inside GetTokenizer / createOrUpdateTokenizer. ModelServiceMap entries (podIP == "") stay unaffected by design.
  4. Health check unlocks the right thing. Snapshot under RLock, probe unlocked, write back only if p.tokenizers[model] == entry. Fixes the cross-model stall without redesigning the pool or introducing a second lock hierarchy.

Optional follow-ups (non-blocking)

  1. Parallel / overlapping health probes — as noted in an earlier review and deferred by the author: single-goroutine + ticker drop already prevents pile-up; parallel probes only matter if many models with slow endpoints show up in practice.
  2. Gemini’s pointer vs value receiver on prefixCacheRouter.tokenize — getTokenizerForRequest was already a pointer helper called from value Route/ScoreAll/PostRouteUpdate; consistency with those helpers is fine either way.

Compatibility / scope

Additive PrefixTokens / SetPrefixTokens on RoutingContext; no CRD, env, or gateway contract changes. Docs not required for this bugfix.

Design: Approve.

@cursor

cursor Bot commented Oct 13, 2026

Copy link
Copy Markdown

Code review

Verdict: Approve (nits only; no merge blockers)

Head reviewed: 8227d927 (includes follow-ups for empty-token cache and GetTokenizer pod-list docs). Linked issue: #3034.

Correctness

  1. Chat KV sync alignment — Route, ScoreAll, and PostRouteUpdate all go through kvSyncPrefixCacheRouter.tokenize (chat template first, plain-text fallback). Nil tokenizer errors are raised inside the closure and are not cached. Matches the engine’s KV-event hashes.
  2. Tokenize once — cachedPrefixTokens stores successful results only; 8227d927 maps nil → []byte{} so an empty result is not re-tokenized; reset clears prefixTokens so pooled contexts cannot leak.
  3. Health check lock scope — probes run unlocked; write-back is skipped if the entry was replaced or removed; healthy→unhealthy log/counter stay outside the lock after the status update.
  4. Pod departure — discovery-backed entries record podIP; usable fails when that IP is absent from the caller’s ready list; replace path closes the old tokenizer. Service-map entries keep podIP == "" and are not churned by pod list changes. Comment on GetTokenizer correctly documents that callers must pass the model’s full ready set.

Tests / local checks

Nits (non-blocking)

  1. Pointer vs value receiver on prefixCacheRouter.tokenize (style only; see design comment).
  2. Sequential health probes with per-model 5s timeout remain a latency bound for the background checker only — fine to leave for a follow-up as the author described.

Code: Approve. Merge recommendation: Approve.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Prefix-cache routing tokenizes requests twice, scores KV sync on the wrong tokens, and stalls on the tokenizer pool

2 participants