Kā izveidot pakalpojumu sniedzējam neitrālu tīmekļa aizķeres slāni Async LLM darbiem
Praktiska arhitektūra, lai pārvērstu vietējo nodrošinātāju tīmekļa aizķeres un aptaujātos pakešu stāvokļus vienā drošā, izturīgā un atkārtoti atskaņojamā atzvanīšanas līgumā asinhroniem LLM darbiem.
An async LLM API should not force customers to know which provider sends webhooks, which requires polling, or how each one represents completion. Customers need one dependable contract: submit a job, receive a signed terminal-state event, and retrieve the result through the gateway.
Delivering that contract requires more than translating provider payloads. The gateway must own job state, event identity, retry history, endpoint security, and recovery. Provider notifications should trigger reconciliation, not become customer callbacks directly.
Why direct provider-to-customer forwarding fails
Providers expose different completion mechanisms. OpenAI supports signed webhook notifications for supported operations, including background responses and batches. Anthropic documents retrieving Message Batch state and polling until processing ends. Its batch results are then obtained separately, and an ended batch can contain a mixture of succeeded, errored, canceled, and expired requests.
These are documented behaviors, but the architectural conclusion is a recommendation: place a normalization layer between providers and customer endpoints. Without it, every customer must implement provider-specific signature verification, polling, state mapping, duplicate handling, retries, and result retrieval.
This layer naturally belongs in a multi-model AI API gateway. It can correlate provider activity with the tenant, credentials, policies, and job record already used to submit the request.
Make the gateway job record authoritative
Create a gateway job before submitting work upstream. Give it an identifier that never depends on a provider job ID. A practical record contains:
job_id, tenant ID, environment, and submitting principal- provider, provider account, and provider job ID
- canonical state and monotonic state version
- provider state and last provider observation time
- result locator, result availability, and retention deadline
- callback endpoint and delivery policy snapshot
- creation, submission, terminal, and reconciliation timestamps
Keep the canonical state machine small. For example: queued, submitted, running, succeeded, partially_succeeded, failed, canceled, and expired. Define which transitions are legal and reject regressions caused by delayed or out-of-order signals.
A batch-level success signal must not be interpreted as success for every item. If constituent outcomes differ, expose a batch state such as partially_succeeded and put item-level outcomes behind the result API.
Use separate adapters for webhooks and polling
Native-webhook adapter
The inbound adapter should read the exact raw request body, verify the provider signature and timestamp, apply a payload-size limit, and durably enqueue the notification. Only then should it return a successful response. Parsing or acting on an unverified body creates an avoidable security boundary failure.
Keep this request path short. OpenAI advises acknowledging accepted webhook requests quickly and moving substantial work to a background worker. It also documents retries for unsuccessful or slow deliveries, redirects being treated as failures, and the possibility of duplicate events.
The queued notification should cause a worker to retrieve or confirm authoritative provider state. Do not emit a customer event merely because an inbound payload appears to say “completed.” The signal may be duplicated, delayed, incomplete, or followed by a state that requires separate result retrieval.
Polling adapter
For providers that expose status retrieval, schedule polling from the gateway job record. Use exponential backoff with jitter, enforce per-provider concurrency and rate limits, and stop normal polling when the job reaches a confirmed terminal state.
A reasonable schedule starts quickly and becomes progressively less frequent. Apply a random offset so thousands of jobs submitted together do not create synchronized polling spikes. Treat temporary authorization, rate-limit, and server errors as retriable observations rather than terminal job failures.
Polling is also useful as a repair path for webhook-enabled providers. A low-frequency reconciliation poll can recover a notification that was missed because of an internal outage or configuration error.
Publish thin, versioned events
A customer event should describe a gateway state transition, not reproduce a provider payload. One compact envelope might look like this:
{
"event_id": "evt_01J...",
"event_type": "llm.job.terminal",
"event_version": "1.0",
"occurred_at": "2026-10-15T14:22:31Z",
"tenant_id": "tenant_42",
"job_id": "job_01J...",
"job_state": "partially_succeeded",
"error_class": null,
"result_ref": "/v1/jobs/job_01J.../result"
}Keep event_id stable for the logical state transition. Generate a separate delivery_attempt_id for each HTTP attempt. Customers deduplicate with the event ID; operators use attempt IDs to diagnose timeouts, response codes, and retry decisions.
Thin events keep model output and sensitive input out of callback infrastructure. The receiver makes an authenticated request to retrieve the current job and result. This adds a round trip, but avoids repeatedly sending large or confidential output and prevents an old callback body from becoming the source of truth.
Version this schema independently from provider schemas. Provider-specific fields can be retained in restricted diagnostic records, but they should not silently leak into the public contract of a central AI API control plane.
Persist the transition and event atomically
The most dangerous failure window occurs when the database marks a job complete but the corresponding event is never queued. Prevent it with a transactional outbox or an equivalent durable mechanism.
- Lock or compare-and-swap the canonical job record.
- Validate that the new state version is greater than the stored version.
- Write the job transition and outbox event in the same database transaction.
- Commit the transaction.
- Let a separate publisher move pending outbox rows into the delivery queue.
- Mark publication progress without deleting the audit record prematurely.
This architecture provides at-least-once delivery. Do not promise exactly-once callbacks across databases, queues, networks, and customer systems. A timeout can occur after the customer has processed a request but before the gateway receives its response. The correct contract is stable event identity plus idempotent customer handling.
Sign customer callbacks and defend the endpoint
Sign the exact raw body together with an authenticated timestamp and stable event ID. Send the signature, timestamp, and event ID in headers, and publish verification helpers for supported languages. Receivers should verify the signature and timestamp before parsing the JSON or triggering work.
Secret rotation needs an overlap window. During that period, include signatures that can be validated with both the retiring and replacement secrets. Record which key version produced each signature, but do not expose secret material in delivery logs.
Customer-controlled callback URLs create an SSRF risk. Apply the following controls at registration and again when opening each connection:
- Require HTTPS and allow only supported ports.
- Resolve the hostname and reject loopback, private, link-local, multicast, and other special-purpose addresses.
- Protect against DNS rebinding by validating the actual connection destination.
- Disable redirects, or resolve and validate every redirect target before following it.
- Isolate delivery workers and restrict their network egress.
- Limit request body size, response body size, connection time, and total request time.
Registration-time validation alone is insufficient because DNS records and redirect targets can change after an endpoint is approved.
Define retries as part of the public contract
Deliver asynchronously using bounded exponential backoff with jitter. Treat network failures, timeouts, HTTP 408, 429, and most 5xx responses as retriable. Honor a valid Retry-After value within your maximum delay. Most other 4xx responses should pause or end automatic delivery because retries are unlikely to repair an invalid path, authorization configuration, or payload contract.
Publish the retry window, maximum attempts, timeout, and endpoint-disable policy. Long retry windows improve outage recovery but can produce a substantial backlog. Apply per-endpoint concurrency limits so one unhealthy customer cannot consume the entire worker pool.
After automatic retries are exhausted, move the delivery into a dead-letter workflow rather than deleting it. Provide endpoint health, last response code, next retry time, attempt history, event retrieval, and manual replay. For partner-facing systems, these controls are part of reliable partner LLM API management, not merely internal queue administration.
Add reconciliation for failures outside the delivery path
Run a periodic reconciliation worker that searches for inconsistencies, including:
- provider jobs believed to be active beyond their expected processing window
- terminal gateway jobs without a matching outbox event
- published events with no delivery record
- events without successful delivery or explicit expiry
- results that were never fetched before their retention deadline
Reconciliation should be idempotent. If it finds a missing event, it must derive the same logical event identity or confirm that no prior event exists before creating one. Otherwise, the repair process can manufacture duplicate logical transitions rather than duplicate deliveries of the same transition.
Test the contract under failure
Contract tests should cover duplicate provider notifications, out-of-order signals, delayed polling, mixed batch outcomes, provider rate limits, and a crash immediately after the outbox transaction commits. Also test customer timeouts after successful processing, stale signatures, replayed timestamps, secret overlap during rotation, DNS rebinding, redirect changes, dead-letter handling, and manual redelivery.
Measure time from provider terminal state to gateway observation, outbox lag, delivery latency, retries per event, duplicate deliveries, signature failures, unhealthy endpoints, dead-letter volume, and reconciliation repairs. These metrics reveal whether the callback contract is dependable even when the happy path appears healthy.
Implementation checklist
- Use a gateway-owned job ID and canonical state machine.
- Treat provider notifications as refresh triggers, not final truth.
- Support both native-webhook ingestion and rate-limited polling.
- Persist state transitions and events atomically.
- Use stable event IDs and separate delivery-attempt IDs.
- Send thin, independently versioned event envelopes.
- Sign the raw body, timestamp, and event ID.
- Validate callback destinations at registration and connection time.
- Offer bounded retries, dead-letter visibility, retrieval, and manual replay.
- Reconcile terminal jobs, emitted events, and delivery outcomes periodically.
The durable design principle is simple: providers report observations, the gateway owns canonical job and delivery state, and customers receive an at-least-once, verifiable event that points back to an authoritative retrieval API. Provider capabilities will evolve, but this boundary keeps those changes out of customer integrations.