At scale, something always fails. A gateway that matches each failure to its own fix turns about 20 failed calls in 1,000 into 1 or 2 errors a person sees. Only that person can fix those.
Pick Toy agent, Retry only or Four reflexes, raise the failure rate, and press Send 1,000 calls. Count the red squares. Then we build each reflex: retry, classify, budget, failover, cooldowns, compaction, crash recovery and self-repair.
You need Lessons 1 and 2 (the supervisor, ticks and reconnect backoff) and a little Python for the labs. We build the rest from zero.
Lesson 9 of 11 in Anatomy of an Agent Gateway. The running example is OpenClaw. We checked every OpenClaw detail here against its documentation.
Illustrative toy. Each square is one call. We assume a failure mix of 55% brief blips, 25% provider outages, 12% context overflows and 8% bad requests; we did not measure OpenClaw.
Chapter 0
Count the failures a busy gateway sees in a day, and give each kind its own fix
Your agent makes a model call. The call works 999 times in 1,000. That sounds safe. Now let the agent run all day, every day, for everyone in your family.
Call the number of calls in a day n and the chance that one call fails p. How many failures do you expect each day?
F equals n times p.
Each of the n calls has a small chance p to fail. Multiply the two. The result F is how many failures a normal day brings.
With made-up numbers: n = 10,000 calls and p = 0.001. F = 10,000 × 0.001 = 10 failures every day. A rare event per call is a daily event for the gateway.
Each red tick is one failure on a 24 hour line. Drag the calls per day, then pick a better success rate.
Failures are placed at random times with a fixed seed. The count shown is the expected value F, rounded.
So stop asking whether a call will fail. Ask what the gateway does when it fails. A self-healing gateway is one that recovers from the common failures by itself, with no person in the loop. It does three things each time:
| Failure | Example | Reflex |
|---|---|---|
| A brief blip | a reset connection, a busy second | retry after a wait |
| A provider in trouble | rate limits for an hour, billing off | failover to another credential or model |
| A full context | the transcript passes the window | compaction of old turns |
| A crash mid-send | the gateway dies with a reply queued | recovery from the durable queue |
| A bad request | a malformed body, a 404 | surface it now; no fix helps |
Lesson 1 covered the supervisor that restarts a crashed gateway. Lesson 2 covered ticks and reconnect backoff for a dropped socket. This lesson covers what happens to each call.
Chapter 1
Wait longer after each failure, cap the wait, and add a random wobble so a crowd does not retry at once
A provider has a bad second. A thousand gateways get an error at the same moment. Each one tries again. What should "again" mean?
Not "now". The provider is short of capacity, and an instant retry adds load. So each caller waits, and doubles the wait after each failure. This is exponential backoff. A cap stops the wait from growing past a ceiling. Lesson 2 used the same shape for reconnecting a socket.
Backoff alone has a flaw. If every caller uses the same schedule, all thousand retries land in the same instant. This wave is a thundering herd, and it knocks the provider over again. The fix is jitter: each caller adds a small random part to its wait.
Call the first wait d0, the cap dmax, the failed tries so far k, the jitter fraction j and a random number u between −1 and 1.
d-k equals the min of d-zero times two to the k, and d-max, all times one plus j times u.
Double the first wait d-zero once for each failed try k. If that passes d-max, use d-max. Then stretch or shrink the result by up to j, using the random number u.
With d-zero = 0.4 s, d-max = 30 s and j = 0.1: after k = 2 failures, min(1.6, 30) = 1.6 s; with u = 0.5 the wait is 1.6 × 1.05 = 1.68 s. After k = 8, min(102.4, 30) = 30 s, so the wait is between 27 s and 33 s.
1,000 clients fail at time 0. Each bar counts the retries that land in one 50 ms slot. Drag the jitter and watch the spikes spread.
Illustrative: first wait 1 s, doubling, three retries per client, each retry fails. The 10% default is OpenClaw's; the rest is a toy.
OpenClaw's channel sends (a Telegram reply, for one) use 3 attempts, a 400 ms minimum wait, a 30 s cap and 10% jitter. Discord sends start at 500 ms. With 3 attempts there are only 2 waits, so the cap never binds here. It binds for model calls, which retry many more times (Chapter 3).
Chapter 2
Sort each error into "try again" or "tell the caller now", and honour the provider's own wait
A request comes back with 404 Not Found. Send it again and it fails the same way. A retry only helps when the failure belongs to the moment, not to the request.
A transient failure is one that can clear by itself: a timeout, a reset connection, a busy server. A permanent failure is one the request carries with it: a bad body, a missing thing, no permission. Call the chance that one try fails q and the number of tries A. If the tries fail independently, what is the chance that all of them fail?
P-fail equals q to the A.
Each try fails with chance q. All A tries fail only if each one does, so multiply q by itself A times.
With made-up numbers: a blip with q = 0.3 and A = 3 tries gives 0.3 × 0.3 × 0.3 = 0.027, under 3%. A 404 has q = 1, so 1 × 1 × 1 = 1: three tries, three failures, three wasted round trips.
The HTTP status code says whose fault it is. A 5xx code means the server broke, so try again. A 4xx code means the request was wrong, so stop. Three 4xx codes are the exceptions: 408 (request timeout), 409 (conflict) and 429 (rate limited, "try later").
Pick an error. The lit path shows each question the classifier asks, and where the error ends.
The status codes, the 60 s ceiling and the 401/403/404 rule come from OpenClaw's retry docs. The tree is our drawing of them.
A 429 often carries a Retry-After header: the provider's own wait time. The gateway uses it as the minimum wait, because the provider knows its recovery better than a formula does. Patience has a limit. In OpenClaw a wait above 60 s stops retries on that credential. The gateway then tries another credential or model, or reports the error.
Retry runs per request, not per flow. "Send a photo with a caption" can be three requests. If the second one fails, the gateway repeats only the second. A repeat is safe only with an idempotency key, a tag that lets the receiver see "I did this already" (Lesson 2, chapter 5). Where a channel gives no such check, OpenClaw stays careful. A Telegram text send that may have gone out is not sent again, because a duplicate is worse than a delay.
Chapter 3
Add up the waits, and stop when the try count or the time window runs out
A chat send gets 3 tries. A model call in the middle of an agent run gets far more, because the run has work to protect. OpenClaw continues the same transcript after a retry, so tools that already ran are not run again.
More tries means more waiting. A retry budget is the limit on tries and on time for one outage. To see what a budget costs, add up its waits. Use the waits dk from Chapter 1 without the jitter, and call the number of retries R.
T equals the sum over k from zero to R minus one of the min of d-zero times two to the k, and d-max.
Work out each capped wait for k = 0, 1, 2 and so on, R times. Add them. The total T is the longest a person can wait before the gateway gives up on this model.
Rate limits allow 16 attempts, so R = 15. With d-zero = 1 s and d-max = 60 s: 1 + 2 + 4 + 8 + 16 + 32 = 63 s, then 9 × 60 = 540 s. T = 603 s, about 10 minutes, before the request time is even counted.
Each bar is one wait; the line is the running total. Switch the failure kind and drag the retry count.
From OpenClaw's docs: 16 attempts for rate limits, 8 retries in a 90 s window for other transient failures, caps of 60 s and 30 s, a start "around one second". Exact doubling and zero request time are our assumptions.
The budget has two limits. Rate limits get up to 16 attempts in one outage. Other transient failures get 8 retries inside a 90 s window. In our toy the window ends first: the seventh wait would end at 91 s, so only 6 retries fit. A completed model reply resets both, so a long run that works between outages never runs dry.
Some failures skip the budget. Billing errors, auth errors and provider refusals go straight to failover or to the person, because waiting does not fix them.
Chapter 4
Rotate to another credential first, then to another model, and know which errors stop the walk
Your model provider rate-limits you for the next hour. No wait inside a retry budget fixes that. You need a different way in: another credential, or another model.
Failover is the switch to another way in when one stops working. OpenClaw does it in two stages, after the same-model budget of Chapter 3 runs out:
The gateway builds the chain in a fixed order. The requested model goes first. The configured fallbacks follow, in their listed order (agents.defaults.model.fallbacks). The configured primary goes last, so the run can settle back on the default. Duplicates drop out, so a requested model that is also the primary appears once.
Each model box holds two credentials. Pick a scenario and press Walk. Turn on Different primary to see the primary join the end.
The chain order, the advance and stop rules and the strict pick come from OpenClaw's model failover docs. The model names, the windows and the two credentials per model are illustrative.
| Error | Walk | Why |
|---|---|---|
| auth failure, rate limit, overload, timeout, billing | advance | this way in is blocked; another may work |
| model not found | advance | this model is gone; the next one exists |
| context overflow that compaction could not fix | advance, if safe to replay | a model with a larger window may fit it |
| the person pressed stop | stop | nobody wants the answer now |
| a final provider refusal | stop | another model must not route around it |
| no candidates left | stop, report | one error lists each attempt |
Two rules keep failover honest. First, the fallback answers only the current turn: the session still shows the model the person selected. Second, a model the person picked on purpose with /model is a strict pick. If it fails, the person sees the error, not a reply from a model they did not choose.
model_fallback_decision log./model openai/gpt, and that model is rate-limited on both of its credentials. What happens?Chapter 5
Rest a failing credential for the right time, pick the next one in a fixed order, and keep one credential per session
Failover skipped a credential that failed. One second later the next message arrives. Should the gateway try that credential again? Not yet. A cooldown is a rest period in which the gateway does not use a failed credential.
The length of the rest depends on the failure:
| Failure | Cooldown |
|---|---|
| rate limit, with a provider wait | exactly the provider's wait |
| rate limit, with no provider wait | none; the current turn still rotates |
| timeouts and other failures | 30 s, then 1 min, then 5 min (the cap) |
| billing failure, revoked key | disabled for 10 min |
OpenClaw does not invent rate-limit cooldowns. The provider knows when its limit resets, so its number wins. The error counter for other failures resets after a quiet period.
Which credential comes next? With no order configured, OpenClaw sorts by type: OAuth, then static token, then API key. Inside a type, the one used longest ago goes first, so use spreads evenly. Credentials in cooldown go to the end.
The pin marks the credential this session uses. Cause a failure on it, then let time pass.
The cooldown lengths and the sort order come from OpenClaw's docs. The three credentials are illustrative, and the toy never clears the error count.
A provider keeps a prompt cache: it reuses the work on a prompt prefix it has seen. Switching credentials can lose that cache, so OpenClaw pins the chosen credential to the session. The pin moves only on /new or /reset, or when that credential is in cooldown. Compaction does not move it.
The same logic applies to models. After a rate limit sends a turn to a fallback model, the next turns try that fallback first. Call the time of the first fallback tfirst and the time of its latest successful use tlast.
t-end equals the min of t-last plus ten minutes, and t-first plus thirty minutes.
Add 10 minutes to t-last. Add 30 minutes to t-first. The earlier of the two is t-end; after it, turns start from the selected model again.
With made-up times: the first fallback is at 14:00 and the latest success at 14:22. 14:22 + 10 = 14:32; 14:00 + 30 = 14:30. t-end = 14:30, so the cap wins.
/status for an active fallback, and the credential's cooldownUntil.Chapter 6
Summarise the old turns before the context fills, and move the cut so a tool call keeps its result
A chat runs for a week. Every message and every tool result joins the transcript the model reads. One morning the next call fails: "context length exceeded". A new provider does not help, because every model has a window.
Compaction writes a summary of the older turns into the transcript and keeps the recent turns word for word. The model reads the summary plus the recent tail. The full history stays on disk, so nothing is deleted.
When does it start? Call the model's context window W and the room kept free for the summary R, both in tokens.
T-c equals the min of zero point seven five times W, and W minus R.
Take three quarters of the window W. Take the window W minus the reserve R. Start compaction at whichever is smaller.
OpenClaw's example: W = 1,000,000 and R = 20,000 give min(750,000, 980,000) = 750,000 tokens. With made-up W = 32,000: min(24,000, 12,000) = 12,000. In a small window the reserve decides.
If a call overflows anyway, OpenClaw compacts and tries again. Before it compacts, it reminds the agent to save important notes to its memory files (Lesson 8).
There is one trap. A tool use writes two entries: the tool call ("get the weather") and the tool result ("18 °C, rain"). The model API rejects a result with no call before it. If the cut falls between them, the call goes into the summary and the result stays: an orphan. OpenClaw moves the cut so the pair stays together.
Drag how many entries to keep. Turn off Pair-safe cut and find a cut that orphans a result.
Illustrative transcript. The pair rule and the full history on disk come from OpenClaw's compaction docs; OpenClaw cuts by tokens, not by entry count.
Chapter 7
Keep each reply in a durable queue under a lease, and decide after a crash whether to send it again
The agent finishes a reply. The gateway starts to send it to Telegram. Then the machine loses power. Lesson 1's supervisor restarts the gateway. Did the reply go out?
The gateway cannot always know. It has two bad choices. At most once means never send again: no duplicate, but maybe a lost reply. At least once means send again: no loss, but maybe a duplicate. OpenClaw picks per case, with evidence.
Each reply goes into a durable outbound queue, a store on disk that survives a restart. The process that sends it holds a lease: a claim on that reply that expires unless it is renewed. Call the lease length L and the time of the last renewal trenew.
t-free equals t-renew plus L.
Take the last time the sender renewed its claim, t-renew. Add the lease length L. Before t-free, the reply still belongs to the old sender, even if it is dead.
With made-up times: the last renewal is at 12:00:20. The crash is at 12:00:31. t-free = 12:00:20 + 60 s = 12:01:20, 49 s after the crash. Any crash waits between 40 s and 60 s.
Drag the crash time. Then pick what the evidence says about the send.
The 60 s lease, 20 s renewal and the decision rules come from OpenClaw's retry docs (durable outbound delivery). The times are illustrative.
After the lease ends, the evidence decides. If the channel can check, its answer wins. Recovery settles a delivered reply and sends a proven unsent one. With no proof, OpenClaw sends an ordinary text reply once more, and accepts a rare duplicate over a lost reply. It never resends media or actions this way. If that resend is cut off too, it sends a notice that the reply may be missing.
A run that goes quiet without crashing is a different case. Lesson 4 showed the labels long-running, stalled and stuck. They report, and you decide.
Chapter 8
Check health, tighten risky settings, and change config only through a checked, one-field-at-a-time path
Some faults are not in a call. They sit in the config: a group chat left open to anyone, a credentials file anyone on the machine can read. The gateway can find and fix some of these, if the fix is fenced.
OpenClaw has three repair tools:
| Tool | What it does |
|---|---|
openclaw doctor | health checks for the gateway, channels, plugins, model routing and config; --fix runs guided repairs |
openclaw security audit | finds risky settings; --deep adds live checks on the running gateway |
openclaw security audit --fix | applies a fixed list of safe repairs |
The safe list is short on purpose. --fix changes an open group policy to an allowlist and tightens file permissions on config and credential files. It does not rotate keys, disable tools, change the network address or auth, or rewrite plugins. Those choices stay with you.
An agent can also edit config through the gateway tool, one step at a time:
config.schema.lookup: read what a setting means and which values are valid.config.get: read the current config and its hash, a short fingerprint of that exact version.config.patch with baseHash: change only the named fields. The gateway refuses the patch if the config changed since that hash.That refusal is optimistic concurrency: write freely, but only on top of the version you read.
The agent and you both read version v1. Press Agent patches, then You patch. Turn the check off and try again.
Illustrative settings. The flow and the baseHash rule come from OpenClaw's config RPC docs.
There are more fences. The gateway accepts at most 30 config writes or update.run calls per 60 s for each method and device. Restarts are at least 30 s apart. update.run updates and restarts the gateway; update.status then confirms the version that runs.
baseHash with every patch; on a refusal, read again and redo the change.config.patch require the baseHash from config.get?Chapter 9
Inject one failure into one call and watch which reflex takes it
One call moves through five stages: intake, classify, provider, context and deliver. Each button breaks one stage. Watch where the call goes next.
Press a failure. Green means the gateway recovered; red means it surfaced the error with a reason.
Illustrative timing, sped up. Each path follows the rules of Chapters 1 to 7.
| Failure | Reflex | Chapter |
|---|---|---|
| blip | retry with capped, jittered backoff | 1, 3 |
| bad request | surface at once | 2 |
| provider down | rotate credential, then fall back, then cool down | 4, 5 |
| context overflow | compact pair-safe, then retry | 6 |
| crash mid-send | recover from the durable queue after the lease | 7 |
Chapter 10
Keep the terms, the numbers, a checklist and the core code in one place
A self-healing gateway expects failure, sorts it and runs the matching fix. Retry handles blips. Failover handles a blocked provider. Compaction handles a full context. The durable queue handles a crash. Bad requests go straight to the person.
| Term | Meaning | OpenClaw number |
|---|---|---|
| backoff | a wait that doubles after each failure, up to a cap | channel sends: 400 ms min, 30 s cap |
| jitter | a random part of each wait | 10% |
| channel retry | tries for one send | 3 attempts |
| retryable codes | errors that may clear | 408, 409, 429, 5xx, transport |
| provider wait ceiling | the longest Retry-After honoured on one credential | 60 s |
| model retry budget | tries per outage | 16 attempts for rate limits; 8 retries in 90 s otherwise |
| candidate chain | models to try, in order | requested, fallbacks, primary, no duplicates |
| cooldown | rest for a failed credential | provider's wait; 30 s, 1 min, 5 min; billing 10 min |
| fallback stickiness | try the fallback first after a rate limit | 10 min idle, 30 min cap |
| compaction start | context size that triggers a summary | min(0.75 W, W − reserve) |
| lease | a sender's expiring claim on a queued reply | 60 s, renewed every 20 s |
| config write limit | patches per method and device | 30 per 60 s |
A toy of the retry and failover reflexes. It is a sketch for reading, not OpenClaw's code.
pythonimport random, time RETRYABLE = {408, 409, 429} | set(range(500, 600)) ADVANCE = {"auth", "rate_limit", "overloaded", "timeout", "billing", "model_not_found"} def wait(k, d0=0.4, dmax=30.0, j=0.1, hint=None): d = min(d0 * 2 ** k, dmax) * (1 + j * random.uniform(-1, 1)) return d if hint is None else max(d, hint) # the provider's wait is the floor def call_with_retry(send, attempts=3, ceiling=60): for k in range(attempts): r = send() # one request, same idempotency key if r.ok: return r if r.status not in RETRYABLE: return r # permanent: surface now if (r.retry_after or 0) > ceiling: return r # too long: let failover act if k < attempts - 1: time.sleep(wait(k, hint=r.retry_after)) return r def chain(requested, fallbacks, primary): out = [] for m in [requested, *fallbacks, primary]: if m not in out: out.append(m) return out def run_turn(models, profiles_for, ask): attempts = [] for m in models: for p in profiles_for(m): # OAuth, token, API key; oldest use first r = ask(m, p) if r.ok: return r attempts.append((m, p, r.reason)) if r.reason not in ADVANCE: return r # abort, refusal: stop the walk raise RuntimeError("all candidates failed", attempts)
Now press Present or Teach and explain it from memory. Cover the herd, the classifier, the budget, the chain, cooldowns, the pair-safe cut, the lease and the baseHash. Then go back to the hero and break the calls again.