Skip to article
API429 / Field notes

AI API Request Coalescing: Share Authorized In-Flight Work

Design bounded application request coalescing with exact input identity, privacy checks, per-caller deadlines and one coordinated failure decision.

Hourglass and a queue of paper request cards
Editorial photo illustration: Hourglass and a queue of paper request cards. Topic: AI API Request Coalescing: Share Authorized In-Flight Work.

AI API request coalescing lets callers share one active application-owned execution when they are authorized to receive the same result. Define exact input identity, give each caller a deadline and cancellation state, bound the waiting group, and coordinate one outcome decision. Coalescing is an opt-in application pattern; it does not establish native API429 deduplication, remote idempotency or permission to replay an uncertain generation.

Define an authorized sharing group

Start with the product's result semantics, not a hash function. A document extraction requested twice for one immutable revision may be shareable when both observers have equivalent authorization and accept the same output contract. Two people independently asking for a creative variation may require two results even when the prompt text matches. Separate audit evidence, independent samples and deliberate regeneration must not disappear into a shared group.

The Go singleflight package offers a narrow reference point: its Do operation suppresses duplicate in-flight calls for a key within a group and shares their result. It does not provide durable storage or coordination across independent application processes. A distributed deployment needs an explicitly designed ownership mechanism; copying the same map into every worker does not produce one global execution.

Control When it applies What it cannot establish
Application in-flight sharing Several permitted observers want one active result Remote acceptance after a crash
Durable operation ledger A business action must survive retries and restarts Exactly-once remote execution without the endpoint's contract
Completed-result cache A finished result remains authorized and sufficiently fresh That all identical prompts should share one business operation

Use the application idempotency ledger guide when recovery must preserve a business operation across restarts. A coalescing group may refer to that ledger, but it does not replace it. Explicitly decide whether a late observer may join, whether completed output may be reused, and how users request a fresh result. Each choice changes the product's behavior.

Preserve exact inputs and privacy boundaries

A sharing identity needs the authenticated tenant and authorization scope, endpoint, exact model identifier, prompt bytes, schema, tools, immutable files or content snapshots, retrieval snapshot and all generation parameters. Preserve the output contract, format and limits too. Equality of a short prompt hash alone is insufficient when a document, retrieval result or tool definition differs. A versioned request encoding can make comparison unambiguous without changing any submitted value.

Do not normalize whitespace, resolve model aliases into a supposedly equivalent name, round temperature values or ignore randomness merely to increase matches. These changes can alter output or hide distinct user intentions. If your application intentionally preprocesses inputs before submission, record that explicit input contract and compare the exact resulting request. Do not treat a current document URL as a frozen file: the underlying bytes may change while callers wait.

Apply authorization before joining and before delivering a shared result. Do not cross a privacy boundary because the prompt looks public or happens to match. Permissions can change while execution is in flight; a waiter that loses access must not receive the result. Shared output can contain data derived from retrieval, files or tools that was absent from the visible prompt. Include the relevant access boundary and immutable source snapshot in the decision.

Workload Possible sharing condition Reason to keep executions separate
Document extraction Same immutable document, schema and authorized result Distinct document revision or independent audit requirement
Retrieval answer Same retrieval snapshot and permitted evidence set Live retrieval changed or access scopes differ
Support summary Same ticket version, language and authorized observers New messages or restricted fields change the input
Embedding task Exact input bytes, model and preprocessing contract Different chunking or privacy boundary
Creative generation Product explicitly requests a single shared result Independent samples, intentional regeneration or separate creative outputs
Tool workflow Side effects have their own documented controls Sending, charging or writing cannot be merged by prompt similarity

Use opaque group identifiers in routine events. Exclude prompts, personal identifiers, secrets and credentials from keys and logs. Fingerprints are sensitive correlation data rather than anonymization, so restrict access and retention. If results are retained after completion, use encrypted application-authorized references and a separate cache policy. Do not make a shared result globally readable merely because its computation was shared.

