resil overview
Add retries, circuit breakers, and timeouts to calls to databases and APIs, nested as closures with errors returned unchanged.
Use resil in code that calls something over the network: HTTP and gRPC clients, database queries, message brokers, and third-party APIs. It has three building blocks, Retry, Breaker, and Timeout. Each has the same two methods, Do and Get, and they nest like ordinary function calls.
Installation
You need Go 1.27 or later. Run the installation command in your Go module.
go get github.com/luminyra/resilThree building blocks
Retrycalls an operation again after a failure, with exponential backoff, a cap, and jitter. Its zero value is ready to use: three attempts, waiting 100ms and then 200ms. An error wrapped withStopends retrying at once.Breaker, created withNewBreaker, opens after a number of consecutive failures or when a failure rate is reached over a sliding window, and then returnsErrOpenwithout calling the dependency. After a cooldown it lets one probe through, and closes if the probe succeeds.Timeoutlimits how long a call may take. When its own deadline fires, the error matchesErrTimeout. When the caller cancels, the error is returned unchanged.
Do is for operations that return only an error. Get is a Go 1.27 generic method for operations that also return a value.
When to use it
Only retry operations that are safe to repeat: reads, and writes with an idempotency key. Use Breaker when a dependency can be down for a while and waiting on it would pile up requests, and Timeout when a call can hang. Do not wrap code in the same process. A panic or a bug does not go away on the second attempt.
Go standard library integration
Every call takes a context.Context, and errors come back unchanged, so errors.Is and errors.As keep working. Operations run on the caller's goroutine. resil starts no goroutines, so operations must return when their context ends. Waits and timing use the standard time package, so tests can use testing/synctest to skip backoff and cooldowns instantly.
Performance
A retry whose first attempt succeeds takes about 4 ns. A closed breaker takes about 11 ns in consecutive-failure mode and 47 ns in failure-rate mode. An open breaker rejects a call in about 23 ns. None of these allocate. The figures are the overhead around an operation; a network call usually takes thousands of times longer.
The quickstart runs a retry first, then combines all three building blocks.