SymfonyWorld Online 2020
100% online
30+ talks + workshops
Live + Replay watch talks later

New in Symfony 5.2: Retryable HTTP client

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());
Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

It's awesome!
Thanks ! @Jérémy
Awesome feature I don't miss as long as everything works :)

Btw, The "multiplier" option seems to be linear according to the comment in the example, but it is exponential as described in the text. One of these is wrong.
> RetryableHttpClient(HttpClient::create());

That looks like an unfortunate composition. This can be read like "new FooHttpClient (new BarHttpClient)". Why do you inject an object of the same type (judging by its name)?
@Daniel that pattern is called Decorator, it allows to add behaviors to a core algorithm without changing the class itself. Here, RetryableHttpClient adds the retry mechanism without needing to change anything in HttpClient.
Login with SymfonyConnect to post a comment