Length-Aware Batching: Checks Before LLM Deployment | Hokstad Consulting

Length-Aware Batching: Checks Before LLM Deployment

Length-Aware Batching: Checks Before LLM Deployment

Length-aware batching is ready for deployment only when token limits, queues, GPU memory and request deadlines pass tests together. Count the complete request, reserve space for its output, and test mixed request lengths at normal load and during bursts of two to three times that rate.

Before release, check that:

  • Every length bucket meets its latency targets without leaving long requests waiting indefinitely.
  • Timeouts and cancellations free scheduler slots and KV-cache memory within agreed limits.
  • GPU memory stays within tested limits, including when the cache fills.
  • Named owners approve the test records, and a timed rollback drill restores service within the agreed window.

Higher throughput is not a pass if requests miss latency targets, cancelled work holds resources, or rollback fails.

::: @figure Length-Aware Batching: Deployment Release Gates{Length-Aware Batching: Deployment Release Gates} :::

Continuous Batching: Optimize LLM Serving Throughput and Latency

Check Queue Controls and Request Deadlines

Once token budgets are set, check that the scheduler can admit work without starving long requests.

Assign release owners before deployment. The serving lead owns scheduler behaviour. The service owner owns user-facing admission and rejection policy, along with the timeout matrix. Both must approve the scheduler policy and timeout matrix. Block release until scheduler-control and request-lifecycle tests pass.[4][6][7]

Bound Queues and Prevent Bucket Starvation

Set global and per-bucket limits for queued requests, queued input/output tokens, active sequences, tokens per iteration, and maximum input and generation lengths. Document each scheduler limit’s scope, alert threshold and admission outcome: queue, reroute or reject. Use HTTP 503 for capacity rejection and HTTP 429 for rate limiting. Return a machine-readable reason, such as queue_full or deadline_would_be_missed. Reject requests when the remaining deadline cannot cover both queueing and execution.[4][5][10]

Test continuous admission and chunked prefill with bursts of long prompts, long generations and short requests. Then reverse the mix to check that long requests still make progress. Use reserved capacity, weighted scheduling or ageing to bound waiting time. Require approval of per-bucket queue-wait p95/p99, time to first token, completion latency, rejection rates and starvation alerts. Check that the full sequence fits in the KV cache - not just its first prefill chunk.[4]

The timeout matrix must match the scheduler policy for requests to receive their intended share of capacity. If queueing meets that requirement, the next gate is GPU memory headroom.

Align Timeouts and Release Cancelled Work

Publish a timeout matrix covering queue wait, time to first token, generation, stream idle timeout and total duration. Pass the original deadline through clients, gateways, schedulers and model servers. Downstream timeouts must fit within the remaining budget. An idle timer detects stalled progress, but occasional tokens must not keep it running indefinitely. It must never extend the absolute total deadline. Record which layer enforces each timer.[7][10]

Test client cancellation during queueing and decoding, disconnection immediately after the first token, gateway timeout, model-server shutdown and process termination. Measure how long cancellation takes to release scheduler slots and KV cache. Require the service owner to approve test results showing that resources are released within agreed limits after cancellation. Retries must keep the original deadline, use bounded attempts with jittered exponential back-off, and apply only to retryable failures. Block release if cancelled work still holds resources or retries inflate the queue.[6][8][9][10]

Cancelled work must also release memory cleanly.

Check GPU Memory Headroom and KV-Cache Limits

Once queue release is verified, measure GPU memory headroom under live batching - not just model size. Record weights, activations, temporary runtime buffers, communication buffers, CUDA graph allocations, allocator fragmentation and KV-cache separately. Measure allocated and reserved memory after loading, initialisation, graph capture and warm-up, then during concurrent mixed workloads. Convert cache capacity into usable blocks or tokens based on the model’s layers, attention or key-value heads, cache precision, tensor-parallel layout, sequence length, generated-token limit and concurrent request count.[5][11][15]

Maintain a table of configured and tested limits for every serving configuration. Include the model, quantisation, GPU model and count, runtime and driver versions, batching policy and cache settings. The rows below describe tests to run, not measured results. Record the actual configured and achieved limits, peak allocated and reserved memory, minimum free memory, peak cache occupancy and pass/fail evidence.[5][11][15]

Workload Configured limits to record Joint test to record
Concurrent long requests Input/output limits, concurrency, batched-token budget, KV-cache blocks 32 requests, each with 8,000 input and 1,000 generated tokens[11][15]
Mixed lengths Per-bucket limits and total active-token budget 70% of requests at 256/128 input/output tokens; 25% at 4,000/1,000; 5% at 16,000/2,000[11]
Uneven bucket demand Long-bucket concurrency and KV-cache ceiling Simultaneous long-request arrivals, followed by demand beyond cache capacity[11]

Limits tested separately may not be safe together. Test context length, output allowance, concurrency and token budgets in combination. Reduce admission limits if that combination breaches approved headroom. Repeat cold-start and warm-cache tests after changes to weights, quantisation, precision, runtime, CUDA libraries, graph capture, batching or sequence limits. For warm tests, populate reusable prefixes where supported, fill and partially drain the cache, then submit new long and mixed-length requests. Cached prefixes still use memory.[5][12][13]

Once headroom is mapped, test cache exhaustion under uneven demand in staging. Push active-token demand to the cache limit, then submit one extra request or a longer sequence. Check that there are no uncontrolled GPU out-of-memory failures, existing requests remain intact, rejected requests return a bounded error, memory use plateaus and the service recovers as demand falls. Record allocation failures, evictions, cancellation behaviour and latency. If offload is enabled, also measure CPU memory and transfer latency.[11]

