Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nice way to add retry functionality to api calls?

Tags:

php

I have an api class to contact a REST api for mailing list management. It includes methods such as subscribe(), unsubscribe(), update(), etc.

In my client code, I have lines such as

Api::subscribe($email, array(..));

Because of occasional failures, we want to add retry functionality to each call. If a call fails the first time, we want to retry once or twice more, before we finally give up.

The straight-forward way to do this is

public static function subscribe($email, array $lists ) {
  $success = FALSE;
  $retries = 3;
  while ( ! success && retries > 0 ) {
    // API call goes here
    $retries--;
  }
}

Rinse and repeat for each method.

In the interests of DRY (Don't Repeat Yourself), I was wondering if there was a nice, design-patterny way to wrap my calls in retries without having to repeat the while loop for each method.

If not, and the simple way is the best fit, that's fine. I just wanted to see if there was a better way out there that I was not aware of.

like image 468
user151841 Avatar asked Nov 14 '25 18:11

user151841


1 Answers

public function retry($apiCall, $retries) {
    $success = false;
    while (!$success && $retries > 0 ) {
        $success |= $apiCall();
        $retries--;
    }
}

public static function subscribe($email, array $lists) {
  retry(function() {
    // your API call here
  }, 3);
}

You simply construct an anomymous function and pass the anonomous function to the code that handles the retrying. Obviously this should be a bit more elaborate to allow returning values (which can be added quite trivially) or to be observable.

One way to make it observable is by passing a callback:

public function retry($apiCall, $retries, $callback) {
    $success = false;
    while (!$success && $retries > 0 ) {
        $success |= $apiCall();
        $retries--;
    }
    $callback($success);
}

You'd simply need to pass the proper callback that does the notification. You can expand greatly on this by passing more elaborate parameters about the kind of event and kind of failure, number of retries etc. depending on your exact needs.

like image 161
StandByUkraine Avatar answered Nov 17 '25 10:11

StandByUkraine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!