Bound waiters, deadlines and memory

Atomically choose one owner for a group in the coordination scope your implementation actually supports. Only that owner may dispatch the shared execution. A caller with different input bytes or output requirements cannot join an existing group. Where a durable operation identifier is involved, a conflicting payload must be rejected through the ledger rather than dispatched as a second version of the same operation.

Each waiter keeps its own deadline and cancellation flag. Joining does not extend a caller's allowed wait, and a later caller should not inherit a response timeout that has already elapsed. Define the shared execution budget separately before dispatch. If the first caller leaves, keep or stop application observation according to policy, while recording that remote cancellation is unconfirmed unless the endpoint documents and confirms it.

Set limits for waiter count, total buffered bytes, group lifetime, output size and the number of active groups. Reject or defer excess observers through a bounded admission path. A popular key can otherwise retain thousands of sockets or copies of a large response. Deliver retained output through authorized references where appropriate; copying every streamed chunk into every waiter's private buffer can defeat your memory limits.

Streaming needs an explicit contract. A late observer may have missed earlier output, and the endpoint may not support replay or resume. Decide whether observers must join before dispatch, wait for a validated terminal result, or receive a product-level “cannot join” response. Do not invent stream offsets, async status endpoints or a promise to reconstruct lost events. The caller's wait ending does not change the execution into a rejected request.

Share failures without a retry storm

One shared failure should produce one coordinated recovery decision. If an execution receives a response that is eligible for retry under the endpoint's contract, the owner evaluates Retry-After, remaining attempts and the shared execution deadline. Do not release every observer into its own immediate retry loop. A bounded group can still create a burst if each caller independently interprets the same failure as permission to submit again.

Use the retry budget guide for 429 and 503 handling, Retry-After seconds or dates, bounded attempts and deadline reserves. First classify acceptance uncertainty. A timeout, partially received stream or accepted job without a final result requires reconciliation, not an automatic paid replay. Poll or resume only where the exact endpoint documents it. A fallback model represents another potential generation and must meet the same input, authorization and output requirements.

When a local in-flight entry is removed, that only means the local group ended. An empty map after restart is not proof that the old execution never happened. If recovery requires a durable ledger, keep completed and unknown tombstones across the supported replay window, and require review when identity retention expires. Lease expiry cannot prove remote absence. Fencing tokens can guard application writes only where your storage enforces them; they cannot guarantee exactly-once execution at another service.

Read the API429 documentation and public API reference for the endpoint contract, and confirm exact model identifiers and supported parameters through the model catalog. An arbitrary header is not evidence of a remote sharing feature. The cost guardrails guide helps separate application accounting for attempts, retained results and successful business actions. The public FAQ covers customer-facing service questions.

Synthetic burst walkthrough

Imagine three authorized observers requesting the extraction for the same frozen document revision and schema. This is a proposed application scenario, not an API429 experiment. Observer A atomically creates the group and becomes its execution owner. Observer B joins after exact request and access checks. Observer C asks for a different schema and receives a separate-operation decision rather than an answer that fits only A's schema.

B's deadline expires while A is still waiting. B detaches and releases its buffers; A's operation remains in flight. The application must not claim that B's timeout cancelled remote generation. A fourth observer from another tenant is denied access to the existing group even if the document bytes happen to match. A later “generate another version” action also stays separate because it requests a new result.

Suppose the owner loses its connection after receiving part of a stream. It records uncertainty in the associated durable operation, preserves authorized partial evidence, and tells remaining observers that completion is unresolved. It does not hand every observer a fresh retry token or erase the operation on a short TTL. If a supported lookup later confirms completion, the application validates the output and serves eligible observers under current access checks. Without that evidence, a controlled recovery decision remains necessary.

After a result is available, an optional cache may serve it only within its own freshness, authorization and retention policy. Writing the result to a CRM or sending an email remains a downstream operation requiring a destination-supported unique key, transaction, outbox and reconciliation as appropriate. Sharing one generation cannot guarantee that a third-party effect happens once, and no local transaction automatically spans both services.

