[{"content":"A user sends a 50-token question to your LLM API. The GPU is free. Prefill should take 2ms. Instead, the user waits 56ms — because a 4,000-token RAG request arrived one millisecond earlier and locked the GPU for a monolithic prefill pass.\nTPS is not user experience. A leaderboard showing 4,000 tokens/second in aggregate tells you nothing about the 1% of users staring at a spinner. What users actually measure is two things: responsiveness — did the answer start immediately? — and smoothness — did the text flow, or did it freeze mid-sentence? Standard benchmarks use uniform request sizes, which means every request sees identical scheduling behaviour. P99 looks clean because variance is structurally zero. These are happy path benchmarks.\nReal production traffic is bimodal: a mix of short chat turns (50 tokens, instant reply expected) and long RAG queries (4,000 tokens, high compute required). When both hit the same endpoint, the GPU scheduler must juggle two incompatible contracts simultaneously. That juggling act is invisible in uniform benchmarks — and it is what this post quantifies.\nThis post reproduces that collision on an NVIDIA L40S using a bimodal workload I designed specifically to stress-test GPU scheduling. The results led to a vLLM contribution — a BimodalDataset benchmark that makes this trade-off measurable in CI.\nℹ️ Benchmark Environment GPU: NVIDIA L40S (48GB GDDR6) · Model: Llama-2-7b · Framework: vLLM · Workloads: Uniform (100% short) vs. Bimodal (80% short chat + 20% long RAG) · Code \u0026amp; PR: vllm-project/vllm#34146 Two Phases, Two Physics Every LLM request passes through two phases with radically different computational profiles. Understanding the physics of each is prerequisite to understanding why scheduling is hard.\nPrefill: The Burst The model reads the entire prompt at once to compute the initial Key-Value (KV) cache. This is a large matrix multiplication — $N_{\\text{tokens}} \\times D_{\\text{model}}$ — that is compute-bound. The GPU\u0026rsquo;s Streaming Multiprocessors (SMs) light up to near-100% utilisation. A 4,000-token prefill on an L40S takes ~40ms of uninterruptible compute.\nDecode: The Drip The model generates tokens one at a time, each requiring a small vector-matrix multiply — $1 \\times D_{\\text{model}}$ against the model weights. This is memory-bound: the compute cores sit mostly idle, waiting for data from HBM. Each decode step takes ~5–10ms but must happen frequently to maintain a smooth token stream.\nThe collision is structural: prefill wants to lock the GPU for a long burst of compute. Decode needs frequent, short access to keep streams alive. They cannot both be satisfied simultaneously.\nThe Convoy Effect: Short Requests Behind Long Ones In a real system, requests are batched — the scheduler groups multiple decode steps into a single forward pass to amortise memory bandwidth. But when a large prefill arrives, it blocks the batch.\nConsider two requests arriving nearly simultaneously:\nRequest A (chat): 50-token prompt. Prefill takes ~2ms. Request B (RAG): 4,000-token prompt. Prefill takes ~40ms. If B arrives first, A waits 40ms before its 2ms prefill can even start. This is Head-of-Line (HOL) blocking — the \u0026ldquo;convoy effect\u0026rdquo; from networking, replicated inside the GPU scheduler.\nA 50-token chat request waits 40ms for a 4,000-token RAG prefill to complete — a scheduling tax invisible in uniform benchmarks\nThis wait time is invisible in uniform benchmarks because all requests are the same size. There is no \u0026ldquo;short request stuck behind a long one\u0026rdquo; — the scenario cannot occur.\nBreaking the Benchmark: Bimodal Stress Test To reproduce the convoy effect under controlled conditions, I ran two workload patterns through vLLM on an L40S.\nUniform baseline: 100% short requests (50–100 tokens). The \u0026ldquo;happy path.\u0026rdquo;\nBimodal stress test: 80% short chat requests + 20% long RAG requests (2,000–4,000 tokens). This is closer to real production traffic.\nThe Results Metric Uniform Bimodal Impact Short P50 TTFT 13 ms 15 ms +11% Short P99 TTFT 18 ms 56 ms +216% Throughput (tok/s) 3,762 2,372 -37% The P50 barely moves — most short requests still arrive when the GPU is free. But the P99 explodes: 56ms vs 18ms. This is the 1-in-100 short request that landed behind a RAG prefill.\nThe gap between P50 and P99 in the bimodal row is the convoy effect, quantified:\nP50 (15ms): A short request that arrived when the GPU was between prefills. Processed instantly. P99 (56ms): A short request that arrived during a 4,000-token prefill. Waited ~40ms in the queue. That 40ms gap is a scheduling tax that exists in every production system serving mixed traffic. Uniform benchmarks structurally cannot detect it.\nThis is why I contributed a bimodal workload generator to vLLM — --dataset-name bimodal generates configurable mixes of short and long requests, making the convoy effect reproducible in CI benchmarks:\n1 2 3 4 # Bimodal workload benchmark (80% short chat + 20% long RAG) vllm bench serve --dataset-name bimodal --num-prompts 500 \\ --model Qwen/Qwen2.5-0.5B --request-rate 30 \\ --save-result --save-detailed --result-filename bimodal.json Chunked Prefill: The Industry Fix and Its Hidden Cost The standard solution to HOL blocking is chunked prefill: instead of processing a 4,000-token prompt in one atomic 40ms pass, the scheduler breaks it into chunks (e.g., 512 tokens each). Between chunks, it pauses and asks: does anyone else need to run?\n1 2 Atomic: [PREFILL 4000 ──────────────────] → [Short Request] Chunked: [Chunk 512] → [Short] → [Chunk 512] → [Short] → ... This eliminates gross HOL blocking. But my benchmarks revealed an inverse correlation that chunked prefill forces: improving responsiveness (TTFT) breaks smoothness (ITL).\nTTFT vs ITL: The Inverse Correlation I ran the bimodal benchmark (70/30 split) across three chunk sizes on the L40S. The results from my vLLM PR benchmarks show the trade-off precisely:\nMetric Chunk 512 Chunk 2048 Chunk 8192 TTFT ↓ improves with larger chunks Short P99 (ms) 99.1 77.7 66.3 Short P99/Median ratio 7.0× 5.3× 4.6× ITL ↑ degrades with larger chunks Short Max (ms) 8.7 18.7 54.6 Short % \u0026gt;10ms spike 0.0% 26.3% 26.6% Long % \u0026gt;10ms spike 0.0% 81.7% 81.1% As chunk size increases, TTFT tail shrinks and ITL spikes grow — the inverse correlation is structural, not tunable away\nThe numbers confirm it: lower TTFT tail → worse ITL stutters. There is no chunk size that wins on both.\nWhy the Trade-off Is Structural Consider three users competing for the GPU:\nBlue: An active user mid-stream, needing a decode token delivered every ~20ms to maintain a smooth stream. Red: A massive RAG request arriving with a 4,000-token prefill (~40ms of compute). Green: A new chat user pressing Enter just after Red arrives. |OH|: Overhead per chunk — kernel launch latency + memory swap between chunks. Large chunks (8192) — \u0026ldquo;Fast Start, Frozen Stream\u0026rdquo;:\nLarge chunks let Red\u0026rsquo;s prefill clear quickly — Green starts fast, but Blue\u0026rsquo;s stream freezes for the full 40ms prefill duration\nThe scheduler runs Red\u0026rsquo;s prefill in one solid block. Green gets a fast TTFT (the prefill clears quickly, no |OH| overhead), but Blue freezes — no decode tokens for ~40ms. The stream stutters visibly.\nSmall chunks (512) — \u0026ldquo;Smooth Stream, Slow Start\u0026rdquo;:\nSmall chunks interleave Red\u0026rsquo;s prefill with Blue\u0026rsquo;s decode tokens — Blue sees a smooth stream, but Green waits longer as |OH| accumulates across every chunk boundary\nThe scheduler slices Red\u0026rsquo;s prefill into small pieces, yielding to Blue between each chunk. Blue sees a smooth 8ms stream. But every slice adds |OH| (kernel launch + memory swap), so Red\u0026rsquo;s total prefill time stretches from 40ms to 50ms+. Green waits longer because the accumulated overhead delays Red\u0026rsquo;s completion.\n⚠️ The Core Insight Chunked prefill does not eliminate latency. It redistributes it. You can concentrate the pain into a single stutter (large chunks) or spread it as overhead that delays new arrivals (small chunks). There is no setting that avoids both. Choosing Your Compromise There is no free lunch in GPU scheduling. The bimodal experiments prove that optimising for every user simultaneously is not possible. The right chunk size depends on what you are building.\nFor Chatbots and Streaming UIs Optimise for: Stream smoothness (ITL)\nConfig: Small chunks (512)\nWhy: Users tolerate a slightly slower start (100ms TTFT) far more than they tolerate a stuttering, freezing stream. A chatbot that starts 30ms late but flows smoothly feels faster than one that starts instantly and then freezes for 50ms mid-sentence. Zero requests experience a \u0026gt;10ms ITL spike at chunk 512.\nFor APIs and Batch Processing Optimise for: Throughput and responsiveness (TTFT)\nConfig: Large chunks (4096+)\nWhy: There is no streaming UX to protect. Large chunks let heavy prefills clear the GPU quickly, minimising the total time any request occupies a sequence slot. The P99/Median TTFT ratio drops from 7.0× to 4.6× — a measurably more predictable API.\nObjective Chunk Size P99 TTFT Max ITL Best For Smooth streaming 512 99.1 ms (higher) 8.7 ms ✅ Chatbots, real-time UI Balanced 2048 77.7 ms 18.7 ms Mixed workloads Fast start / throughput 8192 66.3 ms ✅ 54.6 ms (stutter) APIs, batch processing Making It Measurable: The vLLM Contribution The reason this trade-off goes undetected is that standard benchmarks use uniform request distributions. To close that gap, I contributed a BimodalDataset to vLLM — a configurable mixed workload generator that ships directly in vLLM\u0026rsquo;s benchmarking suite.\nWith it, reproducing the convoy effect is a single flag:\n1 2 3 4 5 6 # 80% short chat + 20% long RAG (default) vllm bench serve --dataset-name bimodal --num-prompts 500 # Tunable ratio and token ranges vllm bench serve --dataset-name bimodal --bimodal-short-ratio 0.7 \\ --bimodal-long-input-min 2000 --bimodal-long-input-max 5000 This makes the TTFT-vs-ITL trade-off reproducible in CI. Chunked prefill configurations can now be tuned against workloads that actually resemble production traffic — not uniform benchmarks that structurally cannot expose the inverse correlation.\nConclusion Uniform benchmarks told us TTFT was 17ms. Bimodal production traffic revealed it was 56ms. And chunked prefill — the industry\u0026rsquo;s fix for HOL blocking — does not solve the problem. It forces a choice: fast starts or smooth streams, but not both.\nOptimal GPU scheduling is not about eliminating constraints. It is about choosing which constraint to violate — and making that choice deliberately, with data from workloads that actually resemble your production traffic.\nCode \u0026amp; PR: The bimodal benchmark dataset is available as vllm-project/vllm#34146. The full experiment code and results are linked in the PR description.\n","permalink":"https://pbpatre.github.io/deep-ml-systems/prefill-vs-decode-gpu-scheduling/","summary":"A 50-token chat question should prefill in 2 ms. In bimodal production traffic, P99 TTFT spikes to 56 ms — a 216% penalty from a single long RAG request arriving one millisecond earlier. This post measures what happens when two incompatible workloads share a GPU scheduler.","title":"Prefill vs Decode: The GPU Scheduling Trade-off in LLM Inference"},{"content":"Part 1 established that Python\u0026rsquo;s GIL turns what looks like a 7% preprocessing overhead into a hard throughput ceiling at production concurrency. The natural counter-argument: GPU inference time dwarfs CPU preprocessing time, so the bottleneck should not matter in practice.\nI tested that argument directly. Pushing vLLM and SGLang to saturation under realistic RAG workloads surfaced something more troubling than slowness: the metrics lie. nvidia-smi reports 95% GPU utilization while throughput stays flat and latency degrades 18×. I call this the Utilization Illusion — and it is a direct consequence of coupled Python preprocessing.\nThis post traces the illusion through three frameworks, then breaks it.\nℹ️ Benchmark Environment GPU: NVIDIA L40S · Frameworks: vLLM, SGLang · Model: Qwen2.5-0.5B-Instruct · Workload: 100-turn chat history (~2,500 tokens) · Concurrency: 20 users (interactive) vs. 400 users (saturation) · All experiment code on GitHub How vLLM and SGLang Handle Preprocessing Both frameworks adopt a just-in-time preprocessing model that places CPU-heavy work on the scheduler\u0026rsquo;s critical path. Understanding why requires tracing the request lifecycle in each.\nvLLM orchestrates requests via a centralized Python event loop. Before the scheduler can allocate memory pages (PagedAttention), it needs the exact token count — which forces it to run the tokenizer synchronously. In high-throughput scenarios, the main thread blocks on string processing, preventing it from effectively batching for the GPU.\nSGLang introduces Radix Attention to optimize multi-turn and RAG workloads. By modeling the KV cache as a Radix Tree, it can reuse attention computation from shared prefixes, theoretically reducing GPU work for repeated system prompts to near zero. The catch: to traverse the Radix Tree and find a cache hit, the system first needs the token sequence. Which means it must tokenize the raw prompt before it can check the cache. The GPU optimization is real; the preprocessing barrier upstream of it is completely intact.\nThis architectural constraint sets up the experiments that follow.\nThe Utilization Illusion: vLLM Under Saturation The first experiment targeted vLLM\u0026rsquo;s scheduler under realistic load. Each request carried 100 turns of chat history — representative of a RAG-augmented agent loop — and I measured what happened when concurrent users scaled from 20 to 400 (experiment code).\nScenario Concurrent Users Throughput (req/s) GPU Utilization P50 Latency Interactive 20 133.75 92.61% 150 ms Saturation 400 133.99 95.42% 2,745 ms A 20× increase in concurrent load. Throughput: flat. Latency: 18× worse. GPU utilization: went up.\nThis is the Utilization Illusion. The Python scheduler was so overwhelmed by Jinja2 templating and tokenization that it could only feed the GPU at ~134 req/s regardless of load. The GPU processed those requests quickly, then waited for the CPU to assemble the next batch — appearing busy while repeatedly idling. What nvidia-smi captures is duty cycle, not efficiency. The gap between duty cycle and Model FLOPS Utilization (MFU) is where the capacity disappeared.\nThe Radix Paradox: When GPU Optimization Cannot Reach the GPU The next experiment tested whether SGLang\u0026rsquo;s Radix Attention — a genuine GPU-side innovation — could break through the bottleneck. I compared two traffic patterns (experiment code):\nCache miss: Every request has a unique prompt history. Attention computed from scratch. Cache hit: All requests share a long common prefix (simulating a shared RAG system prompt). The Radix Tree reuses the KV cache — GPU work for that prefix drops to near zero. Load Concurrent Users Cache State Throughput (req/s) P50 Latency Low 20 Miss 115.10 164 ms Low 20 Hit 245.84 67 ms High 400 Miss 219.81 1,835 ms High 400 Hit 227.52 1,780 ms At low concurrency, Radix Attention works as advertised — a cache hit cuts latency by 60% (164 ms → 67 ms) and nearly doubles throughput. The CPU is not yet saturated, so the GPU savings propagate to the user.\nAt high concurrency, the benefit collapses. The difference between full GPU computation and near-zero GPU computation is 55 ms — less than 3% of total latency. A request with a 100% cache hit still spent 1.78 seconds waiting in the Python queue to be tokenized.\nThe mechanism is clear: SGLang cannot consult the Radix Tree until it has the token sequence. Tokenization happens on the CPU. At saturation, the upstream CPU queue completely masks the downstream GPU optimization. A 0 ms GPU computation cannot help if the CPU takes 2 seconds to prepare the input.\nBreaking the Coupling: Decoupled Preprocessing The pattern that breaks this bottleneck is architectural: move Jinja2 templating and tokenization out of the inference server and into a separate preprocessing gateway that delivers pre-tokenized data to the GPU worker.\nThis is the approach natively supported by NVIDIA Triton Inference Server via ensemble pipelines. To isolate the effect of decoupling alone, I built a simulated sidecar using two Rust-backed libraries that bypass CPython entirely for the heavy work (experiment code):\nminijinja — A Rust implementation of Jinja2, called from Python. Replaces CPython\u0026rsquo;s GIL-bound Jinja2 template rendering. HuggingFace Tokenizers — The same Rust-backed tokenizer from Part 1, which releases the GIL during execution. The sidecar process applies the chat template via minijinja, tokenizes the result, and sends the raw input_ids directly to SGLang\u0026rsquo;s /generate endpoint — completely bypassing the /v1/chat/completions endpoint that would trigger server-side Jinja2 + tokenization.\n1 2 3 4 5 6 7 8 9 10 11 12 13 # Sidecar: Rust-backed preprocessing (GIL-free) def sidecar_process(messages): # 1. Template with minijinja (Rust) instead of Jinja2 (Python) prompt_str = env.render_template(\u0026#34;chat\u0026#34;, system=messages[0][\u0026#34;content\u0026#34;], history=messages[1:] ) # 2. Tokenize with HF Tokenizers (Rust, releases GIL) input_ids = tokenizer.encode(prompt_str) return input_ids # Monolith: raw messages → /v1/chat/completions (server-side Jinja + tokenizer) # Sidecar: input_ids → /generate (GPU only, no preprocessing) Phase 1: The Base Tax First, I measured the raw per-request savings at moderate concurrency (50 users) with long contexts (~2,500 tokens) — before queuing effects compound the cost.\nArchitecture Concurrent Users Throughput (req/s) P50 Latency Monolith 50 118.44 379 ms Decoupled (sidecar) 50 178.58 212 ms Offloading preprocessing saves ~167 ms per request at moderate load — before any queuing dynamics. This is the base tax that every request pays in a monolithic setup.\nPhase 2: The Multiplier Effect At saturation (400 users), that 167 ms base saving has a nonlinear effect on total latency through Kingman\u0026rsquo;s formula: reducing service time at a bottleneck reduces queue depth super-linearly.\nArchitecture Concurrent Users Throughput (req/s) P50 Latency Speedup Monolith 400 178.58 1,997 ms — Decoupled (sidecar) 400 302.60 1,017 ms 1.96× Cross-experiment comparison: decoupled preprocessing vs monolith at 50 and 400 concurrent users\nThree results stand out:\nThroughput increased 70%. The GPU was finally receiving a steady stream of tokens rather than a drip feed assembled by an overwhelmed Python scheduler. Throughput jumped from ~178 req/s to 302 req/s. The monolith was leaving 40% of the GPU\u0026rsquo;s capacity on the table.\nLatency dropped by ~1 second at P50. The 167 ms base tax, compounded through queuing at 400 concurrent users, was responsible for nearly a full second of wait time. This is Kingman\u0026rsquo;s formula in action — small reductions in service time at a saturated bottleneck produce outsized reductions in queue length.\nA residual floor remains at ~1,017 ms. Even without tokenization, deserializing 400 large JSON payloads and managing TCP connections saturates the Uvicorn event loop. This ~1 second floor is the cost of Python\u0026rsquo;s HTTP stack itself — asyncio, Pydantic validation, and ASGI overhead. Breaking below it requires moving the entire networking layer to Rust or C++, which is a separate optimization.\nThree Principles from Saturation Testing Single-request profiling hides all three of these. They only surface when you push the system to saturation.\nUtilization metrics require interpretation. nvidia-smi reports duty cycle, not efficiency. A GPU that processes small batches and idles between them will show high utilization while delivering a fraction of its theoretical MFU. The right metric is throughput per dollar, not utilization percentage.\nGPU-side optimizations have a CPU-side prerequisite. Radix Attention, speculative decoding, and paged attention are real wins — but they operate downstream of preprocessing. At high concurrency, the CPU queue absorbs the gains before they reach the user. Optimizing the GPU without first clearing the CPU bottleneck compounds latency without improving throughput.\nDecoupling is an architectural decision, not a tuning knob. You cannot thread your way out of the GIL (Part 1 showed this), and you cannot cache your way past a saturated tokenizer (this post showed this). The fix requires structural separation: preprocessing as a dedicated layer — ideally Rust-backed — that delivers token IDs, and an inference server that consumes them.\nWhat\u0026rsquo;s Next The decoupled architecture removes the Python preprocessing bottleneck, but introduces new questions: how do you scale the preprocessing tier independently? What happens to latency when the gateway is remote? How does this interact with speculative decoding or prefix caching?\nThe next post will cover production deployment patterns for decoupled preprocessing — including the tradeoffs between in-process, sidecar, and remote gateway architectures.\nCode: All three experiments from this post — vLLM saturation (exp5), SGLang Radix (exp6), and decoupled sidecar (exp7) — are in the GitHub repository.\n","permalink":"https://pbpatre.github.io/deep-ml-systems/preprocessing-barrier-part-2/","summary":"\u003ccode\u003envidia-smi\u003c/code\u003e reads 95% GPU utilization while throughput stays flat and latency degrades 18×. This post investigates the Utilization Illusion — and shows how decoupling preprocessing recovered 40% of GPU capacity the monolithic architecture left on the table.","title":"The Preprocessing Barrier (Part 2): How Preprocessing Starves Your GPUs"},{"content":"Picture this: your H100s are sitting at 65% utilization under peak load. The model is fine. The network is fine. You add more threads — utilization barely moves. You dig into the profiler and find the culprit: a Jinja2 template loop. Python code so unassuming that nobody had thought to benchmark it.\nThis is not a hypothetical. It is a failure mode I set out to reproduce and quantify. Through four controlled benchmarks, I profile the preprocessing pipeline that every LLM inference server runs — templating, tokenization, and collation — and trace exactly how Python\u0026rsquo;s GIL converts what looks like a 7% overhead in single-request profiling into a hard throughput ceiling at production concurrency. The numbers are worth understanding before you hit them in production.\nAll benchmarks were run on a 12-core Apple M3 Pro. The full benchmarking suite is on GitHub.\nℹ️ Benchmark Environment CPU: Apple M3 Pro, 12 cores · Model: Llama-3.1-8B-Instruct · Tokenizer: HuggingFace Tokenizers (Rust) · Templating: Jinja2 · Framework: PyTorch 2.x The Three-Stage Pipeline Before a single float reaches the GPU, raw text must pass through three CPU-bound transformations. Each stage has a different runtime, a different scaling characteristic, and — crucially — a different relationship with Python\u0026rsquo;s GIL.\nTemplating → Tokenization → Collation: three stages, three runtimes, three bottleneck profiles\nStage 1: Templating (Python — GIL-bound) The server receives a list of JSON messages and compiles them into a single formatted string using a model-specific chat template (e.g., ChatML). The dominant implementation is Jinja2 — pure Python, fully GIL-bound.\nInput:\n1 2 3 4 [ {\u0026#34;role\u0026#34;: \u0026#34;system\u0026#34;, \u0026#34;content\u0026#34;: \u0026#34;You are a helpful assistant.\u0026#34;}, {\u0026#34;role\u0026#34;: \u0026#34;user\u0026#34;, \u0026#34;content\u0026#34;: \u0026#34;What is 2+2?\u0026#34;} ] Output:\n1 2 3 4 5 \u0026lt;|im_start|\u0026gt;system You are a helpful assistant.\u0026lt;|im_end|\u0026gt; \u0026lt;|im_start|\u0026gt;user What is 2+2?\u0026lt;|im_end|\u0026gt; \u0026lt;|im_start|\u0026gt;assistant Stage 2: Tokenization (Rust — GIL-free) The templated string is encoded into integer token IDs. The standard implementations — HuggingFace Tokenizers and tiktoken — are Rust-backed and release the GIL during execution, enabling true multi-threaded parallelism.\nInput: The formatted string above\nOutput:\n1 2 3 4 [128000, 128006, 9125, 128007, 271, 2675, 527, 264, 11190, 18328, 13, 128009, 128006, 882, 128007, 271, 3923, 374, 220, 10, 16, 30, 128009, 128006, 78191, 128007, 271] Stage 3: Collation (Python/C++ — partially GIL-bound) Token ID lists are converted into padded PyTorch tensors and pinned for GPU transfer. This stage involves both Python orchestration and C++ tensor operations.\nInput:\n1 2 3 4 [ [128000, ..., 10, 16, 30], # Request A (Short) [128000, ..., 99, 12, 11, ..., 88] # Request B (Long) ] Output:\n1 2 3 4 tensor([ [128000, ..., 10, 16, 30, 128001, 128001], # Padded [128000, ..., 99, 12, 11, ..., 88], # Full length ]) Baseline: A Single Request Looks Fast How expensive is this pipeline for a single request? To establish a baseline, I profiled one Llama-3.1-8B-Instruct request at ~1,000 tokens (experiment code).\nStage Latency Share Tokenization (Rust) 0.82 ms 68% Collation (PyTorch) 0.30 ms 25% Templating (Jinja) 0.08 ms 7% Total ~1.2 ms 100% At 1.2 ms total, it\u0026rsquo;s easy to dismiss preprocessing as negligible — and most teams do. The Rust-based tokenizer handles the bulk of the work efficiently, and Jinja\u0026rsquo;s 0.08 ms contribution barely registers.\nThis is precisely the reasoning that breaks down at scale.\nStructure Matters More Than Content Real-world LLM usage is rarely single-turn. RAG pipelines, multi-turn agent loops, and tool-calling workflows generate requests with dozens or hundreds of message turns.\nThe question: does the structure of a request (number of messages) affect preprocessing cost differently than the content (number of tokens)? To test this, I held the total token count constant at ~100k tokens and varied the number of conversation turns (experiment code).\nTurns Jinja Latency Tokenization Latency Jinja Scaling 1 turn 0.07 ms 56.5 ms 1× 100 turns 0.37 ms 58.7 ms ~5× Slower Jinja templating latency scales with message count (structure), not token count (content)\nTokenization cost scales with content — the number of tokens to encode. Templating cost scales with structure — the number of messages to iterate over in the Jinja template loop. As applications grow more complex (more turns, more RAG chunks, more tool calls), the Python-based templating layer compounds linearly while the Rust tokenizer stays flat.\nThis asymmetry is invisible in single-request benchmarks.\nAt Production Concurrency, the GPU Starves The real bottleneck emerges when the inference server processes batches. Production systems batch 64, 128, or 256 requests per forward pass to saturate GPU memory bandwidth. During batch preparation, the GPU waits.\nI simulated a high-throughput server processing 100,000 requests in batches of 64, and measured the per-batch GPU wait time — the wall-clock time the GPU sits idle while the CPU assembles each batch — across different thread counts (experiment code).\nThreads GPU Wait Time (per batch) Tokenization Jinja 1 thread 456 ms 409 ms 18.6 ms 4 threads 298 ms 248 ms 19.1 ms 16 threads 178 ms 126 ms 20.8 ms 64 threads 134 ms 83 ms 22.3 ms At 64 threads, Jinja templating accounts for 16.6% of total GPU wait time — and is still growing\nThe Rust-based tokenization scales as expected — ~5× speedup (409 ms → 83 ms) by distributing work across cores.\nJinja templating, however, gets slower (18 ms → 22 ms).\nAt 64 threads, the \u0026ldquo;trivial\u0026rdquo; 7% from our baseline now accounts for 16.6% of total GPU wait time. In a system processing thousands of requests per second, this 22 ms per batch becomes a hard ceiling that no amount of GPU optimization can overcome.\nThe Root Cause: Python\u0026rsquo;s GIL Why does adding threads make Jinja slower? To isolate the mechanism, I measured the speedup factor of each component against ideal linear scaling as thread counts increased (experiment code).\nComponent Speedup at 32 Threads Mechanism Tokenization (Rust) 5.72× Releases the GIL — true parallelism Templating (Jinja) 0.84× GIL-bound — actually gets slower Tokenization scales near-linearly with threads. Templating degrades — threads contend for the same GIL lock.\nJinja2 is a pure Python library. Under CPython\u0026rsquo;s GIL, only one thread can execute Python bytecode at a time. When 64 threads attempt concurrent Jinja rendering, they don\u0026rsquo;t run in parallel — they serialize on the GIL and pay additional context-switching overhead. More threads, less throughput.\n⚠️ The GIL Tax Under the GIL, a 12-core CPU is effectively a single-core machine for the templating phase. Every thread added beyond the first increases contention without increasing throughput. Implications Single-request profiling is a trap. The numbers look fine — 1.2 ms total, 0.08 ms for templating — until you model what happens at batch concurrency. Three things become clear:\nCPU preprocessing is not free. When GPU utilization plateaus at 60–70%, the instinct is to look at model architecture, batch sizes, or memory layout. But the GPU may simply be starving for tensors — blocked on CPU-side preprocessing that hasn\u0026rsquo;t been profiled.\nThe community solved half the problem. Rewriting tokenizers in Rust was a massive win — it moved the heaviest preprocessing stage out of the GIL. But the shift to chat-based models introduced Jinja templating as a new serial bottleneck, and that work hasn\u0026rsquo;t received the same attention.\nConcurrency patterns matter as much as algorithms. The difference between a GIL-releasing Rust function and a GIL-bound Python function is invisible at low concurrency and catastrophic at high concurrency. Serving infrastructure must use patterns (multiprocessing, C++ backends, or dedicated preprocessing workers) that can actually saturate available cores.\nWhat\u0026rsquo;s Next Identifying the bottleneck is step one. In the next post, we push vLLM and SGLang to saturation to see what happens when this preprocessing bottleneck meets real GPU serving systems:\nThe Utilization Illusion — Why nvidia-smi shows 95% utilization while throughput stays flat The Radix Paradox — Why SGLang\u0026rsquo;s KV cache optimization cannot reach the GPU at high concurrency Decoupled Preprocessing — What happens when you move Jinja and tokenization out of the inference server entirely Code: The full benchmarking suite — all four experiments, data collection, and plotting scripts — is available on GitHub.\n","permalink":"https://pbpatre.github.io/deep-ml-systems/preprocessing-barrier-in-llms/","summary":"A Jinja2 template loop takes 7% of single-request latency. At production concurrency, it becomes the throughput ceiling. This post traces how Python\u0026rsquo;s GIL converts an innocent-looking preprocessing step into a hard scaling wall.","title":"The Preprocessing Barrier in LLM Inference"},{"content":"I\u0026rsquo;m a Principal ML Systems Engineer at Atlassian, working on the infrastructure that powers AI features across Jira, Confluence, and Atlassian Intelligence.\nI write about LLM production systems and ML engineering — the hard-won lessons from deploying AI at scale.\nLinks\nGitHub: github.com/pbpatre LinkedIn: linkedin.com/in/pratik-patre Twitter / X: @pp_patre ","permalink":"https://pbpatre.github.io/about/","summary":"About Pratik Patre","title":"About"}]