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

Your monthly RAG operating cost unexpectedly triples without a comparable increase in requests. How would you attribute the increase?

Question 282 of 284 · Updated

On this page

A RAG bill is the sum of many different meters: model input and output tokens, embeddings, vector-database reads and compute, reranking, orchestration, network transfer, storage, observability, and idle or over-provisioned infrastructure. Request count alone is a poor cost predictor. A stable request volume can hide longer prompts, more retrieval fan-out, repeated model calls, a model-tier change, retries, cache regressions, or a continuously running background job.

The objective is to move from “the bill is three times higher” to a defensible explanation of which workload, feature, tenant, stage, and behavior caused the incremental spend, and then verify the remediation against both cost and answer quality.

Production incident#

A business knowledge assistant normally processes about 1.2 million user requests per month. The monthly cloud and AI bill rises from $18,000 to $54,000, while request volume increases only 6%. The first dashboard shows that the LLM provider is responsible for most of the increase, so the team initially assumes that model prices changed.

Finance asks for a breakdown by service, but the application logs contain only request IDs and total latency. They do not consistently record tenant, feature, model, token counts, retry attempt, retrieval candidate count, or workflow stage. The vector database and reranker costs are grouped into shared infrastructure accounts. Nobody can explain whether the extra $36,000 came from more expensive answers, a deployment regression, or a new workload.

A trace-based sample reveals three simultaneous changes:

  • A prompt-template deployment added conversation history and more retrieved passages, increasing average input tokens.
  • A retrieval configuration change increased candidate count and enabled reranking for a larger fraction of queries.
  • A timeout handler retried some model calls without reliably recording the original attempt, so one logical user request could create multiple billable operations.

The incident is not one mysterious price increase. It is a combination of unit-cost growth, workflow amplification, and incomplete allocation.

Root-cause debugging: establish the cost equation#

Start by decomposing spend rather than comparing invoice totals alone.

For a given period:

[ C_{total}=C_{LLM}+C_{embedding}+C_{vector}+C_{rerank}+C_{compute}+C_{storage}+C_{network}+C_{observability} ]

For each component, separate:

  • Price effect: the unit price, model tariff, discount, or billing tier changed.
  • Volume effect: more billable units were consumed.
  • Mix effect: traffic shifted toward a more expensive model, region, feature, tenant, or workload class.
  • Efficiency effect: more units are consumed per successful user outcome.
  • Fixed/idle effect: provisioned capacity or baseline resources grew without corresponding work.

Use a consistent time window and currency. Reconcile application-side estimates with provider invoices and cloud billing exports; estimates are diagnostic, while billed usage is the financial source of truth.

1. Validate the bill before blaming the application#

  • Compare invoice line items, usage quantities, unit prices, discounts, credits, taxes, and billing periods.
  • Check whether the previous month was a partial period, promotional credit, or delayed usage posting.
  • Identify new SKUs, model versions, regions, projects, vector indexes, and provisioned capacity.
  • Separate one-time migration, backfill, evaluation, and load-test costs from recurring serving costs.
  • Check whether a provider changed its billing dimensions or whether an account/project was consolidated.

A threefold invoice can be a reporting or allocation change rather than a threefold increase in production consumption.

2. Build a request-to-work trace#

Give every user request a stable logical request ID and every downstream operation a unique operation ID. Propagate a trace context through retrieval, reranking, embedding, model calls, tool calls, retries, and asynchronous jobs.

Record, where applicable:

  • tenant, product feature, environment, region, route, and workload type;
  • model/provider and model version;
  • prompt-template version, retrieval configuration version, and index version;
  • input, output, cached, reasoning, and modality-specific tokens when provided;
  • number of retrieval sources, shards, candidates, reranker inputs, and reranker duration;
  • number of model calls and retry attempts per logical request;
  • cache lookup/result, cache key version, and cache bypass reason;
  • status, timeout, cancellation, and whether the operation was billable;
  • estimated cost and provider-reported or reconciled cost.

Do not log raw prompts, retrieved documents, or personal data merely to allocate spend. Use controlled identifiers, redaction, retention limits, and access controls. High-cardinality tenant and request attributes belong in traces or cost-event records; avoid exploding metric label cardinality.

3. Decompose unit economics#

Compute more than total spend:

LaTeX
LaTeX
LaTeX

Also calculate cost per tenant, feature, model, workflow, and successful task. Compare distributions—not just averages—because a small set of long-context outliers can dominate spend.