Proposed application acceptance checks

These checks belong to the application implementation; they are not performed API429 trials or performance benchmarks. Exercise decisions at ownership, authorization and delivery boundaries, including the points where an observer leaves or a process crashes.

Scenario Application acceptance condition
Concurrent same-group admission One owner dispatches within the explicitly supported coordination scope
Changed prompt, model, schema, tools or snapshot The caller cannot join a mismatching result
Intentional regeneration A new operation remains independent despite identical bytes
Different tenant or revoked authorization No result or sensitive correlation data crosses the boundary
Deadline or cancellation Only that observer detaches; remote cancellation is not presumed
Hot key or large output Waiters and buffers stay within configured bounds
Shared 429 or 503 One bounded owner policy handles recovery without independent retry storms
Partial stream or lost acceptance evidence The operation stays uncertain; no automatic paid replay
Restart, expired lease or late owner Lost memory cannot authorize replay; stale application writes are fenced
Downstream CRM, email or payment Destination evidence resolves delivery uncertainty before another effect

FAQ

Is coalescing the same as caching?

Coalescing coordinates an active execution. Caching reuses a completed result under a separate reuse policy. A product can support both, but deleting an in-flight entry does not authorize replay of an unresolved operation.

Can identical prompts always share an answer?

No. Authorization, source snapshots, exact model and parameters, output contracts and the user's intended operation all matter. Independent creative results and separate audit evidence need separate executions when the product requires them.

Does singleflight coordinate every worker in a deployment?

A group in one process does not coordinate independent processes or survive their restarts. Define the supported ownership scope explicitly and use a durable operation design when recovery must cross that boundary.

What if every waiter cancels?

Release local observation resources according to policy, but retain the evidence required for recovery. Cancellation is not proof that remote work stopped. Only a documented and confirmed endpoint cancellation contract can establish that outcome.

Runnable offline Python 3.10+ singleflight verification

The following self-contained Python 3.10+ standard-library module simulates application-owned request coalescing for POST /v1/chat/completions with exact tenant, authorization, schema and snapshot fingerprinting, bounded waiter admission, independent caller deadline detachment and preserved timeout uncertainty:

from __future__ import annotations

from dataclasses import dataclass, field
import hashlib
import json
from typing import Literal

JoinDecision = Literal[
    "owner_dispatched",
    "joined_in_flight",
    "rejected_group_full",
    "separate_execution_required",
    "detached_caller_deadline",
    "unresolved_unknown_timeout",
]


