Retrieval-Augmented GenerationRAGProduction RAG — API Performance, Concurrency & Cost

A batch of long-context requests exhausts GPU memory and delays interactive traffic. How would you separate workloads and manage admission control?

Question 284 of 284 · Updated

On this page

1. The production incident#

A RAG platform serves two workloads on the same LLM fleet:

  • Interactive: employees ask short questions and expect a first token within 800 ms, followed by a smooth stream.
  • Batch: an overnight job summarizes large document collections, evaluates retrieval quality, and processes prompts containing tens of thousands of tokens. Its completion deadline is measured in hours.

At 02:00, a backfill starts 240 long-context requests. The serving layer treats every request as equal and admits them into the same queue as interactive traffic. GPU memory climbs; KV-cache blocks become scarce; the inference scheduler repeatedly preempts and recomputes sequences. A few replicas hit CUDA out-of-memory errors and restart. Interactive p95 time-to-first-token rises from 650 ms to 6.4 seconds, streaming pauses become common, and retries add more load.

The immediate symptom is “GPU memory is full.” The actual design failure is unbounded competition for a finite, sequence-dependent memory pool. A request count limit alone cannot protect the service: one 32k-token prompt can consume far more cache than many short prompts.

The objective is to isolate workloads, admit work according to predicted resource demand, preserve interactive headroom, and let batch work make progress without monopolizing the fleet.

2. Understand what is consuming GPU memory#

Do not treat all GPU memory as KV cache. A serving replica's memory budget may include:

  • Model weights and quantization metadata.
  • Runtime, CUDA context, kernels, communication buffers, and graph-capture allocations.
  • KV cache for active and cached sequences.
  • Prefill activations and temporary attention/workspace tensors.
  • Multimodal encoder state, if applicable.
  • Allocator fragmentation and safety headroom.

For a conventional decoder with full attention and uniform dimensions, approximate raw KV-cache bytes as:

The factor 2 represents keys and values. Use KV heads—not query heads—when grouped-query attention is used. Actual serving capacity also depends on tensor parallelism, layer-specific attention, sliding-window or hybrid attention, cache dtype, block rounding, prefix sharing, and engine implementation. Use the engine's measured cache-block capacity as the operational source of truth; the formula is a sanity check, not an admission controller by itself.

Prefill creates KV state for prompt tokens. Decode adds state as output tokens are generated. Therefore, the prompt length alone is not the final reservation: a request with a 12k-token prompt and a 4k-token output allowance may need capacity for roughly 16k retained tokens, subject to model and engine semantics.

A request-count queue can therefore be dangerously misleading. Track tokens and estimated memory, not just requests.

3. Root-cause debugging: prove where capacity disappeared#

Build a timeline from gateway admission through queueing, prefill, decode, and completion. Correlate every event with request ID, workload class, model revision, replica, and a privacy-safe tenant identifier.

3.1 Inspect the workload mix#

  • Plot prompt-token and requested-output-token distributions by workload class: p50, p90, p95, p99, and maximum.
  • Count concurrent active sequences and queued sequences, not only HTTP requests per second.
  • Separate interactive chat, retrieval synthesis, offline evaluation, document summarization, and backfill traffic.
  • Check whether retries, fan-out, or agent loops multiply one user request into several model calls.
  • Inspect whether a RAG prompt unexpectedly includes entire documents, duplicated chunks, verbose tool output, or oversized conversation history.

3.2 Inspect memory and scheduler evidence#

  • Record GPU allocated and reserved memory, free memory, and non-framework allocations.
  • Inspect KV-cache blocks used/free, allocation failures, preemption count, recomputation count, and cache eviction.
  • Compare active sequences with the configured sequence limit and the scheduler's token budget.
  • Inspect prompt-token backlog and time spent waiting for a KV allocation.
  • Correlate OOMs with prefill bursts, large output reservations, model warmups, graph capture, or other processes sharing the device.
  • Distinguish a genuine capacity shortage from fragmentation, a leak, or an unexpectedly large workspace.

A high GPU-utilization number does not prove healthy serving. The GPU may be busy recomputing preempted requests while useful completed-request throughput falls.

3.3 Separate prefill pressure from decode pressure#

Prefill processes prompt tokens and can create a large initial KV allocation. Decode repeatedly advances active sequences and grows their KV state. Long prefill batches can also interfere with decode latency even before memory is exhausted.

Measure:

  • Time to first token (TTFT), including queue wait and prefill.
  • Inter-token latency (ITL/TPOT) for active streams.
  • Prefill tokens per second and decode tokens per second.
  • Time waiting for memory admission versus time executing on GPU.
  • KV-cache occupancy during prefill and as outputs grow.

If memory rises sharply when long prompts enter, investigate admission and prefill. If it rises gradually during long generations, investigate output limits, active sequence count, and decode retention. If it remains high after requests finish, investigate cache retention, prefix-cache policy, or a leak.

3.4 Test the incident hypothesis#

Replay the same traffic in four controlled runs: interactive only, batch only, mixed traffic without limits, and mixed traffic with proposed reservations. Hold model, hardware, request distribution, and arrival rate constant. Compare SLO-compliant goodput, memory peaks, preemption, OOM, and batch completion time. This identifies whether the failure is caused by shared admission, a single workload, or a separate runtime defect.

4. Engineering solution: isolate first, then share capacity deliberately#

4.1 Classify requests using trusted identity#

Assign workload class at the gateway or job orchestrator after authentication and authorization. Do not let an untrusted caller set priority=interactive and bypass controls.

A practical classification:

  • Interactive: user-facing, latency SLO, bounded prompt and output.
  • Nearline: user-visible but asynchronous, moderate deadline.
  • Batch: offline summarization, evaluation, re-indexing, and bulk synthesis.
  • Exceptional long-context: approved requests requiring a larger context envelope.

Carry the classification as authenticated metadata through retrieval, reranking, prompt assembly, model routing, and tracing. Enforce class-specific context and output limits at the gateway and again at the inference boundary.

4.2 Create separate queues and a protected interactive floor#

Use distinct bounded queues and explicit service objectives. Reserve a minimum share of model-serving capacity for interactive traffic. Batch can borrow idle interactive capacity, but it must yield when interactive demand approaches its reservation.

There are several isolation strengths:

  1. Separate logical queues on one engine: lowest operational cost, but memory remains shared. This is useful only when the engine supports reliable per-class scheduling and memory-aware admission.
  2. Separate model-server replicas or GPU pools: stronger blast-radius and memory isolation. Route batch to a dedicated pool; keep interactive replicas protected.
  3. Separate prefill and decode pools: useful at substantial scale when long prefills and active decode streams interfere. It adds KV transfer, networking, orchestration, and failure modes, so benchmark before adopting it.

A priority queue is not memory isolation. A high-priority interactive request can still fail if batch work has already consumed all KV blocks. Reserve capacity before admitting batch work; priority alone cannot recover memory already allocated to running sequences.

4.3 Admit by estimated token and memory demand#

For each candidate request, estimate its maximum retained sequence length:

reserved_tokens = prompt_tokens + max_new_tokens

Apply model-specific rules for truncation, sliding windows, multimodal tokens, and shared prefixes. Convert the estimate into cache blocks using the serving engine's block size and cache layout. Include a conservative safety factor for rounding, uncertainty, and runtime overhead.

Admission should consider all of the following:

  • The request's class and deadline.
  • Maximum context and output length for that class.
  • Current active and queued token reservations.
  • Available KV blocks after the interactive reserve and safety watermark.
  • Maximum active sequences and prefill-token budget.
  • Queue length and estimated queue wait.
  • Whether the request can complete before its deadline.

Do not admit based only on current free memory. A running sequence can grow during decode. Reserve for the allowed output or use a controlled incremental reservation mechanism that can guarantee capacity before accepting each growth step.

For a long request, choose one explicit policy: reject with a clear limit, queue in the batch lane, route to a long-context pool, or split the upstream RAG task into bounded independent work where semantics allow. Never silently truncate context if doing so changes answer correctness.

4.4 Bound both running and waiting work#

Use limits for:

  • Maximum prompt tokens per request.
  • Maximum output tokens per request.
  • Maximum active sequences per workload class.
  • Maximum aggregate queued prompt tokens.
  • Maximum queued requests and total reserved tokens.
  • Maximum batch prefill tokens per scheduler iteration.
  • Maximum time in queue and request deadline.

A queue is not extra capacity. If its estimated wait exceeds the request's deadline, reject or reschedule rather than allowing work to accumulate until every request times out together. Return retry guidance such as a bounded Retry-After only when retrying later is useful; clients must use jitter and a retry budget.

4.5 Use memory-aware inference scheduling#

On a compatible serving engine:

  • Enable continuous batching so completed sequences release slots promptly.
  • Use chunked prefill to divide very long prompts into smaller scheduler steps, allowing decode work to proceed between chunks.
  • Set a maximum batched-token budget and active-sequence limit based on measured SLOs and cache capacity.
  • Preserve a KV-cache watermark so new work is not admitted when only a dangerously small number of blocks remain.
  • Use full-sequence-length checks where supported; admitting only the first chunk can overcommit cache before the request finishes prefill.
  • Monitor preemption and recomputation. Frequent preemption is a symptom of over-admission, not a healthy scheduling strategy.
  • Consider prefix caching when repeated system prompts or document prefixes are identical and safe to share. Account for the cache's retained memory and tenant isolation requirements.

