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());
|
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.
New in Symfony 5.2: Retryable HTTP client symfony.com/blog/new-in-symfony-5-2-retryable-http-client
Tweet thisComments
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.
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)?
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Maxime Doutreluingne said on Oct 5, 2020 at 09:43 #1
Thanks ! @Jérémy