Skip to content
Back to skills

Resilience

ASecurity

Make code survive a slow, failing or flaky dependency with the least code. Covers a timeout on every outbound call, bounded retries with backoff only where repeating is safe, idempotency keys on retried writes, and a decided answer for when the dependency is down. Use whenever a change adds or touches a call to another system (HTTP API, database, queue, cache, subprocess, third-party SDK), when a consumer handles messages that can arrive twice, when a slice's criteria say what happens when a ...

  • 2 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added December 3, 2026
developmenttypescriptpythongonodeapidatabase

Works with

  • cli
  • api

Security analysis

A100/100

Scanned December 3, 2026

npx -y skills add restierecon/tbv --skill resilience --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Resilience?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Resilience
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/restierecon-resilience/badge)](https://www.skillsdirectory.com/skills/restierecon-resilience)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: resilience
description: Make code survive a slow, failing or flaky dependency with the least code. Covers a timeout on every outbound call, bounded retries with backoff only where repeating is safe, idempotency keys on retried writes, and a decided answer for when the dependency is down. Use whenever a change adds or touches a call to another system (HTTP API, database, queue, cache, subprocess, third-party SDK), when a consumer handles messages that can arrive twice, when a slice's criteria say what happens when a dependency fails, or when an incident traced back to a hung or retried call.
---

# Resilience

Every call to another system will one day be slow, fail, or succeed twice. Decide
what this code does in each case, with the least code that does it, using what the
project already has. Nothing more, nothing less.

## 1. List the calls and how each can fail
For every outbound call the change adds or touches, write one line:
`<call> — slow | down | error | duplicate → <what happens>`. For example:
- `GET rates API` — slow or down → the quote page shows the last saved rate
- `POST payment charge` — timeout → retried with the same idempotency key, never charged twice
- `orders queue consumer` — same message twice → the second one is ignored

A call with no line gets no new code. A line you can't fill in is a product decision:
in a TBV project it goes back to /grill, not into the diff.

## 2. Use what the project already has
Search for the HTTP client, its timeout settings and any retry helper already in use
(`timeout=`, `AbortSignal.timeout`, `context.WithTimeout`, `tenacity`, `backoff`,
`urllib3.Retry`, `p-retry`, `axios-retry`, `Polly`, `resilience4j`, `retry`). Reuse it.
Never add a retry or circuit-breaker library for one call: a plain loop is shorter
to read. A new dependency needs its one-line justification, and in a TBV project an ADR.

## 3. Put a timeout on every call
Most clients wait forever by default: Python `requests`, Node `fetch`, Go's
`http.DefaultClient`. Set one on every call, from the caller's budget: if the
request must answer in 10 s, a call inside it gets a few seconds, not 30. Database
and queue clients get a connect and a query or receive timeout. A missing timeout is
a defect, not a style choice.

## 4. Retry only what is safe to repeat
Retry when both hold:
- the failure is transient: connection error, timeout, HTTP 429, 502, 503 or 504
- repeating the call can't do the work twice: a read, a `PUT` or `DELETE`, or a write
  that carries an idempotency key (section 5)

Then:
- 3 attempts at most, with exponential backoff and full jitter (a random wait between
  0 and `base * 2 ** attempt`), and `Retry-After` when the server sends one
- never retry other 4xx errors: the request is wrong and will stay wrong
- retry in one layer only; a retry inside a retry multiplies the load on a dependency
  that is already struggling
- the whole loop stays inside the caller's time budget

```python
import random
import time

import requests

RETRYABLE = {429, 502, 503, 504}
ATTEMPTS = 3


def fetch_rate(currency):
    for attempt in range(1, ATTEMPTS + 1):
        try:
            response = requests.get(f"{RATES_URL}/{currency}", timeout=(2, 5))
        except (requests.ConnectionError, requests.Timeout):
            if attempt == ATTEMPTS:
                raise
        else:
            if response.status_code not in RETRYABLE or attempt == ATTEMPTS:
                response.raise_for_status()
                return response.json()["rate"]
        time.sleep(random.uniform(0, 0.2 * 2 ** attempt))
```

```typescript
const RETRYABLE = new Set([429, 502, 503, 504]);
const ATTEMPTS = 3;

export async function fetchRate(currency: string): Promise<number> {
  for (let attempt = 1; ; attempt++) {
    try {
      const response = await fetch(`${RATES_URL}/${currency}`, { signal: AbortSignal.timeout(5000) });
      if (!RETRYABLE.has(response.status) || attempt === ATTEMPTS) {
        if (!response.ok) throw new Error(`rates returned ${response.status}`);
        return (await response.json()).rate;
      }
    } catch (error) {
      const transient = error instanceof TypeError || (error instanceof DOMException && error.name === "TimeoutError");
      if (!transient || attempt === ATTEMPTS) throw error;
    }
    await new Promise((resolve) => setTimeout(resolve, Math.random() * 200 * 2 ** attempt));
  }
}
```

## 5. Make writes safe to repeat
A timeout on a write doesn't mean it failed: the other side may have done the work.
- Sending: create the idempotency key once, with the record it belongs to (the order,
  the payment), store it, and send the same key on every attempt. A key made fresh on
  each attempt protects nothing.
- Receiving: queues and webhooks deliver at least once. Record each message or event
  ID under a unique constraint in the same transaction as the work, and treat a
  duplicate as already done.

```python
def handle_order_paid(event, connection):
    with connection:
        inserted = connection.execute(
            "INSERT INTO processed_events (id) VALUES (?) ON CONFLICT DO NOTHING", (event.id,)
        ).rowcount
        if inserted:
            connection.execute("UPDATE orders SET paid = 1 WHERE id = ?", (event.order_id,))
```

## 6. Decide what happens when it's down
| Answer | Use it when | Default |
|---|---|---|
| Fail fast with a clear error (503, a retryable job failure) | the caller can't go on without the result | yes |
| Fall back (last saved value, feature hidden, work queued for later) | the criteria say stale or partial is acceptable | no: needs a criterion |
| Circuit breaker | a hot path calls a dependency that fails for minutes at a time, and the project already has one | no |

Never invent a fallback the criteria don't name: a silently stale price is worse
than an error. Log the outcome once, with the attempt count, as the observability
skill describes: `warn` when a retry or fallback saved the call, `error` when it
didn't.

## 7. Prove it with a test
Each line from section 1 gets one test that makes the dependency misbehave and checks
the result. Replace the sleep so the test runs in milliseconds.

```python
def test_rate_fetch_retries_a_503_then_returns_the_rate(monkeypatch):
    responses = iter([FakeResponse(503), FakeResponse(200, {"rate": 1.1})])
    monkeypatch.setattr(requests, "get", lambda *args, **kwargs: next(responses))
    monkeypatch.setattr(time, "sleep", lambda seconds: None)
    assert fetch_rate("EUR") == 1.1


def test_rate_fetch_does_not_retry_a_400(monkeypatch):
    calls = []
    monkeypatch.setattr(requests, "get", lambda *args, **kwargs: calls.append(1) or FakeResponse(400))
    with pytest.raises(requests.HTTPError):
        fetch_rate("EUR")
    assert len(calls) == 1
```

A duplicate message gets a test that delivers it twice and checks the work happened
once. A timeout gets a test that checks the timeout is passed, not one that waits for it.

## 8. Keep it readable
Write the loop where the call is. No comments: `RETRYABLE` and `ATTEMPTS` say what
they are. No retry decorators, wrappers or base classes of your own, unless the
project already uses them. When a third call needs the same loop, move it into the
module that owns those calls, not into a `utils` file.

## In a TBV project
A slice that adds a call to another system carries a criterion for its failure line
from section 1, like "when the rates API is down, the quote page shows the last saved
rate" (slice-planning skill). Build exactly that. Gaps you notice in other calls go
under FLAG CANDIDATES, not into the diff.

## Never
- An outbound call without a timeout.
- A retry on a write without an idempotency key, or on a 4xx other than 429.
- Unbounded retries, retries without backoff, or retries at more than one layer.
- A fallback the criteria don't name.
- A new retry or circuit-breaker dependency added for one call.
- Comments explaining a retry loop.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.