saloonphp / saloon

🤠 Build beautiful API integrations and SDKs with Saloon
https://docs.saloon.dev
MIT License
2.09k stars 107 forks source link

Feature request: Exponential backoff #303

Closed binaryfire closed 1 year ago

binaryfire commented 1 year ago

Exponential backoff really helps with unreliable APIs. A second failed attempt usually means the service is overloaded or there's a problem with network connectivity. In both cases it's best to pause for a longer period before retrying again.

It'd be great to have this option in Saloon. This is how I implement it in my apps. Happy to work on a PR if you're interested?


    public function execute(int $id): array
    {
        $attempt = 0;

        while ($attempt < $this->maxRetries + 1) {
            try {
                $response = Http::withToken($this->token)->get("{$this->baseUrl}/{$id}");

                if ($response->successful()) {
                    return $response->json();
                }

                throw new RequestException($response);

            } catch (RequestException $e) {

                if ($attempt === $this->maxRetries) {
                    throw $e;
                }

                sleep($this->initialDelay * (2 ** $attempt));
            }

            $attempt++;
        }
    }
Sammyjo20 commented 1 year ago

Hey @binaryfire

This is an awesome idea ☺️

Looking at your code, I don't think this would be even that big to implement into Saloon v3. Check out the new send() method in Saloon v3 - with the global retries everything is wrapped in a similar while, and we even have an interval - so I would say it would be as simple as adding a boolean to enable exponential back off?

https://github.com/saloonphp/saloon/blob/v3/src/Traits/Connector/SendsRequests.php#L30

Let me know your thoughts but I'd definitely be open for a PR for Saloon v3 👍

binaryfire commented 1 year ago

Moved to https://github.com/saloonphp/saloon/pull/304