Request pipeline
Definition
The request pipeline is the fixed sequence of stages every inference request passes through in the gateway. It has three phases: access, content and log. Any stage can short-circuit — answer the client at once — or pass the request on.
Function
The order puts cheap refusals first, decides routing before personal data is masked, and records cost and logs only after the answer is known.
flowchart TD
Client([Client]) --> A1
subgraph Access ["Access phase — cheap refusals first"]
A1[Tenant and authentication] --> A2[IP allowlist] --> A3[Rate limit] --> A4[Quota check]
end
A4 --> B1
subgraph Content ["Content phase — body available"]
B1["Input checks<br/>agent invoke · department gate"] --> B2[Cache check]
B2 --> B3["Model resolution and routing<br/>allowlist · compaction check · routing rules"]
B3 --> B4[Guardrails — request]
B4 --> B5["System prompt · spend guards · provider key"]
B5 --> B6["Web search · tool loop · provider call"]
B6 --> B7[Guardrails — response]
B7 --> B8["Send response · cost · cache store"]
end
B8 --> L1
subgraph Log ["Log phase — after the response"]
L1["Request log · metrics"]
end
Access phase
Runs before the request body is read:
- Tenant and authentication — resolves the tenant and gateway from the URL and validates the token. Missing or invalid token:
401; a role without inference rights:403. - IP allowlist — refuses a client outside the gateway's allowlist with
403, before it counts against a rate limit or reserves budget. - Rate limit — see Rate limiting. Refusal:
429 rate_limited. - Quota check — checks the wallet and the spend budgets. Refusal:
429 quota_exceeded.
A body whose declared size is over the request size limit is refused with 413 before the access phase.
Content phase
Has the full request body:
- Input checks — exact-number validation, agent-invoke rewriting, and the department gateway gate.
- Cache check — an exact-match hit returns the stored answer. See Response caching.
- Model resolution and routing — normalises the model id, applies plan and model allowlists, checks the context window, and evaluates the routing rules. The first matching rule wins.
- Guardrails (request) — run after routing, so the final provider is known. Masking is skipped on a wholly-local Myra model leg. See Guardrails.
- System prompt, spend guards and provider key — composes the system prompt, applies the trial, per-user and per-team caps, and loads the provider key.
- Web search, tool loop and provider call — the call to the provider, with retry and fallback on server errors. Provider client errors are returned without retry.
- Guardrails (response) — a blocked response is never sent.
- Send response, cost and cache store — sends the answer, computes the cost, and stores a cacheable response.
Log phase
Runs after the response is sent; a failure here does not affect the client. It writes the request log entry and metrics. Payload logging can be switched off per gateway or per request.
The log write uses the gateway's MariaDB connection pool, which is capped per worker; when it is full the entry goes to the spill area described below. See Database capacity.
If the database has a brief fault while the entry is written (a deadlock, a lock timeout, a lost connection), the entry is not discarded: it is held in a 64 MB in-memory area per gateway container and written again every 2 seconds, with growing pauses of up to 60 seconds, until the database accepts it. An entry the database permanently rejects is not retried; it is reported in the gateway error log with its request id. Each held entry is logged as a warning ([db_spill] request_log: spilled key=<request id>). An entry that cannot be held is logged as an error (request_log row LOST (spill refused: <reason>) request_id=<id>).
- Attribution is kept. A held entry keeps the attribution it had at request time. The department of each provider leg is not looked up again when the entry is written later, so a user who moved to another department in the meantime does not pull the cost into the new one. Each leg's
created_atis the request time, not the moment the retry succeeded. If the department could not be decided at request time (the lookup failed, or the database could not be reached at request time), it is decided at write time and the entry carriesmeta.aig_spill_department_at_replay = true, even if that lookup also failed and the department stays empty. - Claim-check verdict. A held entry whose turn was selected for the shadow file-claim check is stored with
aig_cc_verdict = "none"andaig_cc_err = "spilled": the judge did not run for it. If the entry had in fact been stored already (a lost acknowledgement), the retry finds it present and merges these keys into it (entries without a user, e.g. anonymous or erased, and entries whose stored details already exceed the size limit are left unchanged). - Large entries. An entry over 1 MB is narrowed before it is held: the prompt and response bodies are dropped, while tokens, cost and the provider legs are kept. The stored entry carries
meta.aig_spill_payload_stripped = true. - Container stop. Entries still held when the container stops are reported in the error log and lost. A restart during a database outage can therefore lose recent entries.
- Not held at all.
dropped_*(at spill time). - Removed after being held.
rejected,discarded_malformed.
Metrics, on the gateway /metrics endpoint:
| Metric | Meaning |
|---|---|
aig_db_spill_total{channel="request_log",outcome=...} |
Counter per outcome. spilled: held for retry. replayed: written by the retry. duplicate_key: an entry with this request id is already held. replay_transient and replay_error: the retry failed or errored, the entry stays held and is tried again. rejected: the database refused the entry permanently; it is dropped and logged. discarded_malformed: held entry could not be decoded. dropped_* (dropped_full, dropped_too_large, and similar): not held (area full, still over 1 MB after narrowing, or not encodable). pending_at_worker_exit: entries still pending when a worker exited (kept across a reload; lost only if the container stops, the error line entries still spilled at worker exit is the signal for that). |
aig_db_spill_bytes_used_request_log |
Gauge: bytes currently used of the 64 MB area. |
Alert on any increase of rejected, dropped_*, or discarded_malformed, and on the error lines: each is a lost entry.
Wallet and budget writes
The same holding area protects the money writes at the end of a request. If the database has a brief fault while a wallet charge, the settling of a wallet reservation, the recording of a spend against a budget reservation, or the turn-end debit of a gateway, API key, workspace, user or department spend counter is written (a deadlock, a lock timeout, a lost connection), the write is held in a 16 MB in-memory area per gateway container and repeated every 2 seconds, with growing pauses of up to 60 seconds, until the database accepts it. A write is applied once even when it is repeated: the wallet charge carries its request id, the reservation settle is fenced by the reservation's state, the counter debit carries a key derived from the request id, the scope, the entity and the period, stored in the same database transaction as the counter update (the key and the update are written together or not at all), so a repeat after a lost acknowledgement does not charge twice. These keys are a duplicate guard only, not billing evidence: they hold no workspace, user or amount, and are deleted after 7 days. A held counter debit older than that window (one hour short of it) is rejected and logged rather than risk counting twice. A counter debit that has no request id cannot be held and is lost on a database fault (logged at ERR, metric aig_db_spill_total{channel="wallet",outcome="dropped_unkeyed"}). A held write that fails validation before it is stored (a missing or invalid request id, scope, entity, period or amount, or a key that does not match its contents) is not held; it is logged as [budget_spend_lost] and counted as dropped_malformed. A valid entry the holding area refuses is counted under db_spill's own outcomes (dropped_encode, dropped_too_large, dropped_full, dropped_no_dict). A write the database permanently refuses (for example a reservation that no longer exists, or a workspace without a wallet) is not retried; it is reported in the gateway error log. A held settle of a budget reservation whose reservation has been purged (7 days after it ended) is likewise rejected and logged.
Each held write is logged as a warning ([db_spill] wallet: spilled key=<operation>:<id>). The amount and kind of each held write are logged once at hold time ([budget_spend_spill] wallet <operation> parked for replay ...); a write the database later refuses is reported by key only, so match it to that line. A write that cannot be held is logged as an error ([budget_spend_lost] wallet <operation> LOST (spill refused: <reason>) ...); this line is never suppressed. Entries still held when the container stops are reported in the error log and lost.
The metrics are the ones above with channel="wallet", and the gauge is aig_db_spill_bytes_used_wallet (the 16 MB area). Alert on any increase of rejected, dropped_* or discarded_malformed for this channel and on the [budget_spend_lost] line: each is a spend that was not recorded.
See also
- Multi-tenancy — tenant and gateway resolution.
- Fallback and retry — retry count and fallback chains.
- Error codes — every refusal code, including request size limits.
- IP allowlist.