Contents
Reading the charts. They are Datadog snapshots of production metrics. Datadog draws times in UTC; the captions give SGT (UTC+8). Each caption says which color is which region.
We serve a quantized Gemma 3 12B on Amazon SageMaker to read shopping receipts. A receipt’s OCR text goes in. A strict, schema-shaped JSON comes out: the header, payments, line items, discounts, and categories. Each receipt runs through a chain of six prompts, and every one of them uses structured output.
It started as a notebook in September 2026. By December it was serving production traffic in two AWS regions, at roughly 100,000 requests an hour at peak. This post covers each problem we hit, in the order we hit it, and what fixed it.
The short version
| When (2026) | Problem | Fix |
|---|---|---|
| Sep | Hugging Face transformers serving was slow and ran out of GPU memory |
INT8 W8A8 quantization, text tower only, served with vLLM in the SageMaker LMI container |
| Early Oct | Structured output failed inside the engine (424) |
Pinned container and vLLM versions; the client sends the JSON schema |
| 30 Oct | 100% of a burst failed with KeyError inside the rolling batch |
Upgraded the LMI image (vLLM 0.31) |
| 5 Nov | A streamed request looped forever and took the endpoint down for about 2 hours | Fixed the output formatter; rejected stream: true |
| 5–11 Nov | Structured decoding wrote whitespace until it hit max_tokens |
Engine-level disable_any_whitespace; gateway streaming bug fixed by a LiteLLM upgrade |
| 10 & 19 Nov | One over-length prompt left the engine broken for everyone | prompt_too_long guard before the batch, max_model_len 22,528, watchdog |
| 20–22 Nov | Real traffic arrived; requests timed out at SageMaker’s 60 s limit | Batch 8 → 32, autoscaling (capped by a quota of 2 GPUs) |
| 27 Nov | Prefix-aware routing overloaded one instance | Least-outstanding-requests routing |
| 27–30 Nov | Calendar-minute rate limits caused bursts; containers were killed | Diagnosed; now sizing with a concurrency target |
| 1 Dec | Singapore was out of GPU quota | Added a second region (Sydney), after an earlier capacity failure there |
| 1 Dec | Autoscaling target of 5 was far too low | Target of 32 in-flight requests per instance |
| 2 Dec | Throughput and the p99 tail were still the limit | n-gram speculative decoding: about 1.9× req/s, p99 roughly halved, same accuracy |
| 2 Dec → | Paying for a GPU through the quiet night | Scheduled shutdown and start of the Sydney endpoint |
Requests per hour. Dark blue is Singapore, light blue (stacked on top) is Sydney. From 26 to 30 Nov the Singapore curve has a flat top at about 40k/hour: that is the most two GPUs could take. After Sydney joined on 1 Dec, the total went past 100k/hour.
1. Getting a 12B model to serve at all (Sep – Oct)
Starting point. Gemma 3 12B instruct, loaded with transformers in a notebook on a T4 (16 GB). It ran out of memory, and when it did fit, generation was slow.
What we changed:
- Dropped the vision tower. We only read OCR text. Removing SigLIP and keeping
Gemma3ForCausalLMsaved memory and made the model simpler to quantize. - Quantized to INT8 W8A8 with
llm-compressor: weights per-channel and static, activations per-token and dynamic, andlm_headleft in full precision. The weights are about 12.8 GB. - Switched from
transformersto vLLM. Thetransformershandler un-quantized the weights in memory, so we paid for INT8 and still ran at bf16 cost. vLLM has real INT8 matmul kernels forcompressed-tensors. - Served it in the SageMaker LMI (DJL) container, with our own
model.pyhandler. The handler accepts OpenAI-style chat requests, applies the chat template, enforces a JSON schema through vLLM structured outputs (xgrammar), and strips code fences. - Hardware:
ml.g6e.xlarge, one NVIDIA L40S with 48 GB. After the weights, there is room for about 370k tokens of KV cache (fp8).
First lesson: pin everything. In early October the endpoint began failing with 424 without any change on our side. SageMaker had replaced the instance during maintenance, and the container came up with a different library snapshot, which had a serialization bug for structured-output parameters. Since then, the image is pinned by digest, and every build is a versioned package in the SageMaker Model Registry.
2. 30 Oct: a burst, then 100% failures
The receipt team sent its first real burst through our LiteLLM gateway. Every request failed.
Blue: requests. Orange: 4xx errors. From 16:08 SGT every request failed (105 of 105 in the window), even “say hi”.
Root cause. A race in the older LMI/vLLM rolling-batch code. vLLM returned output under a request ID that the LMI layer had already dropped, which raised KeyError inside the batch loop. Prefix caching, guided decoding, and five or more concurrent requests together made it likely.
Fix. Upgraded the container to LMI 0.38 with vLLM 0.31. No model or config change was needed. Replaying the burst at 48 req/min with concurrency 5 gave 48/48 successes.
Side lesson. The gateway retried each failure and then fell back to an alias of the same endpoint, so 6 failed requests became 48 invocations. A gateway fallback that points back at the same backend makes things worse.
3. 5 Nov: one streamed request, two hours down
What happened. A caller sent a request with stream: true, and the same container log line repeated 51,088 times. On the finished-token path, our output formatter never moved the stream cursor forward. DJL called it again and again, the engine thread starved, the worker died, and the orphaned engine process kept the GPU memory. SageMaker kept reporting the endpoint as InService, but it was down for about 2 hours.
Fix:
- One-line formatter fix (MP v19).
- Reject
stream: truewith a typed error (v20). Callers need the complete JSON anyway, so streaming gives them nothing. - A watchdog that restarts the worker on engine errors.
Lesson. None of our earlier load tests streamed. Test with the request shapes callers actually send.
4. 5–11 Nov: the whitespace trap
The symptom. A small share of calls ran until max_tokens and came back truncated. The output was valid JSON up to a point, followed by thousands of spaces.
The cause. Strict JSON-schema decoding can trap the model. If the grammar doesn’t allow the token the model wants (for example } while a required key is still missing), whitespace is still allowed, so the model keeps writing whitespace. At about 40 tokens/s, 3,000 tokens takes longer than SageMaker’s 60-second limit.
What didn’t work. We tightened the schemas one at a time: additionalProperties: false, maxLength, required keys, and temperature 0. Each patch closed one loophole and revealed the next.
What worked. disable_any_whitespace set at the engine level:
option.structured_outputs_config={"backend":"xgrammar","disable_any_whitespace":true}
A per-request flag was silently ignored in our version. After the change, our 20-receipt, 6-step test pack was clean: 135/135.
A second bug in the same week. Streamed responses through the gateway were cut off early and still reported a clean stop. That was a LiteLLM bug: SageMaker stream chunks were being split in the middle of a record. Upgrading the gateway to v1.109 fixed it.
5. One bad prompt breaks the engine for everyone (10 & 19 Nov)
What happened. A prompt longer than max_model_len was rejected by vLLM. The rejection also took down the other request being admitted in the same step, and after that the engine returned 424 to every request. Health checks still passed, because they only check that the server process is running.
Orange: 4xx. A 11,975-token prompt arrived at 13:33 SGT against an 8,192-token limit. About 50 minutes of failures followed, until a restart at 14:22 SGT.
Fix (MP v28–v30):
model.pycounts prompt tokens and rejects over-length prompts with a clearprompt_too_longerror before they reach the rolling batch.max_model_lenraised to 22,528. Our prompts average about 3.6k tokens, and the long tail is about 12k.- Every request logs its effective sampling parameters and prompt token count. This gave the calling team evidence that temperature and top-p reach the model.
- A watchdog that restarts the worker on engine errors but never on timeouts, and starts once per process.
6. 20–22 Nov: real traffic, and the 60-second wall
What happened. The calling team moved all receipt prompts onto our endpoint, about 4–6 req/s. A single GPU running a batch of 8 couldn’t keep up. Requests waited in the queue, and SageMaker’s 60-second limit for real-time invocations cut them off.
Red: requests that hit the 60 s limit, per hour. They start at about 16:00 SGT on 20 Nov at batch 8. The next day, on batch 32, traffic was higher still.
What we changed, and what it taught us:
max_rolling_batch_size8 → 32. Decode is limited by memory bandwidth, so a bigger batch gives much more throughput per GPU for little extra latency per token. KV cache was never the limit: at a 22.5k context we still fit about 16 full-length requests.- Autoscaling on in-flight requests (
ConcurrentRequestsPerModel). We had a quota of 2g6e.xlargeinstances in the region, so autoscaling couldn’t go above 2. The quota also means a blue/green deploy has to scale down to 1 first, so that the new fleet fits. - Why streaming and async inference don’t help here. A queued request has no first token yet, so streaming has nothing to send. Async endpoints can’t be called through our gateway path.
- A gateway retry multiplies a timeout. Each timed-out call is retried, which adds even more load to an endpoint that is already full.
Timeouts per day, both regions, including gateway retries. Peak in the week of 21–23 Nov, a second rise from 27 to 30 Nov (section 8), and close to zero from 2 Dec (section 11).
7. 27 Nov: cache-aware routing backfired
The idea. Every request in a chain step shares a long instruction prefix, and vLLM’s prefix cache already served about 75% of prompt tokens. SageMaker’s PREFIX_AWARE routing sends requests with the same prefix to the same instance, which should raise the hit rate further.
What happened. We set PrefixLength to 4096 bytes, which is inside the shared instructions. That meant each prompt type went to one instance. One type has max_tokens=5000 and produces long outputs, and all of it landed on the same instance.
Red: 60 s timeouts. Green: max in-flight requests. From about 09:30 SGT on 27 Nov one instance ran at about 34 s average latency with 640 timeouts in an hour, while the other ran at about 13 s with 1. The 11:00 SGT spike was the switch back, done during the day (see below).
Fix. LEAST_OUTSTANDING_REQUESTS routing. Both instances now carry even load, and the cache hit rate stayed at about 75%, because every instance quickly caches every prompt type.
Lessons:
- When request cost varies a lot by prompt type, prefix affinity becomes affinity by prompt type.
- Don’t deploy during the day with a quota of 2. The blue/green switch left one instance carrying all traffic for about 28 minutes, with up to 360 timeouts a minute and two container restarts. Since then we deploy at night, and scale back to 2 immediately after the switch.
8. The gateway’s rate limit made traffic bursty
LiteLLM’s rpm limit counts per calendar minute. When load is at the limit, held-back requests all go out together at second 0 of the next minute. The GPU then gets bursts instead of a steady stream.
Under those bursts, SageMaker’s /ping health check timed out on a full container, and SageMaker killed and restarted the container. In the logs this showed up as restarts on a 5-minute grid.
What we took from it:
- Size capacity from concurrency: in-flight requests per instance.
- Treat
rpmas a rough split between backends, not as a capacity limit. - The gateway’s
max_parallel_requestsis enforced per gateway pod, in memory, and returns429. It doesn’t cap total load on the backend.
Our planning figure: one GPU completes about 3.8 req/s at 32 in flight. Allowing for bursts, budget about 110 rpm per instance.
9. A second region
Singapore had 2 GPUs of quota and needed them for other work. Sydney had 10.
- 24 Nov: the first Sydney deploy waited 85 minutes and then failed with
InsufficientInstanceCapacity. We went back to Singapore only. - 1 Dec: a retry found capacity in about 6 minutes. Sydney went live with the same files as Singapore (MD5-identical), the same routing, and its own autoscaling.
- In the gateway, both regions are first-choice backends. Bedrock is second-choice, used for overflow and fallback.
Endpoint names include the region, so dashboards never mix the two.
10. Choosing the autoscaling target
Our first target was 5 in-flight requests per instance. With a batch of 32 that is far too low: the endpoint scaled out while the GPU was idle most of the time, and in Sydney (quota 10) it went to 5 instances. We also tried 64, but anything above the batch size of 32 just sits in the queue.
We settled on 32 per instance, which equals the batch size, with min 1 and max 2 in each region:
- Scale out when in-flight requests stay above 32 for 30 seconds.
- Scale in when they stay below 28.8 for 15 minutes.
Max in-flight requests per endpoint over a weekday. When it goes above 32, the endpoint scales out to a second instance.
11. Speculative decoding: the biggest single gain
Why. At a batch of 32 the GPU was close to 100% busy all day, and the latency tail was still near the 60 s limit. To serve more requests per GPU, we had to make each decode step produce more than one token.
What. vLLM n-gram speculative decoding. Extraction output copies a lot from its input (store names, item text, numbers), so we can guess the next few tokens by finding them in the prompt, with no draft model. The guesses are proposed on the CPU, and the GPU checks 4 of them per step. One line in serving.properties:
option.speculative_config={"method":"ngram","num_speculative_tokens":4,"prompt_lookup_max":4,"prompt_lookup_min":2}
Benchmark on temporary endpoints, 120 requests per run, concurrency 32:
| Baseline | n-gram spec decoding | |
|---|---|---|
| Requests/s | 1.98 – 2.21 | 3.76 – 3.83 |
| Output tokens/s | 443 | 842 |
| p99 latency | 34 – 38 s | 17.5 – 18.6 s |
| Accuracy (5 passes, about 2,230 checks each) | 94.94% | 94.99% (no measurable change) |
The engine logs showed 2.5–3.6 tokens accepted per step in production. We rolled it out to both regions at night on 2 Dec, with zero errors during the rollout.
GPU utilisation per endpoint. Singapore (purple) was at about 100% for all of 1 Dec. Two things happened next: Sydney (blue) took half the traffic from the evening of 1 Dec, and speculative decoding went live at about 03:00 SGT on 2 Dec. From 2 Dec the GPUs run at about 40–80% at the same traffic. The gap on 3 Dec SGT night is the night shutdown (section 12).
CPU, where 100% is one vCPU. The n-gram proposer runs on the CPU, so from the 2 Dec rollout CPU use doubles, from about 60% to about 120%. The work moved from the GPU to otherwise idle CPU.
Max model latency in seconds. Until 1 Dec it sits at the 60 s limit. After Sydney and speculative decoding, it peaks at 20–45 s.
Production latency, before and after (all requests, one day each):
| p50 | p90 | p99 | p99.9 | |
|---|---|---|---|---|
| Before | 6.3 s | 29.5 s | 52.3 s | 64.9 s |
| After | 5.5 s | 12.4 s | ~21 s | ~26 s |
Timeouts in the Singapore morning peak (08:00–10:00) went from 292 to 1.
12. Turning Sydney off at night
A real-time SageMaker endpoint can’t scale to 0 instances. At night our traffic is a small fraction of the daytime peak, and Singapore can take all of it.
What we built: two scheduled Airflow DAGs.
- 23:00 SGT: remove the autoscaling registration, then delete the Sydney endpoint. The endpoint config and the model stay.
- 04:00 SGT: deploy the same model package again. The endpoint is in service at about 04:15, before the morning ramp.
- Every day, including weekends.
Requests per 10 minutes. Sydney (blue) drops to zero at 23:00 SGT and is back at about 04:15 SGT. Singapore (purple) keeps serving the low night traffic.
One side effect still to fix. While Sydney is deleted, the gateway still tries it first, gets an error, and falls back to Bedrock. A short gateway cooldown for the Sydney backend would send that traffic to Singapore instead.
13. Is self-hosting worth it?
At our volume (about 3.6B input and 0.25B output tokens a day), Bedrock’s per-token price was lower than keeping enough always-on GPUs for the peak before speculative decoding. That would have been 14–16 instances at the busiest hour.
Self-hosting comes out ahead only if requests per GPU-hour go up: speculative decoding (about 1.9×), prefix caching (about 75% of prompt tokens are never recomputed), and not running GPUs at night. That is why most of the work above is throughput work, not model work.
What we would tell ourselves in September
- Pin the container by digest, and register every build as a versioned package. Instance maintenance will pick up whatever “latest” happens to be.
- Run load tests with the request shapes callers really send: streaming, over-length prompts, the slowest prompt type, and bursts.
- An endpoint shown as
InServicecan still fail every request. Alert on error rate, not on the endpoint status. - Check inputs before they reach the batch. One bad request must never break the engine for the others.
- Constrained decoding has its own failure modes. Disable free whitespace at the engine level.
- Size by concurrency, not rpm. Set the autoscaling target to the batch size.
- Prefix-aware routing pins prompt types to instances, and request cost varies a lot by type.
- Know your quota before planning a blue/green deploy, and deploy at night.
- For extraction work, try n-gram speculative decoding first. It is a one-line change with no draft model, and it nearly doubled our throughput.
- Gateway retries and fallbacks multiply load during an incident. Check what each fallback points to.