A cheap answer that fails and triggers another request is not necessarily efficient. Pair cost with quality, latency, completion, and user outcome metrics.

4. Find the first divergence#

Create a timeline of deployments and configuration changes beside cost and usage metrics. Compare the period before and after the increase:

  • cost per logical request and per successful answer;
  • input/output tokens per model call and calls per logical request;
  • retrieval candidates and reranker invocations per request;
  • cache hit rate and cache bypass rate;
  • retry rate, timeout rate, and cancelled-but-billed operations;
  • model mix and price per million tokens;
  • vector DB reads, compute hours, index growth, and provisioned capacity;
  • background jobs, evaluations, ingestion, and test traffic.

Segment by tenant, feature, model, prompt version, route, region, and deployment. The earliest segment that changes is often the best lead for root cause.

5. Reconcile estimated cost with actual invoices#

Maintain a cost ledger at operation level. Join provider usage exports to internal operation IDs wherever the provider supports request-level identifiers. When it does not, reconcile at the narrowest reliable aggregation: account, model, SKU, region, and time bucket.

Mark each allocation as direct, measured shared, estimated shared, or unallocated. Do not manufacture precision. A transparent “unallocated shared cost” bucket is better than silently charging arbitrary tenants.

Engineering solution: a cost observability pipeline#

1. Define a canonical cost event#

Emit one structured event for each billable or resource-consuming operation. A useful schema includes:

  • logical_request_id and operation_id;
  • parent_operation_id and trace_id;
  • tenant_id, feature, environment, region, workload;
  • stage (embedding, retrieval, rerank, generation, orchestration);
  • provider, model, model_version, SKU;
  • prompt_version, retrieval_config_version, index_version;
  • input_tokens, output_tokens, cached_tokens, reasoning_tokens, modality;
  • retrieval_candidate_count, shard_count, reranker_item_count;
  • retry_attempt, cache_status, status, duration_ms;
  • usage_quantity, usage_unit, unit_price_version, estimated_cost;
  • provider_billed_usage, provider_billed_cost, reconciliation_status.

Use a versioned schema and validate it at ingestion. Missing tenant or feature metadata should be visible as an instrumentation defect, not silently converted into a misleading allocation.

2. Instrument every cost-bearing stage#

Generation: capture provider-reported billable input and output tokens, model, price version, cached-token accounting, reasoning tokens where billed, and failed/partial operations where billable.

Embeddings: record input token counts, batch size, model, and embedding calls per logical workflow. Include re-embedding and ingestion separately from online query embedding.

Retrieval: track vector queries, candidates, shards, index type, database compute, storage, and provisioned capacity. Candidate count is a useful workload signal but not a substitute for the database's actual billing meter.

Reranking: record input pairs, batch size, model or accelerator, duration, and invocations per user request.

Orchestration and tools: record agent steps, query rewrites, decomposition branches, tool calls, retries, and repeated execution. This is where one request can multiply downstream work.

Infrastructure: allocate container/VM/GPU hours, autoscaling idle time, network egress, logs, traces, and storage. Separate fixed baseline capacity from marginal workload cost.

Use OpenTelemetry GenAI conventions where applicable for token usage and model dimensions, while retaining the additional business identifiers needed for cost allocation.

3. Create a cost waterfall#

For each day and month, show:

  1. provider invoice total;
  2. direct usage attributed to logical requests;
  3. direct usage attributed to background workloads;
  4. shared infrastructure allocated by an explicit rule;
  5. unallocated variance.

Then drill into the top contributors by incremental spend, not merely largest absolute spend. A model that always costs the most may not explain why this month changed.

4. Use a controlled allocation hierarchy#

Allocate costs in this order:

  • Direct operation cost: provider reports a usage amount or cost tied to an operation.
  • Measured tenant resource use: shared vector or compute service exposes per-tenant resource consumption.
  • Usage-based apportionment: split shared cost using measured CPU/GPU time, database work units, tokens, or storage.
  • Capacity reservation: assign dedicated or reserved capacity to the tenant that requested it, with documented rules for idle time.
  • Unallocated shared pool: retain costs that cannot be measured accurately and improve instrumentation.

For example, allocate a shared vector cluster's variable compute by measured database work units per tenant, while allocating fixed baseline capacity by reserved capacity or an agreed subscription share. Do not allocate all shared cost by request count if requests have very different work profiles.

5. Detect anomalies at multiple levels#

Alert on absolute spend, forecast variance, and normalized unit economics:

  • total daily spend and month-to-date forecast;
  • cost per 1,000 logical requests;
  • cost per successful answer;
  • tokens per request and model calls per request;
  • retrieval/rerank work per request;
  • cost per tenant and feature;
  • unallocated cost percentage;
  • divergence between internal estimates and provider billing.

Use baselines that account for day-of-week, traffic mix, deployments, and planned batch jobs. Trigger both aggregate alerts and segmented alerts: a small tenant or feature can have a severe anomaly while total spend remains within budget.

6. Make cost controls safe and measurable#

Once attribution is trustworthy, introduce:

  • per-tenant and per-feature budgets with warning and hard-limit policies;
  • maximum prompt/context and output budgets;
  • model routing rules based on task quality requirements;
  • retrieval candidate and reranker budgets;
  • deduplication of retries and idempotency for billable operations;
  • cache policies with correctness and tenant-isolation safeguards;
  • batch embedding and ingestion scheduling;
  • concurrency/admission limits for expensive workloads;
  • explicit circuit breakers for runaway agent loops.

Do not cut cost blindly. Require quality, groundedness, recall, latency, and completion guardrails for each optimization.

Numerical example: explain the extra $36,000#

Assume the prior month's $18,000 bill is:

  • LLM generation: $9,000
  • embeddings: $1,000
  • vector database: $3,000
  • reranking: $1,500
  • application compute, network, storage, and observability: $3,500

The new bill is $54,000. After reconciling invoice line items and operation-level telemetry, the team attributes the increase as follows:

  • LLM generation: $9,000 → $33,000 (+$24,000)
  • embeddings: $1,000 → $2,000 (+$1,000)
  • vector database: $3,000 → $7,000 (+$4,000)
  • reranking: $1,500 → $5,000 (+$3,500)
  • other infrastructure: $3,500 → $7,000 (+$3,500)

Total increase: $24,000 + $1,000 + $4,000 + $3,500 + $3,500 = $36,000.

The generation investigation shows:

  • logical requests rose 6%, from 1.20 million to 1.272 million;
  • average billable input tokens per logical request rose from 3,000 to 6,000;
  • model calls per request rose from 1.0 to 1.35 because of retries and additional orchestration calls;
  • output tokens and model mix also shifted toward a more expensive tier.

For a simplified illustration, suppose the old generation workload was 3.6 billion input tokens. If the new workload is 1.272M × 6,000 × 1.35 = 10.3032 billion input tokens, it is about 2.86 times the old input-token volume even though request volume rose only 6%. The actual invoice increase also depends on output tokens, cached-token pricing, model mix, and discounts; do not attribute the entire $24,000 to input tokens without reconciling those meters.

Further trace analysis identifies the prompt expansion as the largest input-token driver and retry amplification as an additional multiplier. The retrieval and reranker changes explain their respective cost increases. The team reverts the accidental prompt-history expansion, caps duplicate retry attempts, and restores conditional reranking for low-risk queries.

After rollout, the team compares a matched traffic cohort: cost per successful answer falls from $0.042 to $0.021, while grounded-answer evaluation remains within its agreed non-inferiority margin and p95 latency improves. These figures are illustrative; production decisions require measured cohorts and provider billing reconciliation.

Investigation workflow and pseudocode#

for each billing_period:
    invoice = ingest_provider_cost_exports()
    events = ingest_versioned_operation_cost_events()

    validate_currency_period_sku_and_usage_units(invoice)
    validate_event_schema_and_required_allocation_metadata(events)

    direct_cost = reconcile(events, invoice, keys=[
        provider, account, model_or_sku, region, time_bucket
    ])

    shared_cost = allocate_shared_resources(
        measured_usage_first,
        documented_capacity_rules_second
    )

    unallocated = invoice.total - direct_cost - shared_cost

    compare_with_baseline(
        spend, cost_per_request, cost_per_success,
        tokens_per_request, calls_per_request,
        retrieval_work, rerank_work, tenant_and_feature_slices
    )

    rank_contributors_by_incremental_cost()
    correlate_first_divergence_with_deployments_and_jobs()
    create_owner_assigned_incident_for_verified_anomaly()

before_optimizing:
    define_quality_latency_and_completion_guardrails()
    canary_one_change()
    compare_matched_cohorts()
    reconcile_actual_invoice_after_billing_lag()

The reconciliation pipeline should be idempotent: provider exports can arrive late or be revised. Preserve raw billing records, version allocation rules, and retain the original calculation so finance and engineering can reproduce a monthly total.

Trade-offs and failure scenarios#

  • Exact attribution vs instrumentation overhead: per-operation events improve diagnosis but increase telemetry volume and processing cost. Sample detailed traces carefully, while retaining unsampled aggregate counters and billing events.
  • High-cardinality dimensions vs dashboard cost: tenant, request, and operation IDs are useful for trace/cost-event records but dangerous as metric labels. Keep metrics bounded and use logs/traces or an analytical store for drill-down.
  • Estimated vs billed cost: real-time estimates enable rapid response but can diverge from discounts, cache pricing, provider adjustments, or delayed invoices. Reconcile periodically and show estimate confidence.
  • Direct vs shared allocation: direct usage is defensible; shared infrastructure needs a documented apportionment rule. Request-count allocation is simple but unfair when workloads differ.
  • Cost reduction vs answer quality: smaller models, fewer candidates, shorter context, or lower output limits can degrade recall and groundedness. Use offline evaluation and canary guardrails.
  • Caching vs freshness and isolation: caching can reduce repeated work, but keys must include tenant/security scope and relevant prompt/index versions. Never share cached private evidence across tenants.
  • Retry suppression vs resilience: retries can recover transient failures but amplify spend during outages. Use bounded retry budgets, idempotency, and classify which failed operations were billed.
  • Budget enforcement vs availability: a hard stop protects spend but may interrupt critical workflows. Define tiered warning, graceful degradation, and emergency policies with owners.
  • Delayed billing data: cloud invoices may lag real usage. Use application telemetry for early detection but avoid treating provisional estimates as final finance numbers.
  • Missing metadata: untagged workloads distort tenant showback and anomaly detection. Track allocation coverage and make metadata completeness a release criterion.

Monitoring and operational verification#

Track these signals continuously:

  • spend by provider, SKU/model, stage, tenant, feature, region, and environment;
  • direct, shared-allocated, estimated, and unallocated cost;
  • cost per logical request and per successful answer;
  • input/output/cached/reasoning tokens per operation and per request;
  • model calls, retries, tool calls, and agent steps per logical request;
  • retrieval candidates, vector work units, reranker invocations, and embedding batches;
  • cache hit/miss/bypass rates and prompt-version changes;
  • deployment-correlated changes in unit cost and quality;
  • invoice-to-event reconciliation variance and billing-data freshness;
  • budget forecast, anomaly duration, and cost avoided after remediation.

For every alert, retain an investigation record: detection time, affected scope, first divergent metric, evidence, owner, mitigation, quality impact, final invoice reconciliation, and prevention action.

Prevention checklist#

  • [ ] Define a canonical logical request ID and unique downstream operation IDs.
  • [ ] Propagate tenant, feature, environment, model, prompt version, and workflow metadata through all stages.
  • [ ] Record billable token usage, model calls, retries, retrieval work, reranking, embeddings, and background jobs.
  • [ ] Preserve provider billing exports and reconcile them with internal cost events.
  • [ ] Separate online serving, ingestion, evaluation, experiments, and batch workloads.
  • [ ] Allocate direct costs first; document measured rules for shared infrastructure and expose unallocated spend.
  • [ ] Track cost per successful answer, not only cost per request or monthly totals.
  • [ ] Alert on both total spend and segmented unit-cost anomalies.
  • [ ] Correlate cost regressions with deployments, prompt/config changes, model routing, and scheduled jobs.
  • [ ] Use bounded retries, idempotency, cache correctness, context budgets, and admission controls.
  • [ ] Require quality and latency guardrails for cost optimizations.
  • [ ] Assign an owner and runbook to each anomaly class; review unresolved allocation gaps monthly.

Key principle#

A cost alert tells you that spend changed; attribution tells you what to fix. Join invoice-grade usage with request-level operation telemetry, allocate shared infrastructure transparently, and track cost per successful answer. Only then optimize the stage or workload responsible for the increase—and verify that the savings survive billing reconciliation without harming answer quality.

Further reading#

  • FinOps Foundation, Anomaly Management: detect, investigate, assign ownership, and manage unexpected spend.
  • FinOps Foundation, Allocation: direct and shared cost attribution using metadata and measured usage.
  • Microsoft Learn, Understand usage and cost: ingest, allocate, report, analyze, and alert on cost and usage.
  • OpenTelemetry, GenAI token metrics: standardized token usage counters and operation-level token distributions.
  • Google Cloud, What is Cloud FinOps?: accountability, measurement, unit economics, and optimization.

Related questions

Explore other topics:Large Language ModelsAI AgentsMLOps