Chunked prefill is a scheduling aid, not a substitute for admission control. It can reduce iteration-level interference, but the complete request still needs enough KV capacity as it progresses.

4.6 Make batch work elastic but starvation-safe#

Give batch jobs a bounded concurrency budget and a maximum share of cache blocks. Permit borrowing only when the interactive reserve is not needed. When interactive pressure rises:

  1. Stop admitting new batch requests.
  2. Let already-running batch sequences finish if capacity allows.
  3. Cancel or pause only work that is explicitly checkpointable and safe to restart.
  4. Route new batch work to a queue or alternate pool.
  5. Resume batch admission after memory and latency remain healthy for a defined recovery window.

Do not assume arbitrary LLM generations can be paused and resumed cheaply. A cancelled sequence may lose its KV state and require recomputation. Use job-level checkpoints between documents or tasks, not imaginary token-level preemption guarantees.

4.7 Keep RAG context construction inside the budget#

Inference admission is the final guardrail. Prevent waste earlier:

  • Retrieve a bounded number of chunks and rerank before generation.
  • Deduplicate overlapping chunks and remove repeated source passages.
  • Apply per-document and total-context token budgets.
  • Avoid sending raw full documents when targeted excerpts suffice.
  • Cap conversation history and tool output.
  • Record prompt-token counts by stage so retrieval expansion is visible.

Preserve citations and evidence coverage when reducing context. A shorter prompt that omits the decisive source is not an acceptable optimization.

5. Beginner-friendly numerical example#

Assume one GPU has 80 GiB of memory. After model weights, runtime, communication buffers, and measured non-KV allocations, the serving engine reports 32 GiB available for KV cache. The team keeps a 4 GiB safety reserve, leaving 28 GiB as the schedulable cache budget.

For a hypothetical model, suppose measured cache use is approximately 128 KiB per retained token per sequence. This is an illustrative model-specific value, not a universal constant.

  • One 4,096-token sequence uses about 512 MiB.
  • One 8,192-token sequence uses about 1 GiB.
  • One 32,768-token sequence uses about 4 GiB.

The service reserves 70% of the 28 GiB schedulable budget for interactive traffic and 30% for batch:

  • Interactive budget: 19.6 GiB.
  • Batch budget: 8.4 GiB.

At a particular moment:

  • 24 interactive requests each reserve 4,096 tokens: 24 × 0.5 GiB = 12 GiB.
  • 2 interactive requests each reserve 8,192 tokens: 2 × 1 GiB = 2 GiB.
  • Interactive usage is 14 GiB, leaving 5.6 GiB within its allocation.
  • 2 batch requests each reserve 32,768 tokens: 2 × 4 GiB = 8 GiB.
  • Batch usage is 8 GiB, leaving 0.4 GiB within its allocation.

Now four more 32k batch prompts arrive. Each would need roughly 4 GiB. The admission controller does not launch them all simply because the GPU still has some physical free memory: the batch reservation is already nearly full. It queues or rejects them. Interactive requests retain their reserved 19.6 GiB capacity and do not get pushed out by the backfill.

If the team had used a single shared pool with no reservation, the four new batch prompts could compete for the same cache blocks needed by interactive requests. The scheduler might preempt existing sequences, recompute their prompts, increase latency, or fail allocations.

The arithmetic is intentionally simplified. Production sizing must use actual KV block measurements, output growth, parallelism, cache dtype, activation peaks, and runtime-specific memory accounting. The reserve is not a license to fill every byte: keep measured headroom for non-KV allocations and transient peaks.

6. Admission-control decision flow#

text Request arrives | Authenticate and assign trusted workload class | Validate prompt/output/context limits | Estimate full-sequence KV blocks and deadline | Is class-specific capacity available? | | Yes No | | Reserve capacity Is bounded queue viable? | | Run / schedule Yes -> enqueue with deadline | No -> reject / route elsewhere Release reservation on completion or cancellation | Update metrics and recalibrate estimates

Illustrative pseudocode:

```python def admit(req, state): cls = trusted_class(req.identity) prompt = count_model_tokens(req.prompt) output = enforce_output_cap(req.max_new_tokens, cls)

if prompt > cls.max_prompt_tokens: return reject(413, "prompt exceeds workload limit")

blocks = estimate_kv_blocks( model=req.model, prompt_tokens=prompt, output_tokens=output, cache_dtype=state.cache_dtype, block_size=state.block_size, )

if not deadline_is_feasible(req.deadline, state.queue[cls]): return reject(429, "deadline cannot be met")

if state.available_blocks[cls] >= blocks: state.reserve(cls, blocks) return enqueue_for_execution(req, cls, blocks)

if state.queue_can_accept(cls, blocks, req.deadline): return enqueue_bounded(req, cls, blocks, req.deadline)

return reject(429, "capacity unavailable; retry with backoff") ```

The production implementation must make reservation atomic across workers, handle cancellation and timeout exactly once, reconcile estimates with engine allocations, and release reservations on every terminal path. A gateway-side counter that is not coordinated with the serving fleet can over-admit under concurrency.

7. Trade-offs and failure modes#

  • Dedicated GPU pools: strongest isolation and predictable SLOs, but idle capacity may be stranded. Use when interactive reliability justifies the cost or workload shapes differ substantially.
  • Shared pool with reservations: improves utilization and permits borrowing, but needs accurate accounting, atomic admission, and careful recovery behavior.
  • Strict priority: protects urgent traffic but can starve batch indefinitely. Add minimum batch progress, aging, or reserved batch capacity.
  • Conservative memory estimates: reduce OOM risk but reject work earlier and lower utilization. Recalibrate from observed block allocation and high-percentile request growth.
  • Large queues: absorb short bursts but increase wait time and stale work. Bound by tokens, memory, and deadlines—not request count alone.
  • Chunked prefill: reduces long-prefill interference, but adds scheduling overhead and does not eliminate total KV demand.
  • Prefix caching: can save repeated computation and memory, but retained prefixes consume capacity; scope keys and cache visibility carefully across tenants.
  • Preemption: may preserve system liveness, but recomputation wastes GPU cycles and worsens tail latency. Treat rising preemption as an alert.
  • Prefill/decode disaggregation: can isolate compute phases, but KV transfer adds network bandwidth, latency, and operational complexity.

Never optimize raw GPU utilization as the only objective. Optimize completed, quality-valid requests that meet their workload-specific SLOs.

8. Monitoring and alerting#

Create workload-class dashboards and alerts for:

  • GPU memory allocated/reserved/free and non-KV headroom.
  • KV-cache blocks used, free, reserved, and retained by prefix cache.
  • Active sequences, queued sequences, queued prompt tokens, and estimated queued KV blocks.
  • Admission accept/reject/queue rates by reason and workload class.
  • OOMs, allocation failures, preemption and recomputation counts.
  • Interactive p50/p95/p99 TTFT and ITL/TPOT.
  • Batch queue wait, throughput, completion time, deadline misses, and starvation age.
  • Prompt/output token distributions and estimation error.
  • SLO-compliant goodput and cost per completed request.

Alert on leading indicators: batch reservation saturation, rapidly falling free KV blocks, rising preemption, and interactive queue wait. Waiting for an OOM alert means the guardrail failed too late.

Trace the request from retrieval through prompt construction to the inference engine. Record token counts and resource estimates, but do not log sensitive prompt contents by default.

9. Prevention checklist#

  • [ ] Classify interactive, nearline, batch, and exceptional long-context traffic using trusted identity.
  • [ ] Define separate SLOs, context limits, output limits, and queue deadlines per class.
  • [ ] Measure actual KV blocks per token and reserve for output growth and runtime peaks.
  • [ ] Keep a protected interactive capacity floor and a nonzero memory watermark.
  • [ ] Bound queues by tokens, estimated memory, requests, and maximum wait.
  • [ ] Use memory-aware admission before requests enter the GPU scheduler.
  • [ ] Enable and tune chunked prefill/continuous batching where supported; validate with realistic mixed traffic.
  • [ ] Monitor preemption, recomputation, OOM, KV-cache pressure, TTFT, and ITL.
  • [ ] Test batch bursts, long prompts, output growth, replica loss, and cancellation races.
  • [ ] Verify that every request releases its reservation on success, failure, timeout, and cancellation.
  • [ ] Keep batch work starvation-safe without allowing it to borrow protected interactive memory.
  • [ ] Re-run capacity tests after model, tokenizer, cache dtype, runtime, or prompt-template changes.

10. Key engineering principle#

Separate the queues, reserve the memory, and admit by estimated full-sequence demand—not by request count or current free VRAM alone. Interactive traffic needs a capacity guarantee; batch traffic needs a bounded, elastic lane. Chunked prefill and continuous batching improve scheduling, but only explicit admission control and memory isolation prevent a long-context burst from consuming the resources required by live users.

Related questions

Explore other topics:Large Language ModelsAI AgentsMLOps