DEV Community

Enoch
Enoch

Posted on

A Tiny Retry Utility That Saves You From Random Failures

Sometimes the difference between a flaky system and a reliable one is just a few lines of retry logic. Network calls fail, APIs timeout, and transient issues happen more often than we’d like to admit.

Instead of scattering retry logic everywhere, here’s a small reusable utility with exponential backoff:

// Simple retry utility with exponential backoff
public static T retry(Supplier task, int maxAttempts) {
int attempt = 0;
long delay = 200;

while (true) {
    try {
        return task.get();
    } catch (Exception e) {
        if (++attempt >= maxAttempts) {
            throw e;
        }
        try {
            Thread.sleep(delay);
        } catch (InterruptedException ignored) {}
        delay *= 2; // exponential backoff
    }
}
Enter fullscreen mode Exit fullscreen mode

}

Why this works:

Handles temporary failures (network hiccups, rate limits)

Exponential backoff reduces pressure on downstream services

Keeps your business logic clean and focused

Usage example:

String result = retry(() -> apiCall(), 3);

Simple, effective, and saves you from a lot of random headaches in production.

Top comments (1)

Collapse
 
buildbasekit profile image
buildbasekit

Nice utility. This is one of those small things that makes a big difference in production.

  • Good call on exponential backoff. Reduces pressure instead of making failures worse
  • Keeping retry logic out of business code is the real win here

One thing I’d push on:

  • Retrying blindly can be dangerous → Not all exceptions should be retried (e.g. validation errors) → Missing jitter can cause retry storms under load

Would be interesting to see a version with exception filtering + jitter added.