Retrieval-Augmented GenerationRAGProduction RAG — API Performance, Concurrency & Cost
One large enterprise tenant consumes most of your retrieval infrastructure. How would you design fair scheduling and tenant-specific resource quotas?
Question 281 of 284 · Updated
On this page
- Production incident
- Root-cause debugging
- Engineering solution
- 1. Define a resource contract for each tenant
- 2. Estimate cost, then reconcile actual cost
- 3. Apply token buckets and concurrency limits per tenant
- 4. Schedule fairly across tenants
- 5. Borrow unused capacity without surrendering isolation
- 6. Make overload behavior explicit
- Numerical example: 200 concurrent retrieval slots
- Scheduling pseudocode
- Trade-offs and failure scenarios
- Monitoring and operational verification
- Prevention checklist
- Key principle
- Further reading
A multi-tenant RAG service must protect shared infrastructure without treating every request as equally expensive or permanently wasting capacity reserved for tenants that are idle. The design goal is isolation under contention with safe sharing when capacity is available: one tenant can burst within an agreed envelope, but cannot monopolize retrieval workers, vector-database connections, rerankers, embedding capacity, or model tokens.
Production incident#
A SaaS knowledge assistant serves 240 enterprise tenants from a shared retrieval cluster. On Monday morning, one large tenant launches an internal assistant to 18,000 employees. Its traffic rises from 70 to 620 requests/second. Many requests also retrieve 100 candidates and invoke a cross-encoder reranker.
The service-wide request rate rises by only 28%, but vector-search concurrency reaches its limit. The large tenant occupies most worker slots; smaller tenants see p95 retrieval latency rise from 180 ms to 2.4 seconds and timeouts climb from 0.4% to 9%. A few tenants retry, increasing queue pressure. The incident is initially misdiagnosed as a vector database regression because CPU and database latency are high across the cluster.
The important symptom is not simply high aggregate QPS. It is that one authenticated tenant's share of expensive work grows disproportionately, while unrelated tenants lose their service level.
Root-cause debugging#
Debug by tenant, stage, and resource—not by global request totals alone.
- Reconstruct tenant identity. Join gateway, retrieval, reranker, and model traces using a server-verified tenant ID. Never trust a tenant ID supplied only in an arbitrary client header. Verify that async jobs, retries, and fan-out calls retain the same tenant context.
- Build per-tenant demand profiles. Compare requests/second, concurrent in-flight requests, queue wait, vector DB operations, candidate count, reranker milliseconds, embedding tokens, generation tokens, cache hit rate, and error rate.
- Separate arrival rate from resource consumption. A query retrieving 10 chunks is not equivalent to one retrieving 100 chunks and reranking them. Estimate resource units per request and reconcile estimates against measured CPU/GPU time, DB work, and token usage.
- Inspect contention. Look for one tenant dominating active connections, worker slots, queue depth, database read units, or model-provider quota. Compare its share of capacity with its contracted entitlement.
- Trace the queue. Determine whether all tenants share a FIFO queue, whether a single tenant can fill it, and whether retries or background ingestion share interactive capacity.
- Check isolation correctness. Confirm tenant filters are enforced in retrieval and caches are tenant-scoped. Fair scheduling is not a substitute for authorization or data isolation.
In this incident, a shared FIFO queue and a global concurrency semaphore allowed the burst to occupy 84% of retrieval slots. Per-tenant request counts were logged, but no scheduler used them; a 100-candidate request consumed roughly five times the retrieval work of a normal request.
Engineering solution#
Use layered controls. No single requests-per-second limit is sufficient.
1. Define a resource contract for each tenant#
Create a versioned tenant policy containing:
- Sustained rate: average admitted work over a rolling interval.
- Burst allowance: a bounded token-bucket balance that absorbs short spikes.
- Concurrency ceiling: maximum simultaneous in-flight work.
- Weighted resource budget: units for vector search, reranking, embedding, generation tokens, and storage/egress where relevant.
- Queue limits and deadline: maximum queued work and maximum wait before rejection or graceful degradation.
- Priority class and share: contractual weight, not an informal assumption based on tenant size.
- Isolation tier: shared pool, reserved pool, or dedicated deployment for exceptional workloads.
Set quotas from measured capacity, service commitments, and pricing. A quota should protect other customers and make overages predictable—not silently promise more capacity than the system owns.
2. Estimate cost, then reconcile actual cost#
At admission, estimate a request's cost from features known before expensive work: requested top-k, corpus or shard fan-out, query type, expected reranker use, context budget, and workload class. Use a normalized resource vector rather than pretending all work is one scalar:
- retrieval units (for example, shard probes or calibrated DB work);
- reranker milliseconds or accelerator-seconds;
- embedding and generation input/output tokens;
- concurrency slot-time;
- optional storage and network units.
A simple scalar scheduling weight can be useful for queue selection, but enforce hard limits independently for bottleneck resources. Otherwise a request can remain within its token budget while exhausting database connections.
After execution, record actual usage and reconcile the estimate. Update tenant usage and estimation error. Apply conservative estimates for unknown or adversarial workloads; do not let clients declare their own cheap cost.
3. Apply token buckets and concurrency limits per tenant#
A token bucket controls rate and burst. For tenant i, let the bucket refill at resource units/second up to burst capacity . Admit a request only if its estimated cost can be paid and the tenant has an available concurrency slot. If not, queue within its bounded queue or return a clear 429/503 with Retry-After where appropriate.
Use a distributed, atomic quota service or carefully partitioned local budgets with bounded overshoot. A per-process counter is not a global quota when requests can land on many replicas. Account for replication lag and fail safely when quota state is unavailable; the chosen fail-open/fail-closed behavior should reflect the risk and service tier.
4. Schedule fairly across tenants#
Do not dispatch a single shared FIFO queue. Classify requests by trusted tenant and workload class, then use a fair scheduler such as weighted fair queuing (WFQ) or deficit round robin (DRR).
- WFQ intuition: each tenant receives service in proportion to its configured weight while backlogged. A tenant with weight 3 should receive roughly three times the service of a backlogged tenant with weight 1 over a sufficiently long interval, subject to caps and available capacity.
- DRR intuition: each tenant accumulates a deficit credit each scheduling round. A request is dispatched when its estimated cost fits the tenant's credit. This handles variable-sized requests more naturally than round-robin by request count.
- Maintain bounded per-tenant queues, and use queue aging or a maximum-wait policy to prevent starvation.
- Separate interactive queries from batch indexing, evaluations, and bulk backfills. A batch workload should not consume the slots needed for interactive retrieval.
- Keep independent concurrency pools or limits for distinct bottlenecks: vector DB, reranker, embedding provider, and generation. A single global semaphore cannot protect each constrained dependency.
A practical design combines weighted fair scheduling among eligible tenants with token-bucket admission and per-resource concurrency caps. The scheduler chooses the next eligible tenant; admission checks determine whether the request can run.
5. Borrow unused capacity without surrendering isolation#
Static reservations can waste capacity when a tenant is idle. Give each tenant a nominal share and a maximum burst/borrow ceiling. Let active tenants borrow unused capacity opportunistically, but keep a guaranteed minimum for other backlogged tenants and reclaim borrowed capacity as demand returns.
For premium or regulated workloads, use reserved worker pools or dedicated vector/compute deployments. Shared logical quotas cannot guarantee isolation from noisy neighbors in every physical bottleneck.
6. Make overload behavior explicit#
When a tenant exceeds its allowance:
- reject early before costly retrieval where possible;
- queue only within a bounded wait and queue-size budget;
- return a retry hint that respects the remaining end-to-end deadline;
- shed optional work first, such as broad fan-out or a second reranking pass, only when the product's quality policy permits;
- never bypass authorization filters or silently search another tenant's data;
- prevent retries from bypassing quota accounting or multiplying load.
Apply global admission control as well. Per-tenant fairness cannot create capacity during a cluster-wide outage. When the whole service is saturated, shed work according to priority and system health.
Numerical example: 200 concurrent retrieval slots#
Assume the shared retrieval tier has 200 safe concurrent slots. Three tenant groups have contractual weights of 3:2:5:
- Tenant A (large enterprise): weight 3, nominal share 60 slots.
- Tenant B: weight 2, nominal share 40 slots.
- All remaining tenants as a pooled group: weight 5, nominal share 100 slots.
These shares sum to 200. Within the remaining-tenants group, run another fair scheduler so one small customer cannot monopolize the group.
During the incident, Tenant A offers 620 requests/second. Its configured sustained resource budget supports 180 ordinary retrieval-equivalent requests/second, with a burst bucket allowing 60 extra units for a short spike. Its concurrency ceiling is 60 nominal slots, with a bounded temporary borrow ceiling of 20 when other groups are idle.
If A's average request consumes 1 slot for 100 ms, 60 continuously occupied slots correspond to approximately 600 such completions/second in an idealized steady state (60 / 0.1). But if its requests consume five times the slot-time, the same 60 slots deliver only about 120 requests/second. This is why request-rate limits alone misrepresent resource demand.
Suppose A's expensive burst fills its own 60 slots and exhausts its burst credits. It can wait in its bounded queue or receive a quota response; it cannot occupy B's 40 nominal slots or the other tenants' 100 slots. If B and the pooled group are idle, A may temporarily borrow available capacity up to its configured ceiling. When their traffic returns, new A work stops borrowing and the scheduler restores their shares as existing work drains.
The expected outcome is not that every request succeeds. It is that A experiences controlled throttling while unrelated tenants retain predictable access and latency. Validate the actual throughput using measured slot-time distributions; the arithmetic above is an illustration, not a capacity guarantee.
Scheduling pseudocode#
on_request(request):
tenant = resolve_tenant_from_verified_identity(request)
policy = load_cached_versioned_policy(tenant)
workload = classify_interactive_or_batch(request)
estimate = estimate_resource_vector(request)
if estimate exceeds hard per-request limits:
reject(413_or_429)
if not global_admission_available(estimate):
shed_or_queue_within_global_deadline()
if not tenant_rate_budget_available(tenant, estimate):
reject_with_retry_hint_or_bounded_queue()
if not tenant_concurrency_available(tenant, workload):
enqueue_in_bounded_tenant_queue()
return
enqueue_for_fair_dispatch(tenant, workload, estimate)
scheduler_loop():
tenant = choose_next_eligible_tenant_by_weighted_fair_or_DRR()
request = tenant.queue.head
if resource_pool_available(request.estimated_cost):
reserve_tenant_and_global_capacity_atomically()
dispatch(request)
on_completion(request, actual_usage):
release_concurrency_and_resource_reservations()
reconcile_estimated_with_actual_usage(request.tenant, actual_usage)
update_usage_ledger_and_cost_metrics()The real implementation needs atomic reservation semantics, cancellation cleanup, idempotent usage events, bounded queues, and explicit handling of partial failures. Reservations must be released on timeout, client disconnect, worker crash, and cancellation—not only on the happy path.
Trade-offs and failure scenarios#
- Strict reservations vs utilization: hard partitions improve predictability but strand idle capacity. Borrowing improves utilization but requires bounded borrowing and a reclaim policy.
- Fairness vs priority: equal service is not always correct. Contractual weights, workload criticality, and premium guarantees should be explicit and auditable.
- Request count vs resource units: richer cost models improve fairness but add estimation complexity. Start with a few measured bottlenecks and refine from actual usage.
- Central quota service vs local enforcement: centralized counters are accurate but can add latency and become a dependency. Local leases reduce overhead but permit bounded overshoot; document that bound.
- Queueing vs rejection: queues absorb bursts but increase tail latency and memory pressure. Bound queue length and wait time; reject work that cannot meet its deadline.
- Shared vs dedicated infrastructure: shared pools are economical but provide weaker physical isolation. Dedicated capacity costs more and needs operational automation.
- Tenant identity errors: incorrect identity propagation can mischarge one tenant or bypass limits. Bind identity at authentication and propagate it through signed/internal context.
- Scheduler starvation: variable-cost requests can stall if deficit accounting or aging is wrong. Test with mixed small and large jobs and adversarial arrival patterns.
- Quota rollout mistakes: a policy typo can throttle a critical customer. Version policies, validate them, canary changes, and provide an audited emergency override.
Monitoring and operational verification#
Dashboard and alert on:
- per-tenant admitted, queued, throttled, rejected, and completed work;
- resource units estimated versus actual, split by retrieval, reranking, embedding, and generation;
- per-tenant concurrency, queue depth, queue wait, and p50/p95/p99 latency;
- tenant share of each constrained resource versus entitlement;
- borrow utilization, borrow duration, and time to reclaim;
- global saturation, dependency pool saturation, timeout rate, and retry amplification;
- noisy-neighbor impact: latency/error changes for other tenants correlated with one tenant's traffic;
- quota service availability, policy version, counter drift, and accounting lag.
Use trace exemplars to move from a tenant-level spike to the exact request, retrieval fan-out, candidate count, and dependency that consumed the budget. Alert on sustained entitlement violations and on tenants whose estimated-versus-actual resource error is growing.
Prevention checklist#
- [ ] Define tenant identity from authenticated server-side claims; propagate it to every async task and downstream call.
- [ ] Maintain versioned per-tenant rate, burst, concurrency, resource, queue, and priority policies.
- [ ] Measure resource cost by stage; do not use QPS as the sole capacity metric.
- [ ] Enforce per-tenant token buckets and concurrency limits before expensive work.
- [ ] Use bounded per-tenant queues and weighted fair scheduling or deficit round robin.
- [ ] Partition interactive and batch workloads; protect each constrained dependency independently.
- [ ] Permit borrowing only within explicit ceilings and reclaim it when guaranteed demand returns.
- [ ] Reconcile estimated with actual cost and make retries, cancellations, and fan-out count toward usage.
- [ ] Load-test one noisy tenant alongside many low-volume tenants, including expensive and long-running requests.
- [ ] Test quota-service failure, worker crashes, queue saturation, policy rollout, and regional imbalance.
- [ ] Define when to move a tenant to reserved or dedicated capacity and align it with commercial commitments.
- [ ] Review fairness and tenant SLOs regularly; do not assume a policy remains fair as workload mix changes.
Key principle#
Fair multi-tenancy is resource scheduling, not just rate limiting. Authenticate the tenant, estimate and measure the work, cap each tenant's burst and concurrency, schedule backlogged tenants by explicit weights, and allow only bounded borrowing. This keeps one customer's success from becoming everyone else's outage.
Further reading#
- Kubernetes, API Priority and Fairness: priority levels, concurrency shares, fair queuing, bounded queues, and shuffle sharding.
- Google SRE, Handling Overload: per-customer limits, resource-based capacity, client throttling, and graceful overload behavior.
- Microsoft Azure Architecture Center, Considerations for Multitenant Agentic Systems: tenant-scoped resource monitoring, token usage, noisy neighbors, and dedicated capacity.
- Microsoft Azure Architecture Center, Multitenancy checklist: shared-resource isolation and noisy-neighbor mitigation.
- Microsoft Azure Architecture Center, API Management in multitenant solutions: tenant-specific rate limits and quota keys.
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?
- Your RAG API performs well for 10 concurrent users but becomes unstable at 1,000. How would you load-test and identify the first bottleneck?
- You have a strict two-second response-time budget. How would you allocate it dynamically across retrieval, reranking, and generation?
Explore other topics:Forward Deployed EngineeringLarge Language ModelsAI AgentsMLOps