Some LLM traffic arrives in bursts of identical requests. A dashboard loads and ten widgets ask the same question. A user double-clicks "Summarize". A scheduled report fans out to a hundred subscribers who share one underlying document. A retry layer re-sends a request while the original is still running. Each of these produces several concurrent calls with the same inputs, and you pay for all of them and wait on all of them.
A response cache does not help here, because the first answer has not been written yet. Every duplicate arrives while the original is still in flight, misses the cache, and goes upstream. This is the thundering-herd problem, and the fix is older than LLMs: single-flight, also called request coalescing. The first caller starts the call, later callers with an identical key wait for that same call, and everyone gets the same result. This article builds one, then covers where it quietly goes wrong.
Coalescing is not caching
The two mechanisms answer different questions.
- A cache stores a finished result and serves it for some time afterwards. Its risks are staleness and storing data longer than intended.
- Single-flight holds no result once the call completes. Its entry exists only while the call is running and is deleted the moment it finishes. The next request after that starts a fresh call.
That second property is why coalescing is often easier to justify than caching. There is no TTL to choose, no invalidation problem, and nothing persisted. The only claim you make is: "these callers asked for the same thing at the same moment, so one answer is acceptable for all of them." The two compose well: check the cache, and on a miss go through single-flight, then populate the cache.
A minimal implementation
Here is a small asyncio version. It has three details that matter, and each one corresponds to a failure mode covered below.
import asyncio, hashlib, json
class SingleFlight:
def __init__(self):
self._inflight: dict[str, asyncio.Task] = {}
async def do(self, key, fn):
task = self._inflight.get(key)
if task is None:
task = asyncio.ensure_future(fn())
self._inflight[key] = task
task.add_done_callback(lambda _t: self._inflight.pop(key, None))
# shield: one waiter being cancelled must not cancel the shared call
return await asyncio.shield(task)
def flight_key(tenant, model, params, messages):
blob = json.dumps([tenant, model, params, messages],
sort_keys=True, separators=(",", ":"))
return hashlib.sha256(blob.encode()).hexdigest()Usage is one line around your existing call: await flights.do(flight_key(...), lambda: call_llm(...)).
I ran this against a fake model call that sleeps for 200 ms. Twenty concurrent identical requests produced one upstream call and twenty identical results. When one of two waiters was cancelled mid-flight, the other still received its answer and the upstream call count stayed at one. A request issued after completion made a new upstream call, confirming nothing was cached. Reproduce those three checks with your own client before trusting any variant of this code, because each one fails in a naive implementation.
What goes into the key
The key decides who shares an answer, so a key that is too coarse is a correctness and security bug, and one that is too fine saves nothing.
Include everything that can change the output or its audience:
- the tenant or user identity, or whatever scopes visibility of the content. Two tenants may send byte-identical prompts, but if either response is later enriched with tenant data, or logged and billed per tenant, they should not share a call. When in doubt, scope by tenant.
- the model identifier, and any sampling parameters such as temperature, maximum output tokens and stop sequences
- the full message list, including the system prompt and any tool definitions
- the prompt template version, if the template is rendered after the key is computed
Hash the canonical form. Serializing with sorted keys and fixed separators means {"a":1,"b":2} and {"b":2,"a":1} coalesce. Normalize whitespace only if you are certain your prompt treats it as insignificant.
Do not include request IDs, timestamps or trace IDs. Those differ on every request and would make every key unique. Pass them out of band instead.
A useful test: take a production request, change one field at a time, and assert whether the key changes. Fields that affect output must change it; trace metadata must not. Keep this as a unit test, because someone will add a parameter to the request builder next quarter and forget the key.
When sharing one answer is wrong
Coalescing assumes that identical inputs deserve identical outputs. For LLM calls that assumption is sometimes false.
Callers who want variety. If a feature deliberately samples at a high temperature so that retries or "regenerate" buttons produce different text, coalescing hands every caller the same sample. Exclude those calls from coalescing, or include a per-request nonce in the key for the regenerate path. The same applies to majority-vote or self-consistency setups that rely on several independent samples: if you coalesce them, you silently collapse N samples into one and lose the vote.
Deliberate retries. A user pressing "try again" after a bad answer while the first call is still running will join the bad call. Decide whether retry-after-complaint should bypass coalescing, which in practice means a flag that adds a nonce.
Tool-using agents with side effects. Coalescing the model call is usually safe, because the model call is a pure function of its inputs plus randomness. Coalescing the tool execution that follows is a different matter. Two agent runs that share a model response must still each execute, or explicitly deduplicate, their own side effects under their own idempotency keys. Do not let a coalesced response cause one email to be sent when two users each expected their own.
Failure behavior
Four situations deserve an explicit decision rather than whatever the code does by default.
Errors fan out. If the shared call fails, every waiter receives that failure. That is correct for a deterministic error such as a validation rejection. It is a poor outcome for a transient one, such as a timeout, because a single unlucky call now fails twenty users at once. A reasonable policy: let each waiter retry on its own after a transient error, with jittered backoff, so that the retries do not re-synchronize into a new herd. Note that the first retry will itself coalesce, which is usually what you want.
Cancellation. Without asyncio.shield, cancelling the first caller cancels the task that every other caller is awaiting. That is the most common bug in hand-rolled versions. The inverse problem is a call nobody wants anymore: if all waiters cancel, the upstream call keeps running and you pay for it. Track a waiter count and cancel the task when it reaches zero, if your provider charges for abandoned generations.
Timeouts. A waiter that joins late should not inherit the full original timeout. Give each waiter its own deadline around the shared await, so a call that has already run for 25 of 30 seconds does not hold a late joiner for another 30. If the shared call outlives a waiter's deadline, that waiter gets a timeout while the others continue.
Streaming. Coalescing a streamed response requires buffering chunks so that a late joiner can replay what it missed and then follow live output. That is more machinery than the example above. If your responses stream, consider coalescing only the non-streaming paths first, such as batch jobs and background summaries, where one shared final value is enough.
Scope: single process or fleet
The example coalesces within one process. If you run twenty replicas behind a load balancer, identical requests that land on different replicas do not share a call. That is often still a large win, because a burst often arrives over one reused connection and so reaches a single replica, and in-process logic has no network hop and no new failure mode. Going cross-process requires a distributed lock or claim record with an expiry, which brings its own failure modes: a crashed lock holder, clock assumptions, and waiters polling. Add that only after measuring that duplicate in-flight calls across replicas are a meaningful share of your spend.
Measure before and after. Count upstream calls and coalesced waiters as separate metrics, and compute the coalesce ratio per feature. If it sits near zero for a feature, remove the layer for that path; it is adding a code path with no benefit.
Checklist
- Confirm the problem first: log duplicate keys arriving within the same few seconds and see how common they are.
- Build the key from tenant, model, parameters and the full message list; exclude trace metadata.
- Unit-test that each output-affecting field changes the key and each metadata field does not.
- Shield the shared task so one waiter's cancellation cannot kill it; decide what happens when all waiters leave.
- Give each waiter its own deadline.
- Let transient errors be retried per waiter with jitter; let deterministic errors fan out.
- Exclude calls that rely on independent samples, "regenerate" actions, and side-effecting tool execution.
- Emit upstream-call and coalesced-waiter counts, and review the ratio per feature.
- Start in-process; go distributed only if the numbers justify it.
Comments (0)
No comments yet — be the first.
Sign in to leave a comment.