Overview
TheResult.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 theretry 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:- Exponential
- Linear
- Constant
Doubles the delay with each retry attempt. Best for operations that may need increasing time to recover.Formula:
delayMs * 2^attemptNumberSelective Retry with shouldRetry
Not all errors should trigger a retry. Use theshouldRetry predicate to retry only specific error types:
Async Error Enrichment
You can enrich errors asynchronously in thecatch 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.