Self-Healing

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.

Break the calls

2%

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

Failure Is the Normal Case

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?

Say it aloud

F equals n times p.

F
F the failures you expect in one day, on average.
n
n the calls the gateway makes in one day.
p
p the chance that one call fails, from 0 to 1.
In plain words

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 numbers

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.

Count the drizzle

Each red tick is one failure on a 24 hour line. Drag the calls per day, then pick a better success rate.

10,000

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:

  1. Expect the failure: wrap every outbound call in recovery code.
  2. Classify it: decide which kind of failure it is.
  3. Recover: run the fix that matches that kind.
FailureExampleReflex
A brief blipa reset connection, a busy secondretry after a wait
A provider in troublerate limits for an hour, billing offfailover to another credential or model
A full contextthe transcript passes the windowcompaction of old turns
A crash mid-sendthe gateway dies with a reply queuedrecovery from the durable queue
A bad requesta malformed body, a 404surface 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.

  1. Backoff and jitter: how long to wait, and why the waits must differ.
  2. What deserves a retry: the classifier in front of the retry.
  3. Budgets for model calls: how many tries, for how long.
  4. Walk the candidate chain: rotate credentials, then change models.
  5. Cooldowns and the pinned profile: how long to rest a failing credential.
  6. Compaction: shrink the context and never orphan a tool result.
  7. Recover after a crash: finish the replies a dead gateway left behind.
  8. Self-repair with guardrails: doctor, the security audit and safe config patches.
  9. Every reflex, live: inject a failure and watch the fix.
  10. Field guide: terms, numbers, a checklist, the core code.
A gateway makes 50,000 calls a day, and each fails with chance 0.002. Why must it be built around failure?

Chapter 1

Backoff and Jitter

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.

Say it aloud

d-k equals the min of d-zero times two to the k, and d-max, all times one plus j times u.

dk
d-k the wait before the next try, after k failed tries.
min( , )
the min of take the smaller of the two values.
d0
d-zero the first wait: 400 ms for OpenClaw's shared channel sends.
2k
two to the k 2 multiplied by itself k times: the wait doubles after each failure.
dmax
d-max the cap: 30 s for those channel sends.
j
j the jitter fraction: 0.1, so a wait moves by up to 10%.
u
u a fresh random number from −1 to 1, drawn by each caller for each wait.
In plain words

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 numbers

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.

Release the herd

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.

0%

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

Why does each client add a random jitter to its backoff wait?

Chapter 2

What Deserves a Retry

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?

Say it aloud

P-fail equals q to the A.

Pfail
P-fail the chance that every try fails, so the caller sees an error.
q
q the chance that one try fails, from 0 to 1.
A
to the A multiply q by itself once per try; A is the number of tries.
In plain words

Each try fails with chance q. All A tries fail only if each one does, so multiply q by itself A times.

With numbers

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").

Route an error

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.

A model call returns 429 with Retry-After: 120. What does OpenClaw do?

Chapter 3

Budgets for Model Calls

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.

Say it aloud

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.

T
T the total time spent waiting across all retries, in seconds.
Σk=0R−1
the sum over k from zero to R minus one add one wait for each of the R retries.
d0
d-zero the first wait: about 1 s for OpenClaw model calls.
dmax
d-max the cap: 60 s for rate limits, 30 s for other transient failures.
In plain words

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.

With numbers

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.

Spend the budget

Each bar is one wait; the line is the running total. Switch the failure kind and drag the retry count.

15

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.

With a 1 s first wait, doubling and a 30 s cap, why can a "8 retries in 90 s" budget stop before 8 retries?

Chapter 4

Walk the Candidate Chain

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:

  1. Auth-profile rotation. An auth profile is one stored credential for a provider, an OAuth login or an API key. The gateway tries the next profile for the same provider.
  2. Model fallback. If every profile fails, the gateway moves to the next model in the candidate chain, the ordered list of models it may try.

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.

Walk the chain

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.

ErrorWalkWhy
auth failure, rate limit, overload, timeout, billingadvancethis way in is blocked; another may work
model not foundadvancethis model is gone; the next one exists
context overflow that compaction could not fixadvance, if safe to replaya model with a larger window may fit it
the person pressed stopstopnobody wants the answer now
a final provider refusalstopanother model must not route around it
no candidates leftstop, reportone 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.

The person typed /model openai/gpt, and that model is rate-limited on both of its credentials. What happens?

Chapter 5

Cooldowns and the Pinned Profile

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:

FailureCooldown
rate limit, with a provider waitexactly the provider's wait
rate limit, with no provider waitnone; the current turn still rotates
timeouts and other failures30 s, then 1 min, then 5 min (the cap)
billing failure, revoked keydisabled 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.

Fail a credential

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.

Say it aloud

t-end equals the min of t-last plus ten minutes, and t-first plus thirty minutes.

tend
t-end the time the session stops trying the fallback first.
tlast
t-last the time of the fallback's latest successful turn.
10 min
ten minutes the idle window: each success extends it.
tfirst
t-first the time of the first fallback turn.
30 min
thirty minutes the hard cap from the first fallback.
In plain words

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 numbers

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.

A credential gets a 429 with no retry time and no reset header. What cooldown does OpenClaw give it?

Chapter 6

Compaction Without Orphans

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.

Say it aloud

T-c equals the min of zero point seven five times W, and W minus R.

Tc
T-c the context size, in tokens, at which compaction starts.
0.75
zero point seven five three quarters of the window.
W
W the model's context window in tokens.
R
R the compaction reserve: room kept for the summary, 20,000 tokens in OpenClaw's example.
In plain words

Take three quarters of the window W. Take the window W minus the reserve R. Start compaction at whichever is smaller.

With numbers

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.

Cut the transcript

Drag how many entries to keep. Turn off Pair-safe cut and find a cut that orphans a result.

5

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.

The planned cut lands on a tool result. What does a pair-safe compaction do?

Chapter 7

Recover After a Crash

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.

Say it aloud

t-free equals t-renew plus L.

tfree
t-free the time recovery may take over a reply whose sender vanished.
trenew
t-renew the sender's last renewal; a live sender renews every 20 s.
L
L the lease length: 60 s in OpenClaw.
In plain words

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 numbers

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.

Crash mid-send

Drag the crash time. Then pick what the evidence says about the send.

31 s

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.

A sender renewed its lease at 10:00:40 and crashed at 10:00:55. When may recovery take the reply, and why wait?

Chapter 8

Self-Repair with Guardrails

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:

ToolWhat it does
openclaw doctorhealth checks for the gateway, channels, plugins, model routing and config; --fix runs guided repairs
openclaw security auditfinds risky settings; --deep adds live checks on the running gateway
openclaw security audit --fixapplies 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:

  1. config.schema.lookup: read what a setting means and which values are valid.
  2. config.get: read the current config and its hash, a short fingerprint of that exact version.
  3. 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.

Race two patches

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.

Why does config.patch require the baseHash from config.get?

Chapter 9

Every Reflex, Live

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.

Inject a failure

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.

FailureReflexChapter
blipretry with capped, jittered backoff1, 3
bad requestsurface at once2
provider downrotate credential, then fall back, then cool down4, 5
context overflowcompact pair-safe, then retry6
crash mid-sendrecover from the durable queue after the lease7
Which pairing of failure and reflex is right?

Chapter 10

Field Guide

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.

TermMeaningOpenClaw number
backoffa wait that doubles after each failure, up to a capchannel sends: 400 ms min, 30 s cap
jittera random part of each wait10%
channel retrytries for one send3 attempts
retryable codeserrors that may clear408, 409, 429, 5xx, transport
provider wait ceilingthe longest Retry-After honoured on one credential60 s
model retry budgettries per outage16 attempts for rate limits; 8 retries in 90 s otherwise
candidate chainmodels to try, in orderrequested, fallbacks, primary, no duplicates
cooldownrest for a failed credentialprovider's wait; 30 s, 1 min, 5 min; billing 10 min
fallback stickinesstry the fallback first after a rate limit10 min idle, 30 min cap
compaction startcontext size that triggers a summarymin(0.75 W, W − reserve)
leasea sender's expiring claim on a queued reply60 s, renewed every 20 s
config write limitpatches per method and device30 per 60 s

Checklist

The core, in code

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)

Where each thread continues

The takeaway. Expect failure, sort it, and match the fix: retry the blip, rotate and fall back past a blocked provider, compact a full context, recover a crashed send, and surface what only a person can fix.
In one sentence, what makes a gateway self-healing?

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.

Anatomy of an Agent Gateway, Lesson 9: Self-Healing & Reliability
OpenClaw docs · Next: tools and sandboxing · Back to Gleams