# `Huginn.Clickhouse.Retry`
[🔗](https://github.com/nyo16/huginn/blob/v0.6.0/lib/huginn/clickhouse/retry.ex#L1)

Retries connection failures with capped, jittered exponential backoff.

Only `%Huginn.Error{reason: :connection}` is retried: no usable channel, a
dead connection process, or gRPC `UNAVAILABLE`. Everything else is returned
unchanged on the first failure:

  * ClickHouse errors (`:server`) are deterministic, so retrying cannot help.
  * Deadlines (`:timeout`) are not retried either. The server may still be
    executing (or may already have committed) the request, so repeating it
    could run a query twice or duplicate an insert.

`Huginn.Clickhouse.Client` decides *what* is retried: `query/2` repeats the
whole request, while inserts and streams only repeat channel acquisition,
i.e. nothing that has reached the server.

Each retry emits a `[:huginn, :query, :retry]` telemetry event, see
`Huginn.Clickhouse.Telemetry`.

# `delay`

```elixir
@spec delay(pos_integer(), keyword()) :: non_neg_integer()
```

Returns the delay in milliseconds to wait after failed attempt `attempt`
(1-based).

The delay is drawn uniformly from `1..cap` ("full jitter"), where
`cap = min(retry_backoff * 2 ** (attempt - 1), retry_max_backoff)`. Jitter
keeps many clients that failed together from retrying in lockstep. Returns
`0` when the cap is `0`.

# `transient?`

```elixir
@spec transient?(term()) :: boolean()
```

Returns `true` when `error` is worth retrying, i.e. it is a
`%Huginn.Error{reason: :connection}`.

# `with_retry`

```elixir
@spec with_retry((-&gt; {:ok, term()} | {:error, term()}), keyword(), map()) ::
  {:ok, term()} | {:error, term()}
```

Runs `fun` and retries it while it fails with a transient error.

`fun` is a 0-arity function returning `{:ok, term}` or
`{:error, %Huginn.Error{}}`. `metadata` is merged into the metadata of the
`[:huginn, :query, :retry]` event emitted before each retry.

## Options

  * `:retries` - maximum number of *additional* attempts after the first
    (default: `0`, i.e. no retries).
  * `:retry_backoff` - base delay in milliseconds (default: `100`).
  * `:retry_max_backoff` - upper bound for a single delay in milliseconds
    (default: `5000`).

See `delay/2` for how the delay before each retry is computed.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
