It's a blog

Guzzle 6 retry middleware

Recently I switched from using Guzzle 5 to Guzzle 6 in my mediawiki-api-base PHP library. Everything went very smoothly except for there being no compatible version of the retry-subscriber that I had previously used. The subscriber has been replaced by retry middleware of which I was provided an extracted example. In this post I cover my implementation for the mediawiki-api-base library.

Guzzle 5

With Guzzle 5 you would create a retry subscriber with a filter and then attach it to the event emitter for the guzzle client. A full example can be seen below where RetrySubscriber::createStatusFilter can be seen here.

Guzzle 6

Guzzle 6 got rid of its event system and switched to the afore mentioned middleware system.

Middleware is added to a handler stack upon Client construction as seen below:

The retry middleware takes two parameters, the first is the callable function that decides if a request / response should be retried and the last deciding how long to wait before retrying (similar to in Guzzle 6). Each can be seen below.

When implementing this for the mediawiki-api-base library I actually ended up creating a MiddlewareFactory which can be seen at on github here which is fully tested here.

This implementation includes a more complex retry decider including logging.



  1. is there a provision of setting timeout with guzzle retry middleware? I want the retry attempt to be made upon expiration of pre-defined timeout interval

  2. Thanks for the hint. The retry middleware is really a must when having to deal with an API that isn’t 100% reliable.

  3. I’m curious, is this where OAuth token refreshes would be performed, or is that something which would have to be down further back up the chain?

    • addshore

      November 5, 2017 at 1:16 pm

      I have not really worked with OAuth & Guzzle yet so can’t give you the ‘right’ answer. It definitely sounds possible though.

  4. I’ve been following your example & making multiple asynchronous requests with Promise/any() functions.
    When retry middleware is not used & some of the api end-points are down, this is working fine. But when adding retry middleware while some end-points are down, the request gets slow. It seems that, though other end-points are up, but the failing points are blocking and retrying.


    Request Call Code:
    trait SearchesFlights

    /* $client = new Client();*/

  5. Should Line 20 be \GuzzleHttp\Exception\ConnectException?
    I am getting following error.
    Argument 4 passed to guzzelRetryClient::{closure}() must be an instance of GuzzleHttp\Psr7\RequestException, instance of GuzzleHttp\Exception\ConnectException given

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2018 Addshore

Theme by Anders NorenUp ↑

%d bloggers like this: