Skip to content

Retry Patterns

Implement resilient retry logic with exponential backoff for handling transient failures.

When calling external services (APIs, databases), transient failures are common. Retry patterns help make systems resilient by automatically retrying failed operations with delays.

Exponential Backoff: Delay between retries grows exponentially (1s, 2s, 4s, 8s…) to give failing systems time to recover.

Jitter: Adding randomness to delays prevents thundering herd - when many clients retry simultaneously and overwhelm a recovering service.

Implement two retry functions:

  1. Retry - Basic exponential backoff with configurable parameters
  2. RetryWithJitter - Adds random jitter to prevent synchronized retries
  3. Handle context cancellation for early exit
  4. Test with a simulated unreliable function

Exponential Backoff with Jitter

~25 minmedium

Implement retry logic with exponential backoff and jitter

  • Exponential Backoff: Delays grow exponentially to give systems time to recover
  • Jitter: Random variation prevents synchronized retries (thundering herd problem)
  • Context Cancellation: Respect cancellation signals to avoid wasted work
  • Configurable Retry: Separate configuration from logic for flexibility
  • Transient Failures: Distinguish between retryable and permanent failures