Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,17 @@ All notable changes to **initphp/http** will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Changed (breaking)

- **`RetryPolicy` retries only idempotent methods by default** (RFC 9110 §9.2.2: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT`, `DELETE`). A `POST` or `PATCH` request is now sent once, even when a policy is attached. To retry them deliberately, pass the new last constructor argument `retryableMethods`, for example `new RetryPolicy(retryableMethods: [...RetryPolicy::DEFAULT_RETRYABLE_METHODS, 'POST', 'PATCH'])`. The list opens only the methods it names: the old behaviour (every method, including custom ones such as `QUERY` or `PROPFIND`) is restored only by naming each of them. New API: `RetryPolicy::DEFAULT_RETRYABLE_METHODS`, `getRetryableMethods()`, `isRetryableMethod()`.

### Fixed

- `Retry-After` is now capped at the policy's `maxDelay`. Previously a server could make the client wait for as long as it asked (`Retry-After: 3600` meant an hour).
- A request whose body is not seekable is no longer retried. The retry used to send an empty body, because the first attempt had already consumed the stream; now the first response is returned, or the first exception is thrown.

## [4.0.0] - 2026-11-22

### Changed (breaking)
Expand Down
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,12 @@ $client = (new Client())->withRetryPolicy(new RetryPolicy(
maxAttempts: 4, // 1 initial try + up to 3 retries
baseDelay: 0.1, // first backoff interval, seconds
multiplier: 2.0, // 0.1s, 0.2s, 0.4s, ...
maxDelay: 30.0, // cap on any single interval
maxDelay: 30.0, // cap on any single wait, Retry-After included
jitter: 0.5, // up to 50% random reduction (anti thundering-herd)
));

// Every verb helper inherits the policy transparently.
// Every verb helper inherits the policy, but POST and PATCH are still sent
// once unless you list them in `retryableMethods` (see below).
$response = $client->get('https://api.example.com/flaky');
```

Expand All @@ -177,10 +178,15 @@ Behaviour and backward-compatibility:
- A non-retryable `4xx`/`5xx` response is still **returned, never thrown** (PSR-18).
- A retryable response that exhausts the attempt cap is returned as-is (the last
response); a transport exception that exhausts the cap is re-thrown.
- Only **idempotent methods** (`GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT`, `DELETE`)
are retried by default; `POST` and `PATCH` are sent once unless you list them in
`retryableMethods`. A request whose body is not seekable is also sent once,
since a retry could not send the body again.
- A parseable `Retry-After` header (delay-seconds or HTTP-date) on a retryable
response **overrides** the computed backoff unless you disable it.
- The retryable status set, whether transport exceptions are retried, and
`Retry-After` handling are all configurable on `RetryPolicy`.
response **overrides** the computed backoff, capped at `maxDelay`, unless you
disable it.
- The retryable status set, the retryable methods, whether transport exceptions
are retried, and `Retry-After` handling are all configurable on `RetryPolicy`.

```php
// Customise: only retry 429/503, never on transport exceptions, ignore Retry-After.
Expand Down
6 changes: 4 additions & 2 deletions docs/Client-Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,15 @@ $client = (new Client())->withRetryPolicy(new RetryPolicy(
maxAttempts: 4, // 1 initial try + up to 3 retries
baseDelay: 0.1, // first backoff interval, seconds
multiplier: 2.0, // 0.1s, 0.2s, 0.4s, ...
maxDelay: 30.0, // cap on any single interval
maxDelay: 30.0, // cap on any single wait, Retry-After included
jitter: 0.5, // up to 50% random reduction
));
```

- Retried by default: transport exceptions (`retryOnException`) and the status codes `408`, `425`, `429`, `500`, `502`, `503` and `504` (`retryableStatusCodes`).
- A parseable `Retry-After` header on a retryable response overrides the computed backoff unless `respectRetryAfter` is `false`.
- Only **idempotent methods** are retried by default: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT` and `DELETE`. A `POST` or `PATCH` is sent once; list it in `retryableMethods` to opt in.
- A request whose body is not seekable is sent once too, because a retry could not send the body again.
- A parseable `Retry-After` header on a retryable response overrides the computed backoff, up to `maxDelay`, unless `respectRetryAfter` is `false`.
- A non-retryable `4xx`/`5xx` response is still **returned, never thrown**. A retryable response that exhausts `maxAttempts` is returned as-is; a transport exception that exhausts it is re-thrown.

The full reference (every `RetryPolicy` parameter and clamp, the backoff formula, `Retry-After` parsing and the sleeper seam) is on the [Client Retry](Client-Retry.md) page.
Expand Down
28 changes: 23 additions & 5 deletions docs/Client-Retry.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,22 @@ $response = $client->get('https://api.example.com/reports');

With a policy attached, `sendRequest()` runs this loop (the convenience methods such as `get()` and `post()` go through it too):

0. If the request must not be replayed (see [Which requests are retried](#which-requests-are-retried)), send it once and stop: the first response is returned, or the first exception thrown.
1. Send the request. This is attempt 1.
2. If the transport throws a `Psr\Http\Client\NetworkExceptionInterface` (DNS, TCP, TLS, timeout): retry when the policy has `retryOnException` on and another attempt is allowed. Otherwise the exception is re-thrown.
3. If a response arrives and its status is **not** in the retryable set, return it. This is also true for `4xx` and `5xx` responses: PSR-18 says they are returned, never thrown.
4. If its status is retryable and another attempt is allowed, wait, then go back to step 1. If no attempt is left, the last response is returned as-is.

The wait is the [`Backoff`](#backoff) delay for that attempt, or the `Retry-After` value when the policy honours it (see [`RetryAfter`](#retryafter)).
The wait is the [`Backoff`](#backoff) delay for that attempt, or the `Retry-After` value when the policy honours it (see [`RetryAfter`](#retryafter)). Either way it never exceeds `maxDelay`.

> **The method is not considered.** The policy retries `POST`, `PATCH` and every other method the same way. A request that failed after the server already acted on it can therefore run twice. Attach a policy only where that is safe, for example for idempotent requests, or make the operation idempotent on the server (an idempotency key, for example). Because `withRetryPolicy()` returns a clone, you can keep a retrying client for safe calls and a plain one for the rest.
### Which requests are retried

A retry sends the request again, so two kinds of request are **sent exactly once**, whatever the status or exception:

- **A method that is not in `retryableMethods`.** By default only the idempotent methods of RFC 9110 §9.2.2 are retried: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT` and `DELETE`. `POST` and `PATCH` are not, because the server may already have acted on a request that failed on the way back, and a retry would run it twice. To retry them anyway, list them in `retryableMethods` (see below), ideally together with an idempotency key the server honours.
- **A request whose body cannot be rewound.** Each attempt reads the body from the start. A stream that is not seekable (a socket, a pipe, a request body read once) is already used up after the first attempt, so a retry would send an **empty** body. Such a request is not retried; its first response is returned, or its first exception is thrown. Strings, `php://temp` and files are seekable and are retried normally.

Because `withRetryPolicy()` returns a clone, you can keep a retrying client for safe calls and a plain one for the rest.

Errors that are not transport failures are not retried: `RequestException` (a request that cannot be marshalled) and `ClientException` (for example, cURL cannot be initialised) propagate immediately. See [Client Exceptions](Client-Exceptions.md).

Expand All @@ -40,6 +48,7 @@ new RetryPolicy(
bool $retryOnException = true,
?array $retryableStatusCodes = null, // null = RetryPolicy::DEFAULT_RETRYABLE_STATUS
bool $respectRetryAfter = true,
?array $retryableMethods = null, // null = RetryPolicy::DEFAULT_RETRYABLE_METHODS
)
```

Expand All @@ -52,9 +61,10 @@ new RetryPolicy(
| `jitter` | `0.5` | Ratio in `[0.0, 1.0]`. Out-of-range values are clamped. `0.0` disables jitter. |
| `retryOnException` | `true` | Retry when the transport throws a network exception. |
| `retryableStatusCodes` | see below | Status codes that trigger a retry. Passing a list replaces the default set; it is not merged with it. |
| `respectRetryAfter` | `true` | Let a parseable `Retry-After` header on a retryable response set the wait. |
| `respectRetryAfter` | `true` | Let a parseable `Retry-After` header on a retryable response set the wait, capped at `maxDelay`. |
| `retryableMethods` | see below | HTTP methods that may be retried, compared case-insensitively. Passing a list replaces the default set; it is not merged with it. An empty list never retries. |

The default retryable set is the constant `RetryPolicy::DEFAULT_RETRYABLE_STATUS`: `408`, `425`, `429`, `500`, `502`, `503` and `504`.
The default retryable set is the constant `RetryPolicy::DEFAULT_RETRYABLE_STATUS`: `408`, `425`, `429`, `500`, `502`, `503` and `504`. The default methods are the constant `RetryPolicy::DEFAULT_RETRYABLE_METHODS`: `GET`, `HEAD`, `OPTIONS`, `TRACE`, `PUT` and `DELETE`.

```php
// Retry only on rate limiting and 503, and never on transport errors.
Expand All @@ -63,6 +73,12 @@ $policy = new RetryPolicy(
retryOnException: false,
retryableStatusCodes: [429, 503],
);

// Also retry POST. Only do this when the endpoint is idempotent, for example
// because it honours an Idempotency-Key header.
$policy = new RetryPolicy(
retryableMethods: [...RetryPolicy::DEFAULT_RETRYABLE_METHODS, 'POST'],
);
```

### Methods
Expand All @@ -76,8 +92,10 @@ $policy = new RetryPolicy(
| `getJitter()` | `float` | The (clamped) jitter ratio. |
| `isRetryOnException()` | `bool` | Whether network exceptions are retried. |
| `getRetryableStatusCodes()` | `list<int>` | The retryable status codes. |
| `getRetryableMethods()` | `list<string>` | The retryable methods, upper-cased and without duplicates. |
| `isRespectRetryAfter()` | `bool` | Whether `Retry-After` is honoured. |
| `isRetryableStatus(int $statusCode)` | `bool` | Whether the status is in the retryable set (strict comparison). |
| `isRetryableMethod(string $method)` | `bool` | Whether the method may be retried (case-insensitive). |
| `shouldRetry(int $attempt)` | `bool` | `true` when `$attempt < maxAttempts`. `$attempt` is 1-based: `1` means the first try has just finished. |

The policy has no setters. To change a value, build a new `RetryPolicy`.
Expand Down Expand Up @@ -153,7 +171,7 @@ RetryAfter::parse('Wed, 21 Oct 2015 07:28:00 GMT', 1445412420); // 60.0
RetryAfter::parse(''); // null
```

In the client, `Retry-After` applies to retryable **responses** only, not to network exceptions, and only when `respectRetryAfter` is `true`. When it applies, its value is used **as is**: it is neither jittered nor capped by `maxDelay`. A server that sends `Retry-After: 3600` makes the client wait an hour before the next attempt. If that is too long for your use case, set `respectRetryAfter: false` so the capped backoff is used, or keep `maxAttempts` low.
In the client, `Retry-After` applies to retryable **responses** only, not to network exceptions, and only when `respectRetryAfter` is `true`. When it applies, its value is not jittered but it **is capped by `maxDelay`**: a server that sends `Retry-After: 3600` with the default `maxDelay` of `30.0` makes the client wait 30 seconds, not an hour. Lower `maxDelay` to bound the wait further, or set `respectRetryAfter: false` to ignore the header and use the backoff delay.

## `SleeperInterface` and `Sleeper`

Expand Down
41 changes: 36 additions & 5 deletions src/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use function is_resource;
use function is_string;
use function max;
use function min;
use function preg_match;
use function strlen;
use function strpos;
Expand Down Expand Up @@ -488,8 +489,11 @@ public function head(string $url, $body = null, array $headers = [], string $ver
* enabled, transport exceptions) are retried up to the policy's
* max-attempts cap, spaced by exponential backoff with jitter. A
* `Retry-After` header on a retryable response overrides the computed delay
* when the policy opts in. PSR-18 semantics are preserved: a non-retryable
* 4xx/5xx response is returned, never thrown.
* when the policy opts in, capped at the policy's `maxDelay`. Only the
* policy's retryable methods (idempotent ones by default) are retried, and
* only when the request body can be rewound; any other request is sent
* once. PSR-18 semantics are preserved: a non-retryable 4xx/5xx response is
* returned, never thrown.
*
* @param RequestInterface $request
* @return ResponseInterface
Expand All @@ -504,6 +508,14 @@ public function sendRequest(RequestInterface $request): ResponseInterface
return $this->transport($request);
}

// A request that must not be replayed gets a single attempt: a method
// that is not idempotent may already have been acted on by the server,
// and a body that cannot be rewound would be re-sent empty. In both
// cases the first outcome (response or exception) is the answer.
if (!$this->isReplayable($policy, $request)) {
return $this->transport($request);
}

$backoff = new Backoff($policy, $this->jitterRandomizer);
$attempt = 0;

Expand Down Expand Up @@ -533,10 +545,29 @@ public function sendRequest(RequestInterface $request): ResponseInterface
}
}

/**
* Whether $request may be sent more than once under $policy: its method
* is retryable and its body can be rewound. Any failure while reading
* those two accessors counts as "not replayable"; the single attempt that
* follows reports it as a {@see RequestException}, as PSR-18 requires.
*
* @param RetryPolicy $policy
* @param RequestInterface $request
* @return bool
*/
private function isReplayable(RetryPolicy $policy, RequestInterface $request): bool
{
try {
return $policy->isRetryableMethod($request->getMethod()) && $request->getBody()->isSeekable();
} catch (\Throwable $e) {
return false;
}
}

/**
* Resolve the delay before the next retry for a retryable *response*:
* honour a parseable `Retry-After` header when the policy opts in,
* otherwise fall back to the jittered exponential backoff for this attempt.
* honour a parseable `Retry-After` header when the policy opts in (capped
* at the policy's `maxDelay`), otherwise fall back to the jittered exponential backoff for this attempt.
*
* @param RetryPolicy $policy
* @param Backoff $backoff
Expand All @@ -549,7 +580,7 @@ private function retryDelay(RetryPolicy $policy, Backoff $backoff, ResponseInter
if ($policy->isRespectRetryAfter()) {
$retryAfter = RetryAfter::fromResponse($response);
if ($retryAfter !== null) {
return $retryAfter;
return min($retryAfter, $policy->getMaxDelay());
}
}

Expand Down
Loading
Loading