Reliability
Resilience
Keep working when something you depend on is slow or broken.
Your service calls other things: a payment provider, another service, a database replica. Sooner or later one of them gets slow or fails. Without protection, a slow dependency makes your threads pile up waiting, your service becomes slow too, and the failure spreads to everything that calls you. Resilience annotations stop that. Put them on any method of a provider (the class and method must be open).
| Annotation | The problem it solves |
|---|---|
@TimeLimit | a call that never returns holds a thread forever |
@Retry | a call that fails now and then, and works if you try again |
@CircuitBreaker | a dependency that is down: stop hammering it, fail fast, recover by itself |
@Bulkhead | one slow dependency using every thread and starving the rest |
@Fallback | when it fails anyway, return something useful instead of an error |
@Injectable
open class ExchangeRates(private val provider: RateProvider, private val cache: RateCache) {
@TimeLimit(millis = 2_000) // 4: never wait more than 2 s
@CircuitBreaker(name = "rates", failureThreshold = 5, openMillis = 30_000) // 3: after 5 failures in a row, stop calling for 30 s
@Retry(attempts = 3, delayMillis = 100, multiplier = 2.0, jitter = 0.2) // 2: try up to 3 times, waiting 100 ms, 200 ms (+/- 20%)
@Fallback("cachedRate") // 1: if everything above fails, use the cache
@Bulkhead(name = "rates", maxConcurrent = 10) // 5: at most 10 calls at once
open fun rate(from: String, to: String): Double = provider.fetchRate(from, to)
open fun cachedRate(from: String, to: String): Double = cache.last(from, to) ?: throw IllegalStateException("no rate known")
}The annotations wrap each other from the outside in, in the order they are listed in the source file: the first one written is the outermost. A common, sensible order from the outside is @Fallback, @CircuitBreaker, @Retry, @TimeLimit: the fallback catches whatever escapes, the breaker counts the final result of a call (after retries), and each retry is time-limited.
Time limit
@TimeLimit(millis = 800) open fun lookup(id: String): Customer = crm.find(id)Throws OperationTimeoutException when the method takes longer. Handlers run on virtual threads, so waiting is cheap, but a request that waits 60 seconds still ties up a connection, a database transaction, and a user.
Retry
@Retry calls the method again when it fails. Use it for calls to things outside your process: a payment API, a search service, a database that restarts. Every option has a default, so @Retry on its own means three tries, waiting about 100 ms and then 200 ms, with 20% jitter.
@Retry(
attempts = 5, // tries in all, the first one included
delayMillis = 2_000, // wait 2 s before the second try
multiplier = 2.0, // then 4 s, 8 s, 16 s (use 1.0 for the same wait every time)
maxDelayMillis = 30_000, // never wait longer than 30 s
jitter = 0.2, // each wait varies by up to 20% either way
statuses = [429, 503, 504], // retry only these HTTP status codes
)
open suspend fun charge(order: Order): Receipt = payments.charge(order)| Option | Default | Meaning |
|---|---|---|
attempts | 3 | tries in all, the first one included |
delayMillis | 100 | the wait before the second try |
multiplier | 2.0 | each wait is this many times the one before |
maxDelayMillis | 10 000 | the longest any single wait gets |
jitter | 0.2 | how far each wait may vary, as a fraction (0.2 = up to 20% either way), so clients that failed together do not retry together |
on | all exceptions | retry only these exception types |
stopOn | none | never retry these, even if they match on |
statuses | none | retry only failures that carry one of these HTTP status codes |
What counts as a failure with a status: HttpStatusException from the HTTP client, or any exception that implements HasStatusCode. With statuses = [503], a 503 is tried again and a 404 is not. Without statuses, the other options decide.
Some failures cannot be fixed by trying again. An exception that implements NotRetryable is never retried, and an open circuit breaker is one of those. Put @Retry outside @CircuitBreaker (as in the example above) and a call that finds the circuit open fails at once.
On a suspend function the waits are delays, so the coroutine suspends and other work on the same thread continues. The processor generates the retry wrapper for suspend methods, so the same annotation works in both styles.
Each retry is logged as a warning, such as Retry: Payments.charge failed (try 2 of 5): HTTP 503; trying again in 2000 ms.
Only retry idempotent operations (reading, or writing with an idempotency key). Retrying "charge the card" without one can charge twice.
Migrating from @RetryWith: @RetryWith still works but is deprecated. @Retry has every option it had. The old core @Retry(backoff = false) is now @Retry(multiplier = 1.0), and its delayMillis and on are unchanged.
Circuit breaker
Think of the breaker in a fuse box. It has three states:
CLOSED --(5 failures in a row)--> OPEN --(30 s)--> HALF_OPEN --(trial call works)--> CLOSED
^ |
+--(trial call fails)+- CLOSED: calls go through; failures are counted.
- OPEN: calls fail at once with
CircuitOpenException(it carriesretryAfter), without touching the dependency, so it can recover. - HALF_OPEN:
halfOpenCallstrial calls are let through. One success closes the breaker; one failure opens it again.
@CircuitBreaker(name = "payments", failureThreshold = 5, openMillis = 30_000, halfOpenCalls = 1,
ignore = [CardDeclined::class]) // a declined card is a normal answer, not a sign that the provider is down
open fun charge(card: Card, cents: Long): Receipt = gateway.charge(card, cents)Give the breaker a name: methods that share a name share the state, which is what you want when three methods call the same provider. Read the state for dashboards: Resilience.states() returns {payments=OPEN}, and Resilience.breaker("payments") gives counters (calls, failed, rejected).
Bulkhead
A ship's bulkheads keep a leak in one compartment from sinking the ship. @Bulkhead(maxConcurrent = 10) lets at most 10 calls run at the same time; the 11th waits up to maxWaitMillis (0 means it does not wait) and then fails with BulkheadFullException. Use one per dependency, so a slow supplier can only use its own 10 slots.
Fallback
@Fallback("cachedRate", on = [CircuitOpenException::class, IOException::class])
open fun rate(from: String, to: String): Double = ...
open fun cachedRate(from: String, to: String): Double = ... // same parameters
open fun cachedRate(from: String, to: String, cause: Throwable): Double = ... // or the same plus the exception, to log itThe fallback method must exist on the same class with the same parameters (optionally one more for the exception). Decide what a fallback means for the business: an old exchange rate may be fine for a price estimate and wrong for a settlement.
Handling the errors in HTTP
@Catch(CircuitOpenException::class, BulkheadFullException::class)
class Unavailable : ExceptionFilter {
override suspend fun catch(exception: Throwable, ctx: ExecutionContext) =
HttpResponse(503, mapOf("retry-after" to "30"), """{"error":"dependency unavailable"}""".toByteArray())
}Testing
Resilience.reset() clears breaker and bulkhead state between tests. The annotations take millisecond values, so tests are quick; make a method fail on purpose and assert that the 6th call throws CircuitOpenException.