Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Exponential backoff #303

Closed
binaryfire opened this issue Oct 1, 2023 · 2 comments
Closed

Feature request: Exponential backoff #303

binaryfire opened this issue Oct 1, 2023 · 2 comments
Labels
enhancement New feature or request

Comments

@binaryfire
Copy link
Contributor

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
Copy link
Member

Sammyjo20 commented Oct 1, 2023

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 👍

@Sammyjo20 Sammyjo20 added the enhancement New feature or request label Oct 1, 2023
@binaryfire
Copy link
Contributor Author

binaryfire commented Oct 2, 2023

Moved to #304

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants