Retrieval-Augmented GenerationRAGProduction RAG — API Performance, Concurrency & Cost
You have a strict two-second response-time budget. How would you allocate it dynamically across retrieval, reranking, and generation?
Question 280 of 284 · Updated
On this page
- Why static latency budgets fail
- Production incident
- Root-cause debugging
- Start with a hard end-to-end deadline
- Dynamic allocation: predict the work, then protect the deadline
- Worked allocation profiles
- Numerical example: adaptive policy under a two-second SLO
- Runtime safeguards and implementation pattern
- Quality guardrails: what must not be traded away
- Trade-offs and common mistakes
- Monitoring and prevention
- Prevention checklist
- Key takeaway
- Research references
Why static latency budgets fail#
A two-second response objective is an end-to-end constraint, not a collection of independent timeout settings. Retrieval, reranking, and generation compete for the same finite time. Giving every stage a fixed maximum can waste time on easy queries, starve difficult queries of useful evidence, or leave too little time for generation.
The goal is to allocate the remaining budget according to the request's needs and the system's current state, while preserving a hard deadline. This is different from #278's fan-out critical-path diagnosis and #279's dependency timeout and partial-result handling. Here the central engineering problem is deciding, during a request, how much time and compute each stage deserves.
Production incident#
A knowledge assistant promises a response within two seconds for 95% of requests. The team configures retrieval for 500 ms, reranking for 500 ms, and generation for 1,000 ms. The stages run sequentially, but each timeout is treated as an independent allowance. Authentication, query embedding, prompt assembly, output validation, and network overhead are not included.
Under load, p95 becomes 2.7 seconds. Simple factual questions spend the full reranking allowance even when the initial ranking is already decisive. Complex multi-hop questions sometimes consume most of the retrieval budget and then enter generation with insufficient time to produce a complete answer. A queueing spike at the model endpoint makes the problem worse.
The first dashboard shows average retrieval latency is stable, so the team initially scales the vector database. A distributed trace reveals the actual causes: static per-stage allowances exceed the end-to-end objective; reranking work is not proportional to query difficulty; and generation queue time plus decode time were measured separately from the application timeout. The system has no concept of remaining request budget.
Root-cause debugging#
Instrument the request with one trace ID and record, for each stage:
- start/end timestamps and elapsed time;
- remaining end-to-end budget at stage entry and exit;
- queue wait separately from execution time;
- requested and actual candidate counts, reranker batch size, and prompt tokens;
- model time-to-first-token (TTFT), time per output token, and generated token count;
- whether a stage was skipped, shortened, cancelled, or completed;
- answer quality and evidence coverage for the resulting configuration.
Measure p50, p95, and p99 by query class and load level. Averages conceal tail behavior. For a parallel retrieval stage, measure the slowest required branch, not the average branch. Separate generation queue delay, prefill, and decode: a short prompt does not guarantee fast generation if the serving queue is saturated.
Replay representative requests with controlled stage caps. Compare retrieval recall, evidence coverage, reranker quality, grounded answer quality, TTFT, completion latency, and SLO compliance. This reveals whether a faster configuration is actually useful or merely returns a fast but unsupported answer.
Start with a hard end-to-end deadline#
Create a two-second deadline at ingress. Every stage consumes from the same clock. Before starting work, reserve time for operations that must still happen: response serialization, mandatory safety checks, and network delivery. Use a monotonic clock for elapsed-time measurement.
An illustrative fixed baseline might be:
- ingress, authentication, and query preparation: 100 ms;
- retrieval: 350 ms;
- reranking: 250 ms;
- generation: 1,100 ms;
- final validation and response delivery: 100 ms;
- safety margin: 100 ms.
Total: 2,000 ms.
This is a starting profile for measurement, not a universal prescription. If generation has a measured p95 of 1.3 seconds for the expected output length, a 1.1-second generation allocation is unrealistic. Similarly, do not allocate 400 ms to reranking if it is unnecessary for most queries.
At each transition calculate:
remaining = absolute_deadline - monotonic_now - mandatory_reserve
A stage must never receive more time than the remaining budget. A configured 300 ms reranker timeout does not entitle it to 300 ms when only 140 ms remain.
Dynamic allocation: predict the work, then protect the deadline#
Use a lightweight policy that selects a latency profile from request features and current load. Useful features include:
- query class: simple lookup, semantic question, multi-hop, comparison, or time-sensitive request;
- initial retrieval score distribution and rank gaps;
- number of distinct evidence sources required;
- candidate count and estimated reranker cost;
- expected prompt size and desired answer length;
- recent p95/p99 latency and queue depth for retrieval, reranking, and generation;
- remaining deadline at the current stage.
The policy should use measured latency distributions conditional on these features, not a single global average. For each stage estimate a conservative completion time, such as a calibrated p90 or p95 under the current load. Allocate only work that can plausibly finish before the deadline.
A practical decision sequence:
- Estimate generation first. Reserve enough time for the expected output length, current model queue delay, TTFT, decode rate, and mandatory output checks. If the request needs 180 output tokens and the current decode rate is 120 tokens/second, decode alone is about 1.5 seconds; the system must shorten the answer, select a faster model, or acknowledge that the two-second target is infeasible for that request.
- Reserve non-negotiable work. Authentication, tenant authorization, safety controls, and response serialization are not optional budget sinks.
- Allocate retrieval to evidence sufficiency. Use an initial fast retrieval pass. Expand candidate count or query variants only if the evidence coverage signal is weak and sufficient time remains.
- Allocate reranking conditionally. Rerank when the candidate ordering is uncertain or the query is complex. Skip or reduce reranking when the initial ranking is decisive, or use a smaller candidate set/model when the deadline is tight.
- Recompute after every stage. Use actual elapsed time and fresh queue estimates. Do not assume the original prediction remains accurate.
- Stop optional work before the deadline. A late optional rerank or query expansion must not consume the generation reserve.
This is adaptive budgeting, not simply dividing 2,000 ms into three equal pieces. The policy should be trained or calibrated offline against quality and latency measurements, then constrained by explicit runtime floors, ceilings, and safe fallbacks.
Worked allocation profiles#
Consider a two-second response objective with 100 ms reserved for ingress and final delivery and 100 ms safety margin. The remaining 1,800 ms is shared by retrieval, reranking, and generation.
Easy lookup: Initial retrieval returns one highly relevant authoritative passage with a clear score margin. Allocate 250 ms to retrieval, 0 ms to expensive reranking, and 1,550 ms to generation. The remaining 100 ms is reserved for non-negotiable ingress/response work and 100 ms for safety margin. The system does not spend time improving an already sufficient ranking.
Ambiguous multi-source question: Evidence is spread across several documents and initial ranks are close. Allocate 400 ms to retrieval, 250 ms to reranking, and 1,150 ms to generation, retaining the same 200 ms fixed reserve. The additional ranking effort is justified by expected evidence-quality improvement.
High model queue pressure: The serving endpoint's predicted queue-plus-generation time rises. Reduce retrieval expansion and reranker candidates, but only down to validated minimum evidence coverage. If the expected generation time still cannot fit, use a shorter answer contract, a faster model with tested quality, or an explicit timeout/partial response. Never silently violate the deadline or invent unsupported content to appear fast.
Numerical example: adaptive policy under a two-second SLO#
Assume a service handles 10,000 requests in a representative test. A static policy spends 350 ms on retrieval, 250 ms on reranking, and reserves 1,100 ms for generation, with 300 ms for ingress, validation, and delivery. Under load, queueing pushes 18% of requests beyond two seconds. Easy requests waste reranking time; difficult requests sometimes need more candidate analysis than the static cap allows.
A calibrated adaptive policy uses query features and live queue estimates:
- 55% easy lookups skip cross-encoder reranking and use the time for generation headroom.
- 30% standard questions use a small reranking batch.
- 15% complex questions receive a larger candidate/reranking allocation when the generation estimate still fits.
- If the model queue grows, optional retrieval expansion is reduced first; the policy never spends the mandatory response reserve.
Illustrative measured results on the same 10,000-query mix:
- SLO compliance rises from 82% (8,200/10,000) to 94% (9,400/10,000).
- p95 response time falls from 2.35 seconds to 1.88 seconds.
- Mean reranker calls per request fall from 1.0 to 0.58.
- Evidence recall on the labelled evaluation set changes from 92% to 91%, while grounded answer correctness improves from 84% to 87% because the policy avoids spending reranking compute on already-clear cases and protects generation capacity.
These are illustrative engineering measurements, not a promised benchmark. The important point is to evaluate latency and quality together. A policy that meets two seconds by dropping necessary evidence is a regression.
Runtime safeguards and implementation pattern#
Keep the allocator small, deterministic, observable, and bounded. It can be a rules-based policy initially; a learned policy is justified only after a representative dataset and safe evaluation harness exist.
Pseudocode:
PYTHONasync def answer(query, deadline): reserve_ms = 200 state = observe_live_capacity() features = classify_query_and_initial_signals(query, state) generation_ms = predict_generation_p95( features.expected_output_tokens, state.model_queue, state.decode_rate, ) available_ms = remaining_ms(deadline) - reserve_ms retrieval_cap = choose_retrieval_cap(features, available_ms, generation_ms) candidates = await retrieve(query, timeout_ms=retrieval_cap) available_ms = remaining_ms(deadline) - reserve_ms rerank_cap = choose_rerank_cap( candidates.score_gap, candidates.coverage, available_ms, generation_ms, ) if rerank_cap > 0: candidates = await rerank(candidates, timeout_ms=rerank_cap) ensure_minimum_evidence(candidates) generation_cap = remaining_ms(deadline) - reserve_ms if generation_cap < minimum_safe_generation_ms: return controlled_deadline_response() return await generate( candidates, timeout_ms=generation_cap, max_tokens=budgeted_output_tokens(generation_cap, state.decode_rate), )
Production implementation must also propagate cancellation, bound concurrency, and ensure a timeout cancels child tasks. A budget allocator is not a substitute for the deadline and cancellation mechanisms covered in #279.
Quality guardrails: what must not be traded away#
Latency is not the only objective. Define a minimum evidence sufficiency threshold and preserve authorization, freshness, and citation checks regardless of load. If a fast retrieval pass cannot establish sufficient support, do not skip the only stage that could find necessary evidence merely to meet the SLO.
Use query-class-specific quality floors:
- retrieval recall or evidence coverage on labelled queries;
- answer correctness and faithfulness;
- citation support and freshness;
- abstention correctness when the evidence is insufficient;
- completeness for multi-part questions.
When the system cannot meet both the time budget and the quality floor, return a transparent degraded status, a concise supported partial answer, or an abstention. Do not report an ordinary successful answer if a required source or check was omitted.
Trade-offs and common mistakes#
- More generation reserve improves answer completion but may reduce retrieval depth. Measure quality by query class before shifting the boundary.
- Skipping reranking saves time and cost but can lower precision when candidate scores are close or evidence is distributed across documents.
- Adaptive policies improve average resource use but can oscillate if driven by noisy instantaneous metrics. Smooth signals, add hysteresis, and impose minimum/maximum caps.
- p95-based predictions protect most requests but do not guarantee p99. Track tail misses and decide whether the product SLO is p95 or p99.
- Streaming improves perceived time to first token but does not make total completion latency disappear. Clearly distinguish TTFT from full-response time.
- A faster model may reduce latency but can lower grounding or reasoning quality. Benchmark on the same representative workload.
- Aggressive candidate reduction saves reranking time but may remove the only supporting passage. Preserve a recall-oriented retrieval floor.
- Per-request adaptation can disadvantage expensive query classes. Monitor fairness across tenants and query categories; do not optimize only aggregate latency.
Monitoring and prevention#
Create dashboards for end-to-end p50/p95/p99, SLO compliance, stage elapsed time, stage budget granted versus consumed, queue wait, retrieval candidate count, reranker skip rate, generation TTFT, output tokens, cancellation, timeout, evidence coverage, grounded correctness, and cost per successful answer.
Alert when:
- a stage repeatedly consumes its entire cap;
- predicted versus actual stage latency drifts;
- the two-second SLO is missed for a particular query class or tenant;
- reranking is skipped more often while answer quality declines;
- generation queue time consumes the reserved retrieval budget;
- adaptive policy changes produce a quality or fairness regression.
Run replay benchmarks and load tests before changing the policy. Use shadow mode to compare proposed allocations with the current policy, then canary a small traffic slice. Keep a fixed-budget fallback and rollback switch. Recalibrate after model, index, prompt, hardware, or traffic-distribution changes.
Prevention checklist#
- Define one absolute two-second end-to-end deadline.
- Measure stage latency distributions and queue wait separately.
- Reserve mandatory ingress, safety, validation, and response-delivery time.
- Predict generation cost early, including queueing and expected output tokens.
- Run a fast retrieval pass before deciding whether to expand.
- Rerank conditionally based on evidence uncertainty and query complexity.
- Recompute remaining budget after every stage.
- Bound every stage by the actual remaining deadline.
- Preserve minimum evidence, authorization, freshness, and grounding checks.
- Use safe partial answers or abstention when quality and latency cannot both be met.
- Test adaptive policies on identical labelled workloads under realistic load.
- Monitor p95/p99, quality, cost, and tenant/query-class fairness.
- Roll out in shadow mode and canary before broad deployment.
Key takeaway#
A strict two-second RAG target should be managed as a shared, continuously updated request budget. Predict the expensive generation stage early, spend retrieval and reranking time only where it improves evidence, and recalculate after every stage. Adaptation is useful only inside hard deadlines and quality floors: fast unsupported answers are not successful answers.
Research references#
- Google SRE, Addressing Cascading Failures: https://sre.google/sre-book/addressing-cascading-failures/
- Google SRE, Service Level Objectives: https://sre.google/sre-book/service-level-objectives/
- Dean and Barroso, The Tail at Scale: https://research.google/pubs/the-tail-at-scale/
- Raza et al., SAGE: SLO-Aware Adaptive Retrieval for Production RAG Systems (2026): https://arxiv.org/abs/2608.08237
- Cai and Zafarani, Less can be More: Relieving RAG Bottlenecks via Evidence Frontloading and Pressure-Adaptive Budgeting (2026): https://arxiv.org/abs/2608.25115
- OpenTelemetry, Context Propagation: https://opentelemetry.io/docs/concepts/context-propagation/
Related questions
- Your RAG response latency doubles after adding a third retrieval source. How would you diagnose the critical path and reduce fan-out overhead?
- The same business question triggers several expensive LLM calls through query decomposition. How would you identify unnecessary calls and reduce their cost?
- One large enterprise tenant consumes most of your retrieval infrastructure. How would you design fair scheduling and tenant-specific resource quotas?
Explore other topics:Large Language ModelsAI AgentsMLOps