Skip to main content

Overview

The Result.tryPromise function supports automatic retry logic with configurable backoff strategies. This is essential for handling transient failures in network requests, database operations, and other unreliable operations.

Basic Retry Configuration

Retry logic is configured through the retry option in Result.tryPromise:
The times parameter specifies retry attempts, not total attempts. With times: 3, the operation will be attempted up to 4 times total (1 initial + 3 retries).

Backoff Strategies

Three backoff strategies are available to control the delay between retry attempts:
Doubles the delay with each retry attempt. Best for operations that may need increasing time to recover.
Formula: delayMs * 2^attemptNumber

Selective Retry with shouldRetry

Not all errors should trigger a retry. Use the shouldRetry predicate to retry only specific error types:
If the shouldRetry predicate throws an error, it will result in a Panic. Ensure your predicate is safe and handles all error cases.

Async Error Enrichment

You can enrich errors asynchronously in the catch handler, enabling complex retry logic based on external state:

Real-World Patterns

Circuit Breaker Pattern

Combine retry logic with state tracking to implement a circuit breaker:

Retry with Jitter

Add randomization to avoid thundering herd problems:

Database Transaction Retry

Handle deadlock retries in database transactions:

Testing Retry Logic

Test retry behavior by tracking attempt counts:

Best Practices

1

Choose appropriate backoff

Use exponential backoff for network errors, linear for rate limits, and constant for quick operations.
2

Set reasonable limits

Don’t retry indefinitely. Set times based on your operation’s SLA and timeout constraints.
3

Use shouldRetry for selective retry

Only retry transient errors. Don’t retry validation errors, auth failures, or client errors (4xx).
4

Add timeout protection

Combine retry logic with operation timeouts to prevent hanging indefinitely.
5

Monitor retry metrics

Track retry attempts and success rates to identify systemic issues.
For operations without built-in retry support, consider wrapping them in Result.tryPromise with retry configuration rather than implementing custom retry logic.