@dataclass(frozen=True)
class CoalesceRequest:
    tenant_id: str
    auth_scope: str
    endpoint: str
    model_id: str
    prompt_bytes: str
    schema_version: str
    snapshot_id: str
    temperature: float
    force_fresh: bool = False

    def group_fingerprint(self) -> str:
        payload = json.dumps(
            {
                "v": 1,
                "tenant_id": self.tenant_id,
                "auth_scope": self.auth_scope,
                "endpoint": self.endpoint,
                "model_id": self.model_id,
                "prompt_bytes": self.prompt_bytes,
                "schema_version": self.schema_version,
                "snapshot_id": self.snapshot_id,
                "temperature": self.temperature,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode("utf-8")).hexdigest()


@dataclass
class InFlightGroup:
    fingerprint: str
    owner_caller_id: str
    max_waiters: int
    waiter_deadlines_ms: dict[str, int] = field(default_factory=dict)
    state: Literal["in_flight", "completed", "unknown_timeout"] = "in_flight"
    retry_after_ms: int = 0


class SingleflightCoordinator:
    def __init__(self, max_waiters_per_group: int = 2) -> None:
        self.max_waiters_per_group = max_waiters_per_group
        self.groups: dict[str, InFlightGroup] = {}

    def submit_or_join(
        self, caller_id: str, req: CoalesceRequest, caller_deadline_ms: int
    ) -> tuple[JoinDecision, str]:
        if req.force_fresh:
            return ("separate_execution_required", f"fresh:{caller_id}")

        fp = req.group_fingerprint()
        group = self.groups.get(fp)
        if group is None:
            new_group = InFlightGroup(
                fingerprint=fp,
                owner_caller_id=caller_id,
                max_waiters=self.max_waiters_per_group,
                waiter_deadlines_ms={caller_id: caller_deadline_ms},
            )
            self.groups[fp] = new_group
            return ("owner_dispatched", fp)

        if group.state == "unknown_timeout":
            return ("unresolved_unknown_timeout", fp)

        if len(group.waiter_deadlines_ms) >= group.max_waiters:
            return ("rejected_group_full", fp)

        group.waiter_deadlines_ms[caller_id] = caller_deadline_ms
        return ("joined_in_flight", fp)

    def detach_expired_waiter(self, fp: str, caller_id: str, elapsed_ms: int) -> JoinDecision:
        group = self.groups[fp]
        deadline = group.waiter_deadlines_ms.get(caller_id)
        if deadline is not None and elapsed_ms >= deadline:
            del group.waiter_deadlines_ms[caller_id]
            # Detaching one waiter does not cancel the remote POST /v1/chat/completions call
            return "detached_caller_deadline"
        raise ValueError("Waiter deadline has not elapsed")

    def mark_owner_timeout_uncertainty(self, fp: str) -> JoinDecision:
        group = self.groups[fp]
        group.state = "unknown_timeout"
        return "unresolved_unknown_timeout"


if __name__ == "__main__":
    coord = SingleflightCoordinator(max_waiters_per_group=2)
    base_req = CoalesceRequest(
        tenant_id="tenant-a",
        auth_scope="doc:read:rev-7",
        endpoint="POST /v1/chat/completions",
        model_id="gemini-3.8-flash",
        prompt_bytes="Extract invoice totals",
        schema_version="invoice-v2",
        snapshot_id="sha256:doc-rev-7",
        temperature=0.0,
    )

    d1, fp1 = coord.submit_or_join("caller-a", base_req, caller_deadline_ms=3000)
    d2, fp2 = coord.submit_or_join("caller-b", base_req, caller_deadline_ms=1200)
    assert d1 == "owner_dispatched" and d2 == "joined_in_flight" and fp1 == fp2

    # Bound waiter count: a third waiter on the same hot key is rejected cleanly
    d3, _ = coord.submit_or_join("caller-overflow", base_req, caller_deadline_ms=2500)
    assert d3 == "rejected_group_full"

    # A different schema or tenant produces a distinct fingerprint and cannot join A's group
    diff_schema = CoalesceRequest(**{**base_req.__dict__, "schema_version": "invoice-v3"})
    d_schema, fp_schema = coord.submit_or_join("caller-c", diff_schema, caller_deadline_ms=3000)
    assert d_schema == "owner_dispatched" and fp_schema != fp1

    # Caller B's local deadline expires first; B detaches while owner A remains in flight
    assert coord.detach_expired_waiter(fp1, "caller-b", elapsed_ms=1500) == "detached_caller_deadline"
    assert "caller-a" in coord.groups[fp1].waiter_deadlines_ms

    # If the owner connection drops mid-stream, the group records uncertainty rather than replaying
    assert coord.mark_owner_timeout_uncertainty(fp1) == "unresolved_unknown_timeout"
    d_late, _ = coord.submit_or_join("caller-late", base_req, caller_deadline_ms=3000)
    assert d_late == "unresolved_unknown_timeout"
    print(json.dumps({"status": "ok", "shared_fingerprint_prefix": fp1[:12]}))

Sources & further reading

  1. Go singleflight package — Duplicate in-flight call suppression
  2. API429 documentation
  3. API429 public API reference

Put the next step into practice.

Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.

Telegram