How In-Flight Singleflight Deduplication Works for LLM APIs
Singleflight coalesces concurrent, identical requests that arrive while the same computation is already in flight so only one upstream LLM call executes and all callers share its result—avoiding duplicate token spend, redundant rate-limit consumption, and thundering-herd spikes on cache misses.
- Coalesces concurrent work, not long-term cache storage: Unlike a response cache that serves historical results over TTLs, singleflight deduplicates active in-flight promises/calls sharing the same canonical request key; once the call settles, the in-flight entry is removed (optionally paired with a short-TTL result cache afterward).
- Deterministic canonical request keys: Two requests are “identical” only when every semantic input matches—model, temperature/top-p, system instructions, tool schemas, response format, and normalized messages—while excluding non-deterministic metadata like request IDs or timestamps.
- Shared settlement and error propagation: In Node.js/TypeScript, storing a
Promisein an in-flightMapand deleting it in a.finally()block lets concurrent callersawaitthe same promise, receiving either the resolved output or the shared error.
Steps to Implement Singleflight Deduplication in Node.js / TypeScript
- Build a canonical deduplication key: Hash or serialize the exact request parameters (
model,messages,tools,response_format,temperature) into a deterministic key so semantically different requests never collide. - Look up an active in-flight promise by key: Check
inFlight.get(key)before calling the LLM client; if present, return the existing promise immediately instead of starting a new upstream request. - Register the new promise and clean up in
.finally(): Store the newly created promise ininFlight.set(key, promise)and always deletekeyin.finally()so failures or completions never leave stale entries stuck in memory. - Combine with short-TTL caching and per-caller timeouts carefully: Pair singleflight with a short-lived response cache for repeated queries, and avoid letting one caller’s abort cancel a shared promise still needed by other awaiting callers.
TypeScript Example: Singleflight Coalescer for LLM Completions
import { createHash } from "node:crypto";
import OpenAI from "openai";
const openai = new OpenAI();
type ChatCreateParams = OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming;
function buildRequestFingerprint(params: ChatCreateParams): string {
const canonicalPayload = {
model: params.model,
messages: params.messages,
tools: params.tools ?? null,
tool_choice: params.tool_choice ?? null,
response_format: params.response_format ?? null,
temperature: params.temperature ?? null,
max_tokens: params.max_tokens ?? null,
max_completion_tokens: params.max_completion_tokens ?? null,
};
return createHash("sha256")
.update(JSON.stringify(canonicalPayload))
.digest("hex");
}
export class LlmSingleflight {
private readonly inFlight = new Map<string, Promise<OpenAI.Chat.Completions.ChatCompletion>>();
async createChatCompletion(params: ChatCreateParams): Promise<{
completion: OpenAI.Chat.Completions.ChatCompletion;
deduplicated: boolean;
}> {
const key = buildRequestFingerprint(params);
const existing = this.inFlight.get(key);
if (existing) {
const completion = await existing;
return { completion, deduplicated: true };
}
const promise = openai.chat.completions.create(params).finally(() => {
if (this.inFlight.get(key) === promise) {
this.inFlight.delete(key);
}
});
this.inFlight.set(key, promise);
const completion = await promise;
return { completion, deduplicated: false };
}
}
Helpful Tips for Production Singleflight LLM Layers
- Only deduplicate deterministic or idempotent calls (
temperature: 0or read-only lookups): Coalescing high-temperature creative generations or requests with side-effecting tools can surprise callers expecting distinct samples or fresh tool execution. - Do not bind a shared in-flight call to a single caller’s
AbortSignal: If Caller A aborts while Caller B is still waiting on the same key, aborting the shared upstream request breaks Caller B; pass an independent controller for the shared call and race each caller’s signal locally. - Scope keys by tenant/auth context when data is private: Include
tenantIdor permission scope in the fingerprint whenever prompts contain user- or tenant-specific context so cross-tenant data leakage is impossible.
You must log in or register to comment.