Require infrastructure-lead sign-off on reserved headroom and exhaustion behaviour. Approval must specify the measured, configuration-specific reserved headroom percentage, maximum permitted memory peak, allocation latency limit, active-token ceiling, concurrent-long-request limit, cache allocation policy, offload policy where applicable, co-tenancy assumptions and exhaustion response. Attach memory timelines, cache-occupancy graphs, workload definitions, runtime and driver versions, GPU model, precision, failure logs and recovery results.[5][11][14][15] Block release unless headroom has been measured and rollback to the previous memory baseline has been tested.

Load-Test Mixed Lengths and Uneven Bucket Demand

With token, queue and memory limits set, test the scheduler under mixed demand. Build replayable workloads from request metadata only. Preserve input/output length, priority, tenant or endpoint, streaming mode and cancellation rate. Use approved synthetic or irreversibly de-identified text, and record the seed, length profile, workload ID, tokeniser version and arrival schedule.[17][19]

Keep hardware, model, precision, batch limits and scheduler policy unchanged. Traffic shape should be the only variable.

Drive load by arrival rate, not concurrency alone. A client that waits for each response can slow its own traffic and hide queue growth. Test below, near and above sustainable capacity: run normal demand for 10 minutes, add a 30–60-second burst at two to three times that rate, and test sustained overload.[16][18]

These runs should expose starvation, queue growth and uneven service across buckets under the same approved limits. Use the matrix below to plan tests and record results. For every row, attach the workload version, traffic mix, input/output length ranges, offered arrival rate, burst multiplier and duration, scheduler and bucket settings, queue limits, memory-headroom target and release criteria. Each row must produce a pass/fail decision against the previously approved queue and memory limits.

Traffic profile Offered load Thresholds to set before testing Observed results and decision to record
Separate short, medium and long runs Below and near capacity Per-bucket p95/p99 limits; minimum sample counts Baseline latency and throughput
Production-like mixed lengths 50%, 75%, 90%, 100% and 120% of reference capacity Latency limits, queue bounds and headroom floor Per-bucket latency, peak queue, minimum headroom and shedding
70–90% demand in each bucket, in turn Near capacity and overload Fairness, low-volume bucket latency and recovery limits Bucket sample counts, waiting times, throughput and recovery
Burst plus cancellations Two to three times baseline, then normal Clean-up deadline and recovery limit Queue entries, scheduler slots and KV-cache blocks released; errors and latency recovery

Measure offered, admitted and completed rates separately. Report per-bucket p50/p95/p99 for queue wait, time to first token and end-to-end latency.[16][20] Record inter-token latency, errors, cancellations and sample counts too. Extend runs if low-volume buckets lack enough samples for p99.

During overload, check that shedding matches the documented behaviour. Cancel work while queued, during prefill and during decoding, then measure how long resources take to release.

Define recovery using queue depth, memory use, errors and per-bucket latency. Require queue depth to fall below 10% of its limit within five minutes, no cancelled work left holding resources, and latency within SLO for three consecutive windows. Reject throughput gains that breach any bucket’s latency limit or hide starvation. Conditional results need a named owner for remediation and a retest. Require performance-lead approval of the completed matrix and raw evidence before deployment release.

Conclusion: Enforce Release Gates and Test Rollback

Once the load tests pass, close the release with a signed gate record covering token-count accuracy, queue saturation, timeout and cancellation behaviour, GPU memory headroom, and per-bucket latency and error rates. For each gate, record the threshold, observed result, evidence artefact, approver and approval date.[21][22]

Store versioned evidence alongside the model, serving-engine and tokeniser versions and the configuration checksum. Keep batching, queue, timeout and memory settings versioned and reversible. Name a primary rollback authority and a backup, and use the same mixed-length and uneven-bucket patterns in the rollback drill.

Run a timed rollback drill under active traffic, including cancellations. Measure detection, authorisation, cutover, queue drain and recovery to approved latency and memory levels. Set the recovery window before the drill, then repeat the drill after major serving, infrastructure or routing changes.

Keep dashboards and alerts live after deployment. After a rollback, record the cause and obtain new approval before redeployment. Block release if any critical gate fails, evidence is missing, or rollback exceeds the recovery window.

FAQs

How do I count tokens for chat templates and tool calls?

Count tokens with your chosen model’s token-counting method, not estimates. Before every model call, count the full request: system instructions, all conversation turns, tool definitions and retrieved content. Include chat-template formatting in the input allowance.

Keep an append-only token ledger for the full run, including retries and sub-agent calls, to stay within your token and budget caps.

How should I choose length buckets for my workload?

Use a token-aware scheduler instead of counting requests. Measure 95th-percentile token usage across representative tasks, then set capacity caps above that baseline. This leaves room for longer, valid responses without allocating too much capacity.

For agent-based workloads, reserve 10% to 20% of the total token budget for final completions, including last-step input context and validation. Reconcile those reservations with actual usage to free up unused capacity and maintain throughput.

How much GPU memory headroom should I reserve?

Size GPU memory for peak load, with separate reserves for bursts and failures. Base capacity on tested peak throughput that meets your latency targets.

For a 75% utilisation limit, divide demand by 0.75 once - unless usable capacity already includes that margin. Check that the capacity left after a failure can meet demand under your agreed failure target, such as the loss of an instance or zone. Keep normal utilisation headroom separate from the failure reserve so you don’t count spare capacity twice. [1][2][3]

Need help with your DevOps, cloud or AI plans?

Hokstad Consulting helps companies with DevOps transformation, cloud architecture and hands-on AI development — pragmatic consulting with measurable results.

Our services: DevOps on Retainer · Hosting & Cloud · AI Development & Strategy