Arthur Foo

Case study · API reliability

AI API Gateway

A multi-provider gateway that can switch upstreams after a failure and settle each successful request once.

Software engineer · project-based Aug–Oct 2026 Go · React/TypeScript · PostgreSQL · Redis 763 requests in a local test

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

Simplified
Direct success and fallback for REQ-042 The client submits a request, the wallet reserves funds and routing selects Provider A. The classifier checks for usable output. A usable response proceeds to settlement, or an eligible failure goes to Provider B. Both paths settle under the same logical request. CLIENT Make the request WALLET Reserve funds ROUTING Select a candidate PROVIDER A Handle the first call REQ-042 reserve attempt 1 return output or upstream error CLASSIFIER Choose the next step check bytes and error SETTLEMENT Settle once REQ-042 PROVIDER B Handle the fallback call REQ-042:b2 A: usable output eligible failure attempt 2 Settle REQ-042 using B’s output
First provider succeeds. Provider A returns usable output and the gateway settles REQ-042 once. 首家成功。 供应商 A 返回有效输出,网关对 REQ-042 结算一次。
Fallback. Provider A returns an upstream 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 仍只结算一次。
  1. The client submits request REQ-042.调用方发出请求 REQ-042。
  2. The wallet reserves funds.钱包预扣资金。
  3. Routing selects Provider A.路由选择供应商 A。
  4. Provider A handles the first call and returns output or an upstream error.供应商 A 处理首次调用,返回输出或上游错误。
  5. The classifier checks downstream bytes and the error to choose the next step.分类器核对下游字节和错误,判断下一步。
  6. Usable output goes to settlement, and REQ-042 settles once.有效输出进入结算,REQ-042 结算一次。
  7. An eligible failure goes to Provider B as attempt 2. REQ-042 still settles once.失败且可换路时,供应商 B 处理第 2 次尝试,REQ-042 仍只结算一次。
Fig 04.1 Fallback can change the provider while keeping settlement tied to the same logical request.

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.
Fallback condition · pseudocode Simplified
can_switch =
    failure_is_eligible
    and request_is_replayable
    and downstream_bytes == 0
    and upstream_attempts < 15

05 · Technical choices & trade-offs

Cap attempts and attribute failures using evidence

  1. 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.

    取舍 请求可能在还有候选渠道时就用完尝试配额。

  2. 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.

    取舍 证据不足时,即使确实是供应商故障,也可能暂不处罚。

  3. 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.

    取舍 每类都要分开验证是否会触发冷却。

  4. 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
StepReferenceSettlement outcome
Wallet reservationREQ-042Funds reserved
Provider A · eligible upstream failureREQ-042No settlement
Provider B · usable outputREQ-042:b2One settlement for REQ-042
Fig 06.1 The second attempt has its own internal reference, with one settlement across both attempts.

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 状态回读。

CheckResultSource
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.