Oswaldo Gonzalez

Stop paying twice for the same AI answer

If you have many customers asking for the same thing, you may be paying for the same AI answer many times over. A request already on its way to get an answer shouldn't have a twin starting from zero.

Illustration: many identical requests share a single model call
Identical requests wait for the same result.

The business case

Duplicate AI calls cost money and use up your rate limit. Request coalescing makes identical requests share one call, so you pay less and popular pages respond sooner. How much you save depends on how often requests truly match, so measure that first. Set up carelessly, it can show one customer another customer's data.

Jump to: the implementation / questions for your team

A popular page goes live. The cached summary has expired. In the seconds it takes the model to write a new one, 40 users arrive, and each one misses the cache and starts its own call. You pay for 40 answers, burn through your rate limit, and every user waits the full time. You needed one call.

This is a cache stampede, and caching can't save you from it, because a cache only helps once the answer exists. The gap is the time while the answer is being made. Slow, expensive work makes that gap wide, and few things are slower or more expensive per call than a model.

The fix is request coalescing, also called single-flight. The first request does the work. Identical requests that arrive before it's done wait for that same result.

The code

In C#, a Task is already something many callers can await. So you keep a dictionary of work in progress.

public sealed class SingleFlight<T>
{
    private readonly ConcurrentDictionary<string, Lazy<Task<T>>>
        _inFlight = new();

    public Task<T> RunAsync(
        string key, Func<Task<T>> work, CancellationToken ct)
    {
        var call = _inFlight.GetOrAdd(key, k =>
            new Lazy<Task<T>>(() => RunAndForgetAsync(k, work)));

        return call.Value.WaitAsync(ct);
    }

    private async Task<T> RunAndForgetAsync(
        string key, Func<Task<T>> work)
    {
        try
        {
            return await work();
        }
        finally
        {
            _inFlight.TryRemove(key, out _);
        }
    }
}

Two details do the heavy lifting.

Lazy is there because GetOrAdd can run its factory twice when two threads race. Only one Lazy gets stored, so only one model call starts.

WaitAsync(ct) means each caller can stop waiting on its own terms, without stopping the shared work.

The entry is removed when the work finishes. That's the difference from a cache: this holds nothing once the answer is out. Put it in front of your cache if you also want to keep the result.

The key is where you get hurt

Two requests may share a result only if they really are the same request. Everything that can change the answer has to be in the key.

var input = string.Join(
    '\n', tenantId, model, temperature, prompt);
var key = Convert.ToHexString(
    SHA256.HashData(Encoding.UTF8.GetBytes(input)));

var answer = await singleFlight.RunAsync(
    key,
    () => llm.CompleteAsync(
        model, prompt, temperature, shutdownToken),
    request.Aborted);
Tenant, model, temperature and prompt combine into one hashed key
If a value can change the answer, it belongs in the key.

Look at tenantId. If it's missing and the prompt contains one customer's data, another customer could receive that answer. That's a data leak created by a performance feature, so scope keys to the tenant or user unless the content is truly public.

Coalescing also has to see the same prompt to match. A timestamp or a request ID in your system prompt makes every key unique and the savings vanish without an error. Log your hit rate so you'd notice.

Cancellation has a trap

Notice that the model call gets shutdownToken, while the wait gets request.Aborted. Pass the first user's cancellation token into shared work, and when that user closes their tab, the call dies for the other 39 people waiting on it. Shared work can't belong to one caller.

When not to use it

Remember that failure is shared too. If the call fails, all 40 callers get the same exception. That's usually what you want during an outage, since it stops the pile-on described in the retry storm post. Just don't let all 40 retry at once and recreate the problem.

More than one server

This class coalesces within one process. Run 20 servers and you can still get 20 calls, which may be fine: going from 800 calls to 20 is most of the win.

If you need one call across the fleet, you need something shared. A Redis lock with a short expiry works, with waiters reading the result when it lands. Orleans fits this particularly well, because a grain per key gives you one activation handling that key, so the coalescing comes with the model. If you only want it for cache misses, HybridCache in .NET includes stampede protection.

Start with the in-process version and measure. You may find it's all you need.

Questions to ask your team

The first question is usually a cheap one to answer, and it tells you whether this is worth doing. I build and run AI systems that keep working under heavy load, with this kind of cost in mind. Send me a message on LinkedIn with what yours does, and we can work out where to look first.