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

The same business question triggers several expensive LLM calls through query decomposition. How would you identify unnecessary calls and reduce their cost?

Question 283 of 284 · Updated

On this page

Query decomposition can improve retrieval for genuinely compositional questions. It can also turn one user request into an expensive chain of planner, rewrite, sub-query, retrieval, reranking, synthesis, and verification calls. The engineering objective is not to eliminate decomposition. It is to spend additional calls only when they are likely to add distinct evidence or improve the answer enough to justify their cost and latency.

This lesson focuses on operational diagnosis and call-budget control. The basic concept of query decomposition is covered separately; the concern here is identifying redundant work in a live system and reducing it without damaging multi-hop recall or answer quality.

Production incident#

An enterprise assistant answers questions over product, finance, and policy documentation. A common business question is: “What is the renewal date and annual price for the Acme support plan?”

After a query-planner deployment, the same request triggers:

  • one LLM call to classify the query;
  • one LLM call to generate four sub-queries;
  • four independent retrieval calls;
  • two LLM calls to rewrite low-confidence sub-queries;
  • four reranker calls;
  • one LLM synthesis call;
  • one LLM verification call.

Traffic has not changed, but the median cost per answer increases from $0.018 to $0.061 and p95 latency rises from 2.1 to 5.8 seconds. The four sub-queries frequently retrieve the same plan page and pricing appendix. The planner has split a simple lookup into overlapping pieces; the low-confidence retry logic then repeats retrieval even when the evidence is already sufficient.

The first response to the incident is to reduce top-k globally. That lowers spend, but a separate class of questions asking for comparisons across multiple contract versions begins missing evidence. The actual issue is not “too much retrieval” in every case. It is unconditional decomposition and repeated work without measuring the marginal value of each branch.

Root-cause debugging#

1. Reconstruct one logical request as a call graph#

A request-level trace must show the full tree, not just total model latency. Give the user request a stable root ID and every model, tool, retrieval, and reranker operation a child span with a unique operation ID and parent ID.

Record:

  • stage and purpose: classify, plan, decompose, rewrite, retrieve, rerank, synthesize, verify;
  • model/provider/version and prompt-template version;
  • input/output/cached token usage and estimated/billed cost;
  • latency, status, retry attempt, timeout, cancellation, and finish reason;
  • sub-query ID, normalized query fingerprint, parent query, and branch dependency;
  • retrieval source/index, candidates, document IDs, rank scores, and evidence IDs;
  • whether the operation's evidence was actually used in the final answer;
  • whether the call was cache hit, duplicate, fallback, or quality-triggered.

The trace should make it possible to answer: “For this one user question, why were there eleven LLM calls, which branches were duplicates, and what did each one contribute?”

OpenTelemetry GenAI spans and token metrics provide a vendor-neutral foundation for recording model calls and token usage. Keep prompt/document content out of default telemetry; record safe structural metadata and use tightly controlled, opt-in content capture when an investigation truly requires it.

2. Measure call amplification and token amplification#

Define call amplification:

LaTeX

Define token amplification:

LaTeX

Track both per feature and per query class. A workflow with 1.0 calls/request may still be expensive if prompts are huge; a workflow with 4 calls/request may be justified for complex multi-hop queries. Neither metric alone establishes waste.

Also measure:

  • cost per successful answer;
  • decomposition rate and average branches per decomposed request;
  • duplicate/near-duplicate sub-query rate;
  • unique evidence documents per branch and overlap between branches;
  • fraction of branches whose evidence reaches the final context or answer;
  • retrieval and reranker invocations per logical request;
  • retry and fallback calls by reason;
  • answer quality, citation coverage, and multi-hop recall by query class.

3. Identify specific forms of redundant work#

Semantic overlap: two sub-queries ask for the same fact with different wording, such as “Acme support annual fee” and “yearly price of Acme support”.

Parent-child duplication: the original query retrieves the same evidence as every child query, so decomposition adds no new documents.

Planner over-splitting: a single entity lookup is broken into independent clauses even though one retrieval can satisfy all of them.

Repeated planning: a rewrite or reflection call regenerates essentially the same plan because the workflow does not preserve its previous decision or state.

Unproductive branches: a sub-query returns no useful evidence, but the system retries it repeatedly with minor wording changes.

Evidence duplication: different branches retrieve the same document passages, which are sent repeatedly to the reranker or generator.

Unbounded verification: the verifier asks for another model call without a stopping condition or a measurable unresolved issue.

Retry amplification: timeouts, tool errors, or partial failures cause the same billable operation to run again without idempotency or retry budgets.

Hidden fan-out: framework callbacks, agent loops, or fallback chains invoke model calls that are not counted in the top-level application metrics.

4. Find the first deployment or cohort divergence#

Compare before/after traces by prompt version, planner model, decomposition policy, feature, tenant, and query category. Inspect representative traces from both simple and genuinely multi-hop questions.

A useful review asks:

  • Did planner prompt changes increase branch count?
  • Did a new model or temperature increase plan variability?
  • Did a retrieval threshold change create more low-confidence rewrites?
  • Did a timeout policy add duplicate attempts?
  • Did a framework upgrade change tool-call or reflection behavior?
  • Are branches independent, or does one branch depend on evidence from another?
  • Are the same documents retrieved under different sub-query IDs?
  • Does answer quality actually improve when the extra branch is present?

Do not infer redundancy from branch count alone. Validate against judged answer correctness, evidence recall, citation support, and representative failure cases.

Engineering solution: a budgeted, evidence-aware decomposition pipeline#

1. Add a cheap complexity gate before decomposition#

Route the request into a small set of strategies:

  • Direct: one retrieval using the original query, then one answer call.
  • Constrained: one retrieval with a structured filter or a small number of targeted retrieval variants.
  • Decomposed: multiple sub-queries when distinct entities, conditions, time periods, or evidence sources are required.
  • Iterative multi-hop: retrieve one fact, use it to formulate the next query, and continue only while a real dependency remains.

Use deterministic signals first where possible: number of explicit entities, comparison operators, multiple time ranges, distinct requested attributes, conjunctions, references such as “that company”, and known multi-hop task patterns. A small classifier can help when signals are ambiguous, but its cost must be included in the budget.

The gate should be conservative about skipping decomposition when the question requires joining evidence across documents. Validate routing against a labelled set of easy, compositional, and multi-hop questions.

2. Make the decomposition plan explicit and constrained#

Require the planner to return structured sub-tasks with:

  • the fact or constraint being answered;
  • entity and time scope;
  • required evidence type or source;
  • dependency on prior sub-tasks;
  • why the parent query cannot retrieve it adequately;
  • expected unique information gain;
  • a stop condition.

Reject plans that simply paraphrase the parent query or duplicate another branch. Merge branches that request the same fact over the same entity/time scope. Preserve genuinely distinct constraints—for example, one branch for a 2024 contract and another for its 2025 amendment.

Use schema validation, a maximum branch count, maximum planner tokens, and a maximum number of planning iterations. Invalid or over-budget plans should fall back to a safe simpler retrieval path, not silently expand.

3. Deduplicate before expensive execution#

Normalize query text for exact duplicate detection, but do not rely on string equality. Use a lightweight semantic similarity check or embeddings for near-duplicate candidates, combined with entity, attribute, time range, and source constraints.

A safe merge rule is: merge two branches only when their intent, entity scope, requested attribute, temporal scope, and evidence requirements are equivalent. Similar wording is not enough if one branch asks for gross revenue and another asks for net revenue.

Deduplicate retrieved evidence by stable document and passage identifiers. Preserve provenance showing which branches support each passage. If the same evidence satisfies multiple branches, reuse it rather than reranking or inserting duplicate context repeatedly.

4. Execute independent branches with a bounded budget#

Build a dependency DAG. Run truly independent retrieval operations in parallel, subject to the global and tenant budgets already defined by the service. Run dependent hops sequentially because the later query may require an entity or fact discovered by an earlier hop.

Set explicit limits:

  • maximum branches per request;
  • maximum retrieval calls and candidate count;
  • maximum reranker invocations;
  • maximum planner, rewrite, and verifier calls;
  • maximum total input/output tokens and cost;
  • maximum elapsed time and remaining deadline.

Do not launch all branches and only then discover that the request exceeded its budget. Reserve budget before dispatch and account for retries as additional work.

5. Use marginal evidence value to decide whether to continue#

After each retrieval batch, assess whether new evidence materially increases coverage of required facts. A branch that returns only already-seen passages has low marginal value. A branch that supplies a missing contract date may be essential even if its similarity score is modest.

Use deterministic evidence accounting where possible:

  • map each required answer slot to supporting passage IDs;
  • mark slots covered, uncovered, or conflicting;
  • measure newly covered slots and unique relevant passages per branch;
  • stop when all required slots have adequate evidence or the remaining budget cannot plausibly close the gap.

A lightweight relevance or sufficiency model may assist, but it should not become another unbounded LLM loop. Calibrate the stopping rule against labelled examples and monitor false stops that omit required facts.

6. Reuse work safely#

  • Request cache: cache stable results for identical normalized requests only when tenant, permissions, filters, index version, and freshness policy match.
  • Sub-query cache: reuse retrieval results for equivalent sub-queries under the same tenant and index/security scope.
  • Prompt-prefix caching: where supported by the model provider, keep stable prompt prefixes consistent and measure actual cached-token billing.
  • In-flight deduplication: coalesce identical concurrent work so simultaneous requests do not trigger duplicate expensive operations.
  • Plan reuse: reuse a plan only when the underlying query intent, tenant context, policy version, and data scope are equivalent.

Every cache needs explicit invalidation for document changes, ACL changes, index updates, and prompt/configuration versions. Never share private evidence across tenants merely because their query strings match.

7. Make synthesis consume an evidence ledger#

Pass the generator a compact evidence set with passage IDs, source metadata, covered answer slots, and conflicts. Avoid concatenating the same passage multiple times because it appeared in multiple branches.

The generator should:

  • answer only requested slots;
  • cite evidence for each factual claim;
  • surface conflicts rather than inventing a reconciliation;
  • abstain or request clarification when required evidence is absent;
  • avoid calling another model merely to restate evidence already present.

Use a verifier only for a defined risk or coverage trigger, such as conflicting sources, high-impact claims, or missing citation support. A verifier should return a bounded structured decision, not automatically start another agent cycle.

Numerical example: reduce eleven calls to two or three#

Assume 100,000 logical requests per month. Before remediation, a common simple lookup averages:

  • 1 planner call;
  • 1 decomposition call;
  • 4 branch rewrite calls;
  • 1 synthesis call;
  • 1 verification call.

That is 8 LLM calls per request, or 800,000 calls/month, before counting model calls hidden inside retries. Retrieval and reranking also run four times for each request.

Suppose the average billable usage and model mix produce $0.061 per completed answer. Monthly model cost for this cohort is approximately:

[ 100{,}000 imes $0.061 = $6{,}100 ]

After adding a complexity gate, merging overlapping branches, deduplicating evidence, and making verification conditional:

  • 82% of requests use direct retrieval plus one answer call;
  • 15% use a constrained two-branch path;
  • 3% use a genuinely multi-hop path with up to four targeted branches.

For illustration, assume the new average cost per answer is $0.024. Then:

[ 100{,}000 imes $0.024 = $2{,}400 ]

The cohort saves $3,700/month, approximately 60.7%. This is an illustrative scenario, not a promised benchmark. Measure provider-reported tokens and cost, because call count alone ignores model size, prompt length, cached tokens, and output usage.

The quality guardrail is essential: suppose the evaluation set has 1,000 queries, including 250 multi-hop cases. After rollout, answer correctness changes from 91.0% to 90.8%, citation coverage from 94.0% to 93.9%, and multi-hop evidence recall from 88.0% to 87.8%. These small differences must be assessed against a pre-agreed statistical non-inferiority margin and confidence intervals—not declared harmless from point estimates alone. If critical multi-hop recall falls beyond the guardrail, route that query class back to the deeper strategy.

Implementation sketch#

handle_request(request):
    context = verified_tenant_and_permission_context(request)
    deadline = establish_end_to_end_deadline()
    budget = reserve_call_token_cost_and_retrieval_budget(context)

    strategy = complexity_router(request, cheap_signals)
    if strategy == DIRECT:
        plan = [original_query]
    else:
        plan = planner_with_strict_schema_and_budget(request)

    plan = validate_dependencies_and_required_answer_slots(plan)
    plan = merge_equivalent_subtasks(plan)
    plan = reject_parent_paraphrases_and_duplicate_branches(plan)
    if plan.invalid_or_over_budget:
        plan = safe_fallback_plan(request)

    evidence_ledger = empty_ledger()

    for ready_batch in dependency_dag(plan):
        queries = remove_completed_or_cached_subtasks(ready_batch)
        reserve_budget_before_dispatch(queries)

        results = bounded_parallel_retrieval(queries, deadline)
        results = deduplicate_passages_by_stable_id(results)
        evidence_ledger.merge_with_provenance(results)

        uncovered = required_slots_without_sufficient_evidence(evidence_ledger)
        if uncovered.empty:
            break
        if marginal_value(uncovered, results) < continuation_threshold:
            break
        if budget_or_deadline_exhausted():
            break

    context = compact_unique_evidence(evidence_ledger)
    answer = generate_once_with_citations(context, request)

    if defined_high_risk_or_conflict_trigger(answer, evidence_ledger):
        answer = bounded_verification(answer, evidence_ledger, remaining_budget)

    record_all_calls_cost_tokens_branches_and_quality_signals()
    return answer

The implementation must treat cancellation and retries explicitly. If the client disconnects, cancel downstream work where safe. If a provider times out after accepting a request, the operation may still be billable; record the attempt and do not blindly replay it. Use idempotency keys where the provider supports them and a bounded retry budget for transient failures.

Trade-offs and failure scenarios#

  • Simple routing vs classifier cost: deterministic rules are cheap and explainable but miss subtle composition. A classifier improves coverage but can add latency and another model call. Evaluate its net cost and routing errors.
  • Fewer branches vs recall: merging similar sub-queries can remove an important distinction, especially around dates, entities, units, or legal conditions. Merge only after checking semantic scope and evidence requirements.
  • Parallelism vs latency and load: parallel branches reduce wall-clock time but increase instantaneous retrieval and model concurrency. Bound fan-out and respect tenant/global admission controls.
  • Aggressive stopping vs completeness: early stopping saves money but may miss evidence from a later hop. Use answer-slot coverage and risk-based thresholds, with special protection for high-impact questions.
  • Semantic deduplication vs false merges: embeddings can consider distinct questions similar. Combine similarity with entity, attribute, time, and filter checks; preserve branch provenance.
  • Caching vs freshness: cached evidence may become stale after document or permission changes. Include index and authorization scope in cache identity and invalidate on updates.
  • Verification vs call amplification: a verifier catches unsupported claims but can double generation cost or trigger loops. Invoke it only for explicit risk conditions and cap it to one bounded pass unless a documented policy says otherwise.
  • Cost vs quality measurement: offline benchmarks may not represent real user traffic. Use shadow evaluation, canaries, sampled human review, and rollback thresholds.
  • Retries vs duplicate billing: retries improve resilience but can replay expensive work. Track attempts separately and enforce idempotency, deadline-aware retries, and per-request budgets.
  • Prompt logging vs privacy: storing full prompts helps debugging but can expose confidential data. Prefer structural telemetry, redaction, retention controls, and restricted access.

Monitoring and operational verification#

Monitor the following by tenant, feature, query class, model, and prompt/config version:

  • LLM calls per logical request and calls by stage;
  • billable input/output/cached tokens and cost per successful answer;
  • decomposition rate, branches per decomposed request, and planner token cost;
  • exact and semantic duplicate branch rates;
  • unique evidence passages per branch and cross-branch overlap;
  • evidence coverage gained per additional branch;
  • branches with no useful evidence and branches unused by synthesis;
  • reranker calls and repeated passage processing;
  • cache hit rate, cache bypass reason, and in-flight deduplication rate;
  • retry attempts, timeout outcomes, and billable cancelled operations;
  • p50/p95 latency, queue time, and deadline exhaustion;
  • answer correctness, citation coverage, abstention, and multi-hop recall.

Create a trace-level cost waterfall for sampled requests. A useful operational metric is marginal cost per newly covered answer slot. It reveals when the next branch is spending heavily while adding no useful evidence. Review both median and tail behavior; a small number of runaway agent traces can dominate total spend.

Prevention checklist#

  • [ ] Establish a root trace and unique operation span for every model, retrieval, reranking, and retry call.
  • [ ] Record stage, parent operation, model, prompt version, tokens, latency, cost, and branch identity.
  • [ ] Maintain labelled simple, compositional, and multi-hop evaluation cohorts.
  • [ ] Gate decomposition on expected need; do not invoke a planner for every request by default.
  • [ ] Require structured sub-tasks with distinct intent, scope, dependencies, and expected evidence value.
  • [ ] Merge equivalent branches only after checking entity, attribute, time, and filter scope.
  • [ ] Deduplicate retrieved passages while preserving source and branch provenance.
  • [ ] Enforce per-request call, token, retrieval, reranker, time, and cost budgets.
  • [ ] Use bounded parallelism for independent branches and sequential execution for dependent hops.
  • [ ] Stop when required evidence is sufficient or additional work has low marginal value.
  • [ ] Cache only within matching tenant, permission, freshness, and index-version boundaries.
  • [ ] Make verification conditional, bounded, and measurable.
  • [ ] Count retries and cancelled-but-billed operations; use idempotency where available.
  • [ ] Canary routing changes and enforce answer-quality and multi-hop recall rollback thresholds.
  • [ ] Review high-cost traces and update the evaluation set with real production failure cases.

Key principle#

Decomposition should earn every additional call. Trace the full request graph, measure the unique evidence and quality contributed by each branch, enforce a finite budget, and stop when the evidence is sufficient. Optimize for cost per correct, grounded answer—not minimum call count at any price.

Further reading#

Related questions

Explore other topics:Large Language ModelsAI AgentsMLOps