Symfony News

New in Symfony 5.2: Retryable HTTP client

Jérémy Derussé

Contributed by
Jérémy Derussé
in #38182.

Sometimes, requests made with an HTTP client fail because of different reasons, (network issues, temporary server errors, etc.) In Symfony 5.2 we’ve improved the HttpClient component with a new optional feature to automatically retry the failed requests.

When using the HttpClient inside a Symfony application, use the retry_failed option to enable and configure this feature:

1
2
3
4
5
6
# config/packages/framework.yaml
framework:
    # ...
    http_client:
        # ...
        retry_failed: true

That’s all. Now Symfony will retry up to 3 times all failed requests with a status code included in (423, 425, 429, 500, 502, 503, 504, 507, 510) and it will wait exponentially from 1 second (first retry) to 4 seconds (third attempt).

All parameters of this feature are configurable as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# config/packages/framework.yaml
framework:
    # ...
    http_client:
        # ...
        retry_failed:
            # only retry errors with these HTTP codes
            http_codes: [429, 500]
            max_retries: 2
            # waiting time between retries (in milliseconds)
            delay: 1000
            # if set, the waiting time of each retry increases by this factor
            # (e.g. first retry: 1000ms; second retry: 3 * 1000ms; etc.)
            multiplier: 3

There are other configuration options to define the maximum delay, to use a custom service to implement a “backoff retry” strategy, etc.

When using the HttpClient outside of a Symfony application, use the new RetryableHttpClient class to wrap your regular HTTP client:

1
2
3
use Symfony\Component\HttpClient\RetryableHttpClient;

$client = new RetryableHttpClient(HttpClient::create());

Sponsor the Symfony project.


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook