← Jagesh Maharjan (Jugs) All posts
30 November 2026Gemma 3 12B · vLLM · Amazon SageMaker

Self-hosting Gemma 3 12B for receipt extraction

Three months of fixes, in the order we hit them: quantization, structured-output traps, a two-hour outage, routing, a second region, and the one-line change that nearly doubled throughput.

1.9×requests/s from n-gram speculative decoding p9952 s → about 21 s in production 100krequests an hour at peak 2AWS regions, Singapore and Sydney
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

    Hourly requests by region, 15 Nov – 4 Dec 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:

    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.

    30 Oct incident 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:

    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.

    19 Nov over-length wedge 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):

    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.

    Timeouts, 20–21 Nov 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:

    Daily timeouts 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.

    Prefix-aware routing day 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:

    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:

    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.

    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:

    In-flight requests per endpoint 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 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 utilisation 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 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.

    Night shutdown 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

    1. Pin the container by digest, and register every build as a versioned package. Instance maintenance will pick up whatever “latest” happens to be.
    2. Run load tests with the request shapes callers really send: streaming, over-length prompts, the slowest prompt type, and bursts.
    3. An endpoint shown as InService can still fail every request. Alert on error rate, not on the endpoint status.
    4. Check inputs before they reach the batch. One bad request must never break the engine for the others.
    5. Constrained decoding has its own failure modes. Disable free whitespace at the engine level.
    6. Size by concurrency, not rpm. Set the autoscaling target to the batch size.
    7. Prefix-aware routing pins prompt types to instances, and request cost varies a lot by type.
    8. Know your quota before planning a blue/green deploy, and deploy at night.
    9. 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.
    10. Gateway retries and fallbacks multiply load during an incident. Check what each fallback points to.