The request-dedup bug that can leak one user's data to another

Request deduplication is one of those tricks that looks free. Two components ask for the same thing at the same moment, so you send one request instead of two and hand both of them the same answer. Faster page, less load on the server, nobody complains.
It is free right up until the moment two different people ask for the same thing at the same moment.
Then the second person gets the first person’s data. Not a cached copy of it later — their actual response, right now, in their browser. And every test you are likely to write passes, because tests run as one user.
Here is a version you can run, why it happens, and the one change that closes it.
Run the bug yourself
No libraries. Just Node. Save this as leak.mjs:
// A tiny deduplicator. The bug is in here.
const inflight = new Map()
function dedupe (key, run) {
if (inflight.has(key)) return inflight.get(key)
const p = run().finally(() => inflight.delete(key))
inflight.set(key, p)
return p
}
// Pretend server: gives back the account the token belongs to.
function getSettings (token) {
return new Promise(resolve => {
setTimeout(() => resolve({ owner: token, theme: 'dark' }), 50)
})
}
// The key only knows WHAT was asked for.
const key = req => `${req.method} ${req.url}`
const alice = { method: 'GET', url: '/api/account/settings', token: 'alice' }
const bob = { method: 'GET', url: '/api/account/settings', token: 'bob' }
const aliceResult = dedupe(key(alice), () => getSettings(alice.token))
const bobResult = dedupe(key(bob), () => getSettings(bob.token))
console.log('alice got:', await aliceResult)
console.log('bob got: ', await bobResult)Run it:
$ node leak.mjs
alice got: { owner: 'alice', theme: 'dark' }
bob got: { owner: 'alice', theme: 'dark' }Bob asked for Bob’s settings. Bob got Alice’s.
Why it happens
Read the deduplicator again. It is doing exactly what it was built to do.
Alice calls first. There is no entry for GET /api/account/settings, so it runs the request and stores the promise under that key.
Bob calls 1 millisecond later. There is an entry for GET /api/account/settings, so it returns that promise. Not a copy. The same promise object Alice is waiting on.
The request that actually went out over the network was Alice’s — with Alice’s token. Bob never sent anything. He just stood next to Alice’s answer and read it.
The key was built from method and URL. Both requests had the same method and the same URL. As far as the map is concerned, they were the same request.
They were not the same request. They were two different people asking the same question, which is a completely different thing.
The part that makes this hard to catch
Nothing here is a crash. There is no error in your logs, no 500, no failed test. The response Bob gets is a perfectly valid, well-formed, HTTP 200 response. It is just somebody else’s.
And it only happens when the two calls overlap. If Bob arrives 100ms later, after Alice’s request has settled and the entry has been deleted, everything is correct. So the bug needs timing to show up, which means a normal test suite — one user, one request at a time — will never see it.
That combination (silent, correct-looking, timing-dependent) is why this has to be fixed in the key itself and not by a check somewhere.
The fix
Put who is asking into the key.
const key = req => `${req.method} ${req.url} ${req.token}`That is the whole fix. Run it again:
$ node fixed.mjs
alice got: { owner: 'alice', theme: 'dark' }
bob got: { owner: 'bob', theme: 'dark' }Two different keys now, so no sharing, so two real requests. Alice and Bob each get their own data.
What you must not do instead is check the identity after the fact — look up the shared promise, then compare tokens, then decide whether to return it. That is two steps, and anything can arrive between them. If the key is right, there is nothing to check.
How this looks in real code
In api-client — the HTTP client I wrote so I would stop rewriting lib/api.ts in every project — the key builder is this, and the comment on the last field is there because it is the whole reason the field exists:
export function computeDedupeKey(input: {
method: string;
url: string;
body?: unknown;
tenantId?: string;
authFingerprint?: string;
}): string {
const parts = [
input.method.toUpperCase(),
input.url,
stableSerialize(input.body),
input.tenantId ?? '',
input.authFingerprint ?? '',
];
return fnv1a(parts.join(' '));
}Three things in there are worth copying.
The fingerprint is hashed, not stored. authFingerprint is a string like bearer:<the token>. That string never becomes the map key by itself — every part gets joined and run through FNV-1a, so what ends up in the map is eight hex characters. The token is used to tell two callers apart, not kept lying around as a key you might print in a log line.
tenantId gets the same treatment. Same URL, same body, different tenant is just as wrong to collapse as different user. One layer up, same mistake.
Different credential, different key. That is the behaviour, measured against the real build:
computeDedupeKey({ method: 'get', url: '/api/account/settings', authFingerprint: 'A' })
// 1ba47ba9
computeDedupeKey({ method: 'GET', url: '/api/account/settings', authFingerprint: 'B' })
// 18a476f0Same method, same URL, different person, different key. Nothing to share.
The small detail that is easy to get backwards
Look at stableSerialize(input.body). That is not plain JSON.stringify.
function stableSerialize(value: unknown): string {
if (value === undefined) return 'undefined';
return (
JSON.stringify(value, (_key, val: unknown) => {
if (val && typeof val === 'object' && !Array.isArray(val)) {
const record = val as Record<string, unknown>;
const sorted: Record<string, unknown> = {};
for (const key of Object.keys(record).sort()) {
sorted[key] = record[key];
}
return sorted;
}
return val;
}) ?? 'null'
);
}JavaScript keeps object keys in the order you wrote them. So a body built as a then b stringifies differently from the same body built as b then a, even though they mean exactly the same thing. Plain JSON.stringify would give you two different strings, two different keys, and two requests where one would have done.
Sorting the keys first fixes it. Measured, with nested objects in a different order each time:
POST /x { a: 1, b: { y: 2, x: 3 } } -> 693dbc30
POST /x { b: { x: 3, y: 2 }, a: 1 } -> 693dbc30Same key. This one is not a security bug — the worst case is a duplicate request you meant to avoid — but it is the same discipline: the key has to be a function of meaning, not of typing order.
And the hash is FNV-1a on purpose. Not crypto.randomUUID(), not anything seeded per process. A dedup key has to come out identical every time, on every machine, after every restart. A random seed would quietly turn deduplication off everywhere it matters most — multiple instances behind a load balancer, exactly the place you wanted it.
What happens when it cannot tell who is asking
There is one more case that only shows up once you take this seriously: what if you cannot work out the fingerprint? The token getter throws, the refresh fails, something is misconfigured.
The tempting answer is to fall back to a key without the identity in it. That is the original bug with extra steps.
The client does the opposite — if the fingerprint comes back null, deduplication and caching are both switched off for that request:
let fp: string | null = 'none';
if (cacheConfigured || dedupApplies) fp = await authFingerprint(resolved.auth);
const scopable = fp !== null;
const withDedup = <R>(work: () => Promise<R>): Promise<R> => {
if (!dedupApplies || !scopable) return work();
// ...build the key, then share it
};When it does not know who is asking, it stops sharing. You lose an optimisation. You do not hand somebody the wrong data.
One more thing: who gets to cancel
Once several callers share one promise, a question appears that a normal request never has to answer. One component unmounts and wants to cancel. Three others are still waiting. Who wins?
Not the one who spoke. Each caller increments a count when it attaches and calls release() when it stops caring, and release() only says “yes, really cancel” when the count hits zero:
function release(key: string): boolean {
const entry = entries.get(key);
if (!entry) return false;
entry.count -= 1;
return entry.count <= 0; // true only if THIS was the last one
}Running two subscribers through it, the first release reports false and the second reports true. Cancellation is a vote, not an order, because the promise does not belong to any single caller.
The short version
If you are deduplicating or caching requests, look at how your key is built right now.
If it is made only from what is being asked for — method, URL, body — and not from who is asking, you do not have an optimisation. You have a way for one person’s response to land in a different person’s browser, any time the two of them happen to click at the same moment.
Identity is not something you attach after the key is computed. It has to be inside the key, or the “same request” you are collapsing was never the same request at all.