# Retries

Canonical URL: https://developers.iagenify.com/sdk/concepts/retries/
Language: en

The client retries exactly one thing, once: a 401. Everything else is handed to you, because only you know whether repeating it is safe.

Status: one retry · 401 only

## The one retry {#the-one}

On a `401` the client drops the cached JWT, keeps the refresh token, and replays the request once. A session that expired mid-flight, or a signing change, is absorbed without reaching your code.

> **Only the JWT is dropped**
>
> The refresh token survives, so a client built from a stored session rather than a key recovers too.

## What is not retried {#not-retried}

- `402` — retrying will not create credits.
- `4xx` in general — the request is wrong; repeating it keeps it wrong.
- `5xx` — the call may have had an effect. Repeating a send, a deploy or a write is your decision, not the client's.
- `timeout` and `unreachable` — same reason: the client cannot know whether the work happened.

## Retrying on your side {#your-own}

Branch on `status` and `code` — never on the message text, which is prose and can change.

```javascript
import { IaGenifyError, NotEnoughCredits } from "iagenify";

async function withRetry(call, { tries = 3 } = {}) {
  for (let attempt = 1; ; attempt++) {
    try {
      return await call();
    } catch (err) {
      const transient = err instanceof IaGenifyError
        && (err.status >= 500 || err.code === "timeout" || err.code === "unreachable");

      if (!transient || err instanceof NotEnoughCredits || attempt === tries) throw err;

      await new Promise((r) => setTimeout(r, 2 ** attempt * 250));
    }
  }
}

const prices = await withRetry(() => api.catalogue());   // safe: a read
```

> **Only wrap calls that are safe to repeat**
>
> Reads, always. A send, a deploy, a purchase or a write: only if you can tell whether the first attempt landed.

```python
import time
from iagenify import IaGenifyError, NotEnoughCredits

def with_retry(call, *, tries=3):
    for attempt in range(1, tries + 1):
        try:
            return call()
        except IaGenifyError as error:
            transient = error.status >= 500 or error.code in ("timeout", "unreachable")
            if not transient or isinstance(error, NotEnoughCredits) or attempt == tries:
                raise
            time.sleep(2 ** attempt * 0.25)

prices = with_retry(api.catalogue)   # safe: a read
```
