AI gateway and resilience
Step 10 of 14. Put one controlled layer between Store Assist and its model providers, and decide in advance what happens when a provider slows, fails or changes.
AI gateway and resilience in 60 seconds
- What: one controlled layer between your services and every model provider, holding credentials, routing, limits, logging and failure rules.
- Why: providers have outages, quotas and version changes. Without a single layer, each team handles them differently.
- Failure handling: bounded timeouts, retries only for temporary faults, backoff with jitter, a retry budget, a circuit breaker and a tested fallback.
- Failover: a second model must be qualified on your tasks first. Sometimes a clear error beats a silent downgrade.
- Control: secrets in a vault, quotas and cost tracked by team and feature, model versions pinned and retirements calendared.
The problem it solves
Once Store Assist depends on a hosted model, a company you do not control becomes part of your uptime. It can have an outage, throttle you, retire a model or release a new version whose behaviour shifts on your prompts. If the orchestrator, the evaluation jobs and the document indexer each call providers directly, every one of those events has to be handled in several places, and each place will handle it a little differently.
A gateway gives those problems one home. Application code asks for a capability, such as "answer with a tool-capable model within 6 seconds", and the gateway decides how to get it, what to do when it cannot, and what to record.
What a gateway does
Depending on how you build it, a gateway can provide the following:
- One request and response format across several providers.
- A central place for provider credentials, so application services never hold them.
- Model and provider routing, driven by the routing table from step 8.
- Rate limits and quotas, applied before a request reaches the provider.
- Usage and cost accounting by team, feature and environment.
- Logging of requests and responses, with redaction.
- Timeout and retry policy, in one place.
- Failover between providers or models.
- Configuration of exact model versions.
For a prototype you do not need a separate gateway. A well-organised module inside the application, with one client class and one config file, gives the same abstraction at lower cost. A dedicated gateway earns its place as models, teams and providers multiply. Whichever you choose, the aim is identical: provider-specific behaviour must not spread through the codebase.
Designing for provider failure
Suppose the primary provider starts returning errors at 08:05 on a trading Monday. The wrong response is to keep sending everything and hope. The right one is a rehearsed sequence:
- Give every model call a bounded timeout.
- Retry only faults that look transient, such as a brief overload, and never resend a request the provider rejected as invalid.
- Back off exponentially and add random jitter, so thousands of clients do not retry at the same instant.
- Give up once the time allowance for this question has been spent.
- Open a circuit breaker if failures continue.
- Send eligible questions to a pre-tested second model, or show a controlled, plain message.
- Log the failure, and alert the owning team when thresholds are crossed.
Retry budgets and deadlines
Retries need a ceiling, because every layer that retries multiplies the load. If the client retries three times, the orchestrator three times and the gateway three times, one colleague question can become 27 provider calls. This retry amplification raises cost and can turn a small wobble into a full outage.
Two controls stop it. First, retry in one layer only, and the gateway is the natural choice. Second, give retries a budget: a fixed share of traffic, for example 10%. At the 10 requests per second peak, that allows about one extra call a second. When the budget is spent, failures are returned immediately instead of retried.
Deadlines should travel with the request. Store Assist has 8 seconds for a full answer at the 95th percentile. Retrieval and checks might use 1 second, leaving about 7 for the model. The gateway receives the remaining time on each call and never starts an attempt it cannot finish. A sensible rule is to retry only if the first attempt failed before any output and at least 3 seconds remain.
Circuit breaker settings
A circuit breaker stops calls to a failing dependency for a while. After a recovery interval it lets a few test requests through to see whether the provider has recovered. Choose settings from numbers, not instinct:
| Setting | Example for Store Assist | Reasoning |
|---|---|---|
| Trip condition | 50% or more failures across at least 20 calls in a rolling 30 seconds | At 10 requests per second, 20 calls arrive in about 2 seconds, so the breaker reacts fast. |
| Open duration | 30 seconds | Long enough to relieve the provider, short enough to recover within a trading hour. |
| Half-open probes | 3 requests | A small sample limits harm if the provider is still unwell. |
| Close condition | All 3 probes succeed | Any failure reopens the breaker for another 30 seconds. |
| Scope | One breaker per provider and model | A fault in one model should not block healthy ones. |
Why failover needs qualification
It is tempting to think that when provider A fails, the same prompt can go to provider B. In practice models differ in behaviour, context window, tool-call format, safety behaviour, latency and feature support. A backup that cannot follow the incident tool schema reliably is unfit for a workflow that raises incidents, however fast it answers.
Before automatic failover is switched on, qualify the backup on the traffic it will receive:
- Run the golden evaluation set against it and compare groundedness and sensitive-request escalation with the primary.
- Run every tool schema it may be asked to use and check argument validity.
- Measure time to first token and total time against the route budget.
- Check context limits against your longest prompts.
- Confirm that data handling terms for the backup meet your policy.
- Repeat the check whenever either model version changes.
Not every request deserves a fallback. A route that needs a capability the backup lacks is better served by a clear failure message than by a silent downgrade that produces worse answers. Decide per route:
| Route | Fallback | Behaviour when primary is down |
|---|---|---|
| Procedure questions | Qualified secondary model | Answer normally, tagged as served by fallback in logs. |
| Stock and incident lookups | None needed for reasoning, plain text template | Return the live data in a fixed format, without generated prose. |
| Incident creation | Qualified only if tool schema tests pass | Otherwise say the assistant cannot raise it now, and offer the desk. |
| Sensitive actions | None | Direct to the verification workflow or the desk. No downgrade. |
Credentials, quotas and chargeback
Provider keys belong in an approved secret store. They must never sit in source code, build logs or the browser. Rotate them on a schedule, for example every 90 days, by keeping two keys valid during the changeover so no deploy is needed, and alert on use from an unexpected network.
Track usage by model, team, feature and environment. This shows which features spend the most, and stops one workload using up shared capacity. Tag nightly evaluation runs separately: a 5,000 case run at 1,000 input and 250 output tokens costs about £4 at the illustrative prices, and should never be mistaken for colleague traffic. Monthly spend of £864 can be split by tag into a chargeback report that each owner can read.
Quotas need both a request limit and a token limit, because providers set both. At peak, 10 requests a second at 1,250 tokens each is 12,500 tokens a second, or 750,000 tokens a minute. With retries within a 10% budget, plan for roughly 825,000. If your provider quota is 1.2 million tokens a minute, you are using about 69% at peak, which leaves useful headroom. Give each team its own slice, so a runaway batch job cannot take the opening-hour capacity.
Pinning versions and planning retirement
Always request an exact model version in configuration, not a moving alias. An alias can change behaviour overnight and you would see it first as a quality dip in the stores. Providers also retire versions on published dates. Keep a deprecation calendar with the owner and the retirement date of every model in use, and work backwards from it:
- 90 days before retirement: choose a candidate and run the full evaluation.
- 45 days before: shadow the candidate on real traffic and compare results.
- 14 days before: complete the canary rollout, so that retirement is a non-event.
A gateway improves control and visibility. It does not remove provider outages, and it does not make models interchangeable. Reliability still comes from testing, capacity planning and agreed failure behaviour.
Store Assist, worked through
At 08:05 the primary provider begins failing on 70% of calls. In the first two seconds, 20 calls arrive at the peak rate and 14 of them fail, so the breaker trips. The 10% retry budget means about one retry a second is attempted, and the rest return at once. For 30 seconds, procedure questions go to the qualified secondary, which answers at a slightly higher median latency but within the 1.5 second time to first token target for most requests. Lookups are served as plain templates, and incident creation is paused with a message that sends colleagues to the support desk.
After 30 seconds, three probes go to the primary. Two succeed and one fails, so the breaker reopens for another 30 seconds. Eventually all three succeed and traffic returns. The log shows the fallback share, the budget used and the number of colleagues who saw a degraded message, which feeds the incident review. Availability of 99.9% during trading hours allows roughly 36 seconds of downtime in a 10 hour day, which is why the fallback route matters.
import random, time
RETRY_BUDGET = 0.10 # at most 10% of calls may be retries
MIN_TIME_FOR_RETRY_S = 3 # do not start a retry without this much time left
BACKOFF_BASE_S = 0.2 # first backoff step, before jitter
class Breaker:
# Trips on >= 50% failures over at least 20 calls in the last 30 seconds.
def __init__(self): self.calls = []; self.open_until = 0.0
def allow(self, now): return now >= self.open_until
def record(self, ok, now):
self.calls = [(t, o) for t, o in self.calls if now - t <= 30] + [(now, ok)]
fails = sum(1 for _, o in self.calls if not o)
if len(self.calls) >= 20 and fails / len(self.calls) >= 0.5:
self.open_until = now + 30 # stay open for 30 seconds
def call_model(req, route, providers, breakers, stats):
deadline = req.deadline # absolute time, set by the caller
for provider in route.providers: # primary first, then qualified fallbacks
breaker = breakers[provider.name]
attempt = 0
while breaker.allow(time.time()):
remaining = deadline - time.time()
if remaining <= 0:
return stats.fail(req, "deadline")
try:
reply = provider.complete(req.pinned_model(provider), req.messages,
timeout_s=min(remaining, route.timeout_s))
breaker.record(True, time.time())
return reply
except provider.TemporaryError:
breaker.record(False, time.time())
can_retry = (attempt == 0
and deadline - time.time() >= MIN_TIME_FOR_RETRY_S
and stats.retry_share() < RETRY_BUDGET)
if not can_retry:
break
attempt += 1
stats.count_retry()
time.sleep(random.uniform(0, BACKOFF_BASE_S * 2 ** attempt)) # jitter
except provider.PermanentError:
return stats.fail(req, "rejected") # never retry invalid requests
return stats.fail(req, "all providers unavailable") # caller shows plain message
The classes and helpers are placeholders. The limits are explicit: one retry, a 10% budget, a 3 second floor, a 30 second window.
Design decisions
- Build or buy: start with a module in the application, and move to a dedicated gateway when several teams or providers appear.
- Single retry layer: retry only in the gateway and make every other layer fail fast.
- Per-route fallback policy: list which routes may fall back, which may not, and what the user sees.
- Breaker scope: one breaker per provider and model, with settings kept in versioned config.
- Deadline propagation: carry an absolute deadline in every internal call.
- Logging: redact before storing, and agree retention with the privacy owner.
- Chargeback tags: require team, feature and environment on every call.
- Version control: exact pins, with a calendar owned by a named person.
Measuring it
- Fallback quality gap: golden set scores for each fallback model against the primary, by route.
- Tool schema validity: the share of valid tool arguments from each model.
- Degraded answer rate: the share of colleague answers served by a fallback, and their ratings.
- Version drift: score changes when a provider updates a model, caught by scheduled evaluation.
- Latency by provider: time to first token and total time at the median and 95th percentile.
When to use it, and how much of it
| Situation | Approach | Why |
|---|---|---|
| One model, one team, prototype | A client module with timeouts and a config file | A separate service adds cost before it adds value. |
| Production feature with a trading-hours target | Gateway layer with retry budget, breaker and one qualified fallback | Provider faults will happen and need rehearsed handling. |
| Several teams and providers | Dedicated gateway with quotas, chargeback and shared policy | Central control prevents drift and surprise bills. |
| Sensitive actions | No automatic downgrade | A clear failure is safer than a weaker model making decisions. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Availability | Fallbacks keep answers flowing during provider faults. | Qualify them first, and measure the quality gap. |
| Cost | A gateway and a second provider add running and evaluation costs. | Keep the fallback to routes where uptime matters most. |
| Quality | A fallback model may answer less well. | Show degraded mode in dashboards and review samples. |
| Complexity | One more critical component to run. | Give it an owner, an on-call rota and its own load test. |
What this means for your role
Common mistakes
Step checklist
- All model calls pass through the gateway layer, and no service holds a provider key.
- Every call has a timeout, and a deadline travels with the request.
- Retries happen in one layer, with a 10% budget and jittered backoff.
- Breakers exist per provider and model, with documented settings.
- Each route has a written fallback policy, and fallbacks have passed qualification tests.
- Quotas cover requests and tokens, and each team has its own share.
- Spend is tagged by team, feature and environment.
- Secrets rotate on a schedule with two keys valid during changeover.
- Model versions are pinned, and a deprecation calendar has owners and dates.
- A provider outage drill has been run and the results recorded.
Further reading
- AI gateway, cost and reliability: the concepts behind this step.
- API gateway: the general pattern this builds on.
- Circuit breaker: how breakers behave in detail.
- Rate limiting: limits and quotas explained.
- Availability and reliability: the targets behind the numbers.
With a gateway in place, Store Assist can lose a provider for half a minute and still serve most colleagues. Next: Step 11: Queues, scaling and streaming.