Case study · API reliability
AI API Gateway
A multi-provider gateway that can switch upstreams after a failure and settle each successful request once.
01 · Summary
Switch upstreams and settle once
I helped develop a company's AI API gateway, focusing on routing, failure attribution and capacity protection.
When an upstream fails, the gateway decides whether to switch providers, who is responsible for the failure and how to settle a successful request once.
02 · Problem & constraints
One fast failure could trigger a chain of attempts
A time-only retry budget let a single request try too many channels. Platform or user errors could be attributed to a provider, and some upstreams returned HTTP 200 with no usable output.
Reservations, settlements and refunds must reconcile against the same logical request. Once the client receives streamed bytes, the gateway cannot transparently switch providers. User errors and content-safety refusals end the request.
03 · My role
Routing, failure attribution and capacity protection
As a project-based software engineer, I scoped the reliability changes and set acceptance criteria. I directed Codex and Claude Code through investigation, implementation, testing and independent review, then checked the results at each stage.
Colleagues reviewed and merged pull requests and handled deployment.
04 · Architecture & critical path
Where does a request go when the first provider fails?
Demo request REQ-042 starts with a wallet reservation. If Provider A fails before the client receives any bytes and the request can be replayed, the classifier can send it to Provider B within the attempt limit.
演示请求 REQ-042 先做钱包预扣。若供应商 A 在客户端收到任何数据前失败,且请求可以重放,分类器可在尝试次数上限内把请求交给供应商 B。
Demo request · REQ-042
REQ-042 once.
首家成功。 供应商 A 返回有效输出,网关对 REQ-042 结算一次。
5xx before any downstream bytes. The replayable request reaches B as attempt 2. B returns usable output and REQ-042 still settles once.
换路。 供应商 A 在下游收到任何数据前返回 5xx。这笔可重放的请求改由 B 处理第 2 次尝试,收到有效输出后,REQ-042 仍只结算一次。
- The client submits request
REQ-042.调用方发出请求REQ-042。 - The wallet reserves funds.钱包预扣资金。
- Routing selects Provider A.路由选择供应商 A。
- Provider A handles the first call and returns output or an upstream error.供应商 A 处理首次调用,返回输出或上游错误。
- The classifier checks downstream bytes and the error to choose the next step.分类器核对下游字节和错误,判断下一步。
- Usable output goes to settlement, and
REQ-042settles once.有效输出进入结算,REQ-042结算一次。 - An eligible failure goes to Provider B as attempt 2.
REQ-042still settles once.失败且可换路时,供应商 B 处理第 2 次尝试,REQ-042仍只结算一次。
The Go gateway authenticates and reserves funds, then looks at pinned channels, the personal pool, smart routing and the marketplace in that order. Protocol adapters call upstreams, PostgreSQL stores billing records and Redis coordinates channel health and capacity leases.
- Attempt evidence
- Each attempt records its own evidence, from before dispatch to I/O start and upstream response.
- Streaming boundaries
- The first byte sent to the client commits the route. Usable content is required to commit billing.
- Candidate selection
- Each layer filters out unhealthy or cooled-down channels. A logical request can make at most 15 real upstream attempts.
can_switch =
failure_is_eligible
and request_is_replayable
and downstream_bytes == 0
and upstream_attempts < 15
The other three conditions hold: the failure is eligible, the request is replayable and attempts remain. Change one thing: has the gateway sent the first byte to the client?
A backup provider may be tried. All four conditions hold. Trying is allowed; success is not guaranteed.可以尝试备用供应商。 四个条件都成立。允许尝试,不等于一定成功。
No transparent fallback. The first byte sent to the client commits the route, so downstream_bytes == 0 no longer holds.不能透明换路。 首字节发到客户端后就不能再换路,downstream_bytes == 0 不再成立。
05 · Technical choices & trade-offs
Cap attempts and attribute failures using evidence
-
Put a hard cap on upstream attempts
In addition to the time budget, each logical request can make at most 15 actual upstream calls.
Trade-off A request can exhaust its budget with candidates still available.
取舍 请求可能在还有候选渠道时就用完尝试配额。
-
Require provider evidence before applying cooldown rules
An attribution check runs before the existing cooldown rules. Errors with an unknown owner are recorded for observation.
Trade-off A real provider fault may go unpenalised when the evidence is incomplete.
取舍 证据不足时,即使确实是供应商故障,也可能暂不处罚。
-
Distinguish 429 responses by origin
Confirmed capacity 429s get a bounded retry. Explicit provider rate limits keep the existing penalty rules, and ambiguous 429s are observed.
Trade-off Each class requires a separate check for cooldown side effects.
取舍 每类都要分开验证是否会触发冷却。
-
Keep serving requests during a Redis outage
Redis-backed leases enforce each channel's concurrency limit. The gateway continues to admit traffic when Redis is unavailable.
Trade-off Per-channel concurrency can exceed the configured limit during that gap.
取舍 在这一空窗期内,单渠道并发可能超过设定上限。
06 · Implementation evidence
How two attempts lead to one settlement
The table reconstructs the fallback for demo request REQ-042 from design records. The company interface is private.
下表根据设计记录重画演示请求 REQ-042 的换路过程。公司界面不公开。
Fallback settlement record · REQ-042
Demo data| Step | Reference | Settlement outcome |
|---|---|---|
| Wallet reservation | REQ-042 | Funds reserved |
| Provider A · eligible upstream failure | REQ-042 | No settlement |
| Provider B · usable output | REQ-042:b2 | One settlement for REQ-042 |
07 · Results & verification
Local concurrency tests checked settlement and capacity
Verification combined independent review, focused go test runs with race checks, go vet and PostgreSQL and Redis state read-back in isolated environments.
验证包括独立审查、定向 go test 并检测并发竞争、go vet,以及隔离环境下的 PostgreSQL、Redis 状态回读。
| Check | Result | Source |
|---|---|---|
| Concurrent routing | 763 requests, concurrency 1–30. All stayed within the attempt cap. Measured | Isolated local routing load test |
| Settlement | One settlement per success, zero duplicate charges and zero charged failures. Measured | Billing read-back from the same load test |
| Upstream concurrency per channel | Peak held at the configured 10 with enforcement, versus 28–30 with enforcement off. Zero leaked leases across about 40,000 admitted requests. Measured | Local two-instance capacity test |
08 · Limits & next steps
Production impact is unverified and faster recovery is still in design
Controlled read-only queries returned no production data, so the results here cover local tests. The empty-output fix reached its repair limit and stayed unmerged. Faster recovery of capacity enforcement remains at the design stage.