How do you deduplicate identical concurrent LLM API requests in flight using single flight caching in Go or Node.js? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

How do you deduplicate identical concurrent LLM API requests in flight using single flight caching in Go or Node.js?

message-square
0
1
How do you deduplicate identical concurrent LLM API requests in flight using single flight caching in Go or Node.js?
How do you deduplicate identical concurrent LLM API requests in flight using single flight caching in Go or Node.js? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

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 Promise in an in-flight Map and deleting it in a .finally() block lets concurrent callers await the same promise, receiving either the resolved output or the shared error.

Steps to Implement Singleflight Deduplication in Node.js / TypeScript

  1. 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.
  2. 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.
  3. Register the new promise and clean up in .finally(): Store the newly created promise in inFlight.set(key, promise) and always delete key in .finally() so failures or completions never leave stale entries stuck in memory.
  4. 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: 0 or 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 tenantId or permission scope in the fingerprint whenever prompts contain user- or tenant-specific context so cross-tenant data leakage is impossible.