Divide a request deadline across retrieval stages, prevent queued work from outliving the user and make partial results explicit.
Retrieval deadlines: cancel optional work and label incomplete evidence
One request has one deadline
A retrieval-based answer may run query parsing, lexical search, vector search, reranking, evidence packing and generation. Giving each stage its own full timeout can multiply the user's wait. Start with one end-to-end deadline and pass the remaining time to every downstream operation. Reserve time for mandatory authorization and evidence checks; optional reranking can be skipped when the budget is nearly spent. Reranker budgeting handles the quality cost of a smaller or absent rerank stage.
Admission control comes before expensive work
If the system is saturated, admitting every request can increase queueing delay for all users. Cap concurrent expensive branches, reject or shed excess optional work and return a clear retryable status when the required search cannot finish. A cancellation signal should reach the search backend and any embedding call, not merely stop waiting in the frontend while the work continues. Record queue delay separately from execution time. Shard fanout shows how one slow branch can dominate the tail.
Required evidence is not optional
A timeout in one shard or source may leave an apparently plausible top-K list that omits the only relevant document. Decide in advance whether partial results may be displayed for navigation, and label coverage when they are. Do not feed an incomplete candidate set into a confident answer without an explicit support and abstention policy. An authorization timeout should fail closed; it cannot be treated like an optional reranker. Evidence-bound answering sets the final response rule.
Budget stages by their tail behavior
Allocate deadlines using measured p95 and p99 latency per stage and query slice, not a uniform split. A rare filtered vector query may need more candidate exploration than a common lexical query. If optional work is skipped, log the decision, residual candidate count and index generation so later evaluation can separate quality changes from model changes. A fixed budget should be revisited after corpus growth, shard movement or a new embedding model. Retrieval traces hold those facts.
Exercise slow and failed branches
Simulate a delayed shard, an overloaded embedding service, a cancelled client and a permission store that does not respond. Verify that backend jobs stop, partial evidence is labeled, and private data never crosses a failed authorization boundary. Test retries with idempotency: a user retry must not create duplicate ingestion or repeated paid work. An end-to-end timeout is an operating contract, not a substitute for measuring actual answer support and recall under degraded conditions.
Worked contract
from dataclasses import dataclass
@dataclass(frozen=True)
class RetrievalStage:
name: str
estimated_ms: int
required: bool
def plan_budget(stages: list[RetrievalStage], total_ms: int
) -> tuple[list[str], list[str]]:
if total_ms <= 0:
raise ValueError("deadline must be positive")
remaining = total_ms
run, skipped = [], []
for stage in stages:
if stage.estimated_ms < 0:
raise ValueError("negative stage estimate")
if stage.estimated_ms > remaining:
if stage.required:
raise TimeoutError(f"required stage lacks budget: {stage.name}")
skipped.append(stage.name)
continue
run.append(stage.name)
remaining -= stage.estimated_ms
return run, skipped
pipeline = [RetrievalStage("authorization", 19, True),
RetrievalStage("lexical", 31, True),
RetrievalStage("vector", 39, True),
RetrievalStage("rerank", 47, False)]
assert plan_budget(pipeline, 99) == (
["authorization", "lexical", "vector"], ["rerank"])Performance and operating cost
Planning S stages takes O(S) time and O(S) output space. The example uses estimates, not actual timing or cancellation; a real service computes remaining time from a monotonic deadline and passes it to backend calls. Skipping an optional stage saves its work but may reduce ranking quality. Backend cancellation, concurrency limits and bounded queues are needed to stop abandoned work from consuming capacity. Treat missing required evidence or authorization as a failure, not as a fast answer.
Common Mistakes
- Giving every downstream stage the full request timeout.
- Stopping the HTTP wait while backend queries continue to run.
- Treating a timed-out authorization check as permission to proceed.
- Presenting incomplete shard results as if the full corpus was searched.
Validation drill
Replay 59 queries with injected delays at authorization, vector search and reranking. Record p95 latency, cancellation success, skipped stages and answer support; require explicit failure for missing mandatory work.
