# How to add retry middleware to a Guzzle client in PHP

> Push Middleware::retry onto a Guzzle HandlerStack with rules you can test, set the timeouts, and keep a POST with no key, or a one-shot body, from going out twice.

Source: https://voxgig.com/howto/add-retry-middleware-to-a-guzzle-client

- Audience: api-consumer
- Level: intermediate
- Languages: php
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Push `Middleware::retry($decider, $delay)` onto the client's `HandlerStack`. Retry 429, 500, 502, 503, and 504 only for idempotent methods or requests with an `Idempotency-Key`, and retry a `ConnectException` for any method only when cURL never connected. Refuse to retry a body that cannot be rewound. Set `connect_timeout` and `timeout` on the client; `read_timeout` only covers streamed bodies.

---
## You will need

PHP 8.1 or later with the curl extension, and a Guzzle 7 client installed with Composer. The
sample's `vendor/` is committed, so its commands run without a network. Symfony's client, in the
comparison, needs PHP 8.2 at version 7.4. The stand-in server is
PHP's [built-in web server](https://www.php.net/manual/en/features.commandline.webserver.php),
started by the tests on 127.0.0.1 with four workers.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [caseyamcl/guzzle_retry_middleware](https://github.com/caseyamcl/guzzle_retry_middleware) | A Guzzle client that should honor Retry-After on 429 and 503 with no rules of your own | One more dependency, and its defaults retry a POST up to ten times, with a linear delay | Writes are not idempotent and you want the method rule visible in your code |
| [Guzzle Middleware::retry](https://github.com/guzzle/guzzle/blob/7.17.0/src/RetryMiddleware.php) | Any Guzzle client, when the retry rules must match the API's own semantics | Every rule is yours to write and test, and the default delay ignores Retry-After | You want HTTP defaults on day one, or the project is not on Guzzle |
| [Symfony RetryableHttpClient](https://symfony.com/doc/7.4/http_client.html#retry-failed-requests) | A project on Symfony's HttpClient, where `GenericRetryStrategy` holds a status table per method | A second HTTP client stack if your SDK is built on Guzzle | Your code and its middleware already run through a Guzzle `HandlerStack` |

The built-in middleware adds no dependency and decides nothing for you, which is both its cost and
the reason to choose it. The `guzzle_retry_middleware` package arrives with defaults for 429 and 503, and those
defaults apply to every method, including the POST you did not mean to repeat. Symfony splits the
difference with a status table that retries 500 only for idempotent methods, at the price of
moving off Guzzle.

## Write the decider and the delay

Guzzle calls the decider after every attempt with the retry count, the request, and either a
response or an exception. Return true to send the request again.

```php title="retry.php"
function retryDecider(int $maxRetries): callable
{
    return static function (
        int $retries,
        RequestInterface $request,
        ?ResponseInterface $response = null,
        ?\Throwable $exception = null
    ) use ($maxRetries): bool {
        if ($retries >= $maxRetries) {
            return false;
        }
        if ($exception instanceof ConnectException) {
            $errno = $exception->getHandlerContext()['errno'] ?? null;
            $retryable = in_array($errno, NOT_SENT_ERRNOS, true) || safeToResend($request);
        } elseif ($response !== null) {
            $retryable = in_array($response->getStatusCode(), RETRY_STATUSES, true)
                && safeToResend($request);
        } else {
            $retryable = false;
        }
        // A body that cannot be rewound would go out empty on the next attempt.
        return $retryable && $request->getBody()->isSeekable();
    };
}
```

`safeToResend` accepts the methods [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2)
calls idempotent, plus any request carrying an `Idempotency-Key`.[^1] `NOT_SENT_ERRNOS` holds
cURL errors 6 and 7, could not resolve and could not connect, from the
[cURL error list](https://curl.se/libcurl/c/libcurl-errors.html). Those two mean no byte left
the client, so even a POST is safe to send again.

The delay is the other callable. Guzzle passes it the retry count and the last response, and
sleeps for the milliseconds it returns:

```php title="retry.php"
function retryDelay(int $baseMs = 200, int $capMs = 5000, ?callable $random = null): callable
{
    $random ??= static fn (int $max): int => random_int(0, $max);

    return static function (int $retries, ?ResponseInterface $response = null) use ($baseMs, $capMs, $random): int {
        $after = $response?->getHeaderLine('Retry-After') ?? '';
        if (ctype_digit($after)) {
            return min((int) $after * 1000, $capMs);
        }
        return $random(min($capMs, $baseMs * 2 ** ($retries - 1)));
    };
}
```

Full jitter picks a delay between zero and the exponential bound, so a hundred clients that failed
together do not return together. Without a delay callable, Guzzle waits one, two, and four seconds.[^2]

## Push it onto the stack with all three timeouts

```php title="retry.php"
function retryingClient(string $baseUri, array $options = []): Client
{
    $stack = $options['handler'] ?? HandlerStack::create();
    $stack->push(
        Middleware::retry(retryDecider($options['max_retries'] ?? 2), $options['delay'] ?? retryDelay()),
        'retry'
    );
    unset($options['handler'], $options['max_retries'], $options['delay']);

    return new Client($options + [
        'base_uri' => $baseUri,
        'handler' => $stack,
        'connect_timeout' => 2.0,
        'timeout' => 10.0,
        'read_timeout' => 5.0,
    ]);
}
```

`push` places the layer nearer the transport than the ones `HandlerStack::create` added, as the
ordering example in the
[handlers and middleware](https://docs.guzzlephp.org/en/stable/handlers-and-middleware.html) guide
shows, so each attempt passes through the retry layer. The
[request options](https://docs.guzzlephp.org/en/stable/request-options.html) set the limits:
`connect_timeout` for the connection, `timeout` for each attempt, and `read_timeout` for each read
of a streamed body.

## Count what the server received

`demo.php` sends five clients at `/flaky`, which answers 503 twice and then 200:

```bash
php demo.php
```

```text output
Middleware::retry, GET                               3 requests, final 200
Middleware::retry, POST                              1 request, final 503
Middleware::retry, POST with Idempotency-Key         3 requests, final 200
guzzle_retry_middleware defaults, POST               3 requests, final 200
guzzle_retry_middleware, retry_on_methods GET, POST  1 request, final 503
```

The package retried the POST three times until `retry_on_methods` named GET alone. Its source sets
`retry_on_status` to 429 and 503 and `max_retry_attempts` to 10, with a delay of 1.5 seconds times
the retry count. Symfony, run once by `record.sh` against the same server, retries 503 for a
POST and stops at 500:

```text title="records/symfony.txt"
GET, 503 twice   3 requests, final 200
POST, 503 twice  3 requests, final 200
GET, 500 twice   3 requests, final 200
POST, 500 twice  1 request, final 500
```

## Check it worked

```bash
php test.php
```

```text output
ok 1 - a GET that fails twice is sent three times and succeeds
ok 2 - a POST without an Idempotency-Key is not retried on 503
ok 3 - a POST with an Idempotency-Key is retried
ok 4 - a refused connection is retried for any method
ok 5 - a POST that times out is a ConnectException and is not resent
ok 6 - control: a decider that retries every ConnectException resends that POST
ok 7 - a GET that times out is retried
ok 8 - a non-seekable body is not retried
ok 9 - control: without the check, the second attempt sends an empty body
ok 10 - the delay doubles, caps, and follows Retry-After in seconds
ok 11 - read_timeout ends a streamed body early, with no exception
ok 12 - retryingClient hands every attempt all three timeouts
1..12
# pass 12
# fail 0
```

The script exits 1 when a test fails. Each request count is read from the server's log, and each
attempt count from a layer pushed below the retry.

## When it goes wrong

The server stores an empty body. A body read from a socket or a pipe can be read once, and Guzzle
sends whatever is left on the second attempt, which is nothing. `pitfall.php` wraps its payload in
Guzzle's `NoSeekStream` to stand in for one:

```bash
php pitfall.php
```

```text output
no seekability check, non-seekable body  final 200, bodies received: 15 bytes, 0 bytes
retryDecider, non-seekable body          final 503, bodies received: 15 bytes
retryDecider, string body                final 200, bodies received: 15 bytes, 15 bytes
```

The first line is a write that succeeded with no data. Pass the body as a string, as the third
line does, so every attempt sends all of it.

A POST that timed out is sent twice. Guzzle's cURL handler turns error 28, operation timed out,
into a `ConnectException`, the same class as a refused connection, as its
[`CurlFactory`](https://github.com/guzzle/guzzle/blob/7.17.0/src/Handler/CurlFactory.php) shows.
A decider that retries every `ConnectException` sends again a request the server may have finished,
and test 6 counts three attempts. Read the `errno` from the handler context, as test 5 does.

A slow download never times out. `read_timeout` applies only to a request with `stream => true`,
which Guzzle sends through its stream handler. On a buffered request it does nothing, and on a
streamed one an expired read ends the body early with no exception, as test 11 shows.[^3]

## When not to do this

Do not retry a POST that has no idempotency key because a library's defaults allow it. A 503
from a gateway can follow a write that the service behind it committed.

Do not stack this on a client that already retries. An SDK built on Guzzle may push its own retry
layer, and three attempts inside three attempts is nine requests per call.

Skip the hand-written decider when the API publishes Retry-After on every 429 and 503 and your
calls are reads. The `guzzle_retry_middleware` package covers that case with less code to test. On Symfony's client,
use `RetryableHttpClient` and leave Guzzle out.

Do not keep this delay for an API whose Retry-After runs past five seconds. `retryDelay` caps the
wait at five, so a retry the server asked to come in a minute arrives early and is refused again.

## Related how-tos

- [Decide which status codes an SDK should retry](/howto/decide-which-status-codes-an-sdk-retries)

- [Enforce one total deadline across all retry attempts](/howto/enforce-a-total-deadline-across-retry-attempts)

- [Honor Retry-After without stalling a worker pool](/howto/honour-retry-after-without-stalling-a-worker-pool)

- [Add an API key with Guzzle middleware in PHP](/howto/api-key-guzzle-middleware)

## Last verified

Verified 2026-11-30 against PHP 8.3.6 with the curl extension, `guzzlehttp/guzzle` 7.17.0,
`caseyamcl/guzzle_retry_middleware` 2.13.0, and `symfony/http-client` 7.4.25. Every output block is
what the command preceding it printed, and `records/symfony.txt` is what `record.sh` wrote. The
gate runs the Guzzle commands from the committed `vendor/`; Symfony was installed and run once,
outside it.

[^1]: The header comes from an Internet-Draft, and the IETF Datatracker lists
[draft-ietf-httpapi-idempotency-key-header-09](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/)
as its revision. The decider treats the header as a promise that the server deduplicates, which
only the API's own documentation can confirm.

[^2]: Guzzle's [`RetryMiddleware`](https://github.com/guzzle/guzzle/blob/7.17.0/src/RetryMiddleware.php)
computes that default as two to the power of the retry count less one, times a thousand
milliseconds. The same formula was published as a static `exponentialDelay` method, which 7.17.0
marks deprecated since 7.11 and due for removal in 8.0. The formula outlives its name inside the
constructor.

[^3]: The stream handler converts the fraction of a second with `* 100000`, in
[`StreamHandler`](https://github.com/guzzle/guzzle/blob/7.17.0/src/Handler/StreamHandler.php),
where a microsecond count wants a million. A `read_timeout` of 0.3 seconds therefore reaches
`stream_set_timeout` as 30,000 microseconds. For 1.2 seconds the subtraction leaves a float a
hair under 0.2, so the call receives one second and 19,999.