---
agentTools:
  projectIndex: https://resilience4j.readme.io/llms.txt
---

# Kotlin

Getting started with resilience4j-kotlin

[block:api-header]
{
  "title": "Introduction"
}
[/block]

Integration for [Kotlin](https://kotlinlang.org/) coroutines. This module adds extensions for executing and decorating `suspend` functions as well as custom operators for the coroutine reactive primitive [Flow](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/).

Extension functions that accept Kotlin suspend functions are provided for RateLimiter, Retry, CircuitBreaker, TimeLimiter, and semaphore-based Bulkheads. No extensions for ThreadPoolBulkhead or Caches are currently provided.

For Flow, there are operators provided for RateLimiter, Retry, CircuitBreaker, TimeLimiter, and semaphore-based Bulkheads. No extensions for ThreadPoolBulkhead or Caches are currently provided.

[block:api-header]
{
  "title": "Setup"
}
[/block]

Add the Kotlin module of Resilience4j to your compile dependency, along with whichever core modules are needed:

[block:code]
{
  "codes": [
    {
      "code": "repositories {\n    jCenter()\n} \n\ndependencies {\n\tcompile \"io.github.resilience4j:resilience4j-kotlin:${resilience4jVersion}\"\n  // also have a dependency on the core module(s) needed - for example, retry:\n\tcompile \"io.github.resilience4j:resilience4j-retry:${resilience4jVersion}\"\n}",
      "language": "groovy"
    }
  ]
}
[/block]

[block:api-header]
{
  "title": "Usage"
}
[/block]

Two extension functions are declared for each of  `CircuitBreaker`, `RateLimiter`, `Retry`, and `TimeLimiter`: one to execute a suspend function, and one to decorate a suspend function.

[block:api-header]
{
  "title": "Usage - Suspending Functions"
}
[/block]

Two extension functions are declared for each of  `CircuitBreaker`, `RateLimiter`, `Retry`, and `TimeLimiter`: one to execute a suspend function, and one to decorate a suspend function.

[block:code]
{
  "codes": [
    {
      "code": "val circuitBreaker = CircuitBreaker.ofDefaults()\nval result = circuitBreaker.executeSuspendFunction {\n   // call suspending functions here\n}\n\nval function = circuitBreaker.decorateSuspendFunction {\n   // call suspending functions here\n}\nval result = function()",
      "language": "kotlin"
    }
  ]
}
[/block]

The suspend functions suspend where usage of the normal methods would block.  For example, calls to a `RateLimiter` which need to be delayed to fit within the rate limit suspend before the given function is executed.
No changes are made to the coroutine context of the given suspend functions.

[block:api-header]
{
  "title": "Usage - Flow"
}
[/block]

There are extensions for `Flow<T>` defined for each of `CircuitBreaker`, `RateLimiter`, `Retry`, and `TimeLimiter`. The order in which operators are chain is important and directly correlates to the order in which resilience primitives are evaluated. Considering the following example, `flowOf(1).retry(...).timeLimiter(...)`, all of the retry attempts must completed within the duration of the supplied TimeLimiter.

[block:code]
{
  "codes": [
    {
      "code": "val retry = Retry.ofDefaults()\nval rateLimiter = RateLimiter.ofDefaults()\nval timeLimiter = TimeLimiter.ofDefaults()\nval circuitBreaker = CircuitBreaker.ofDefaults()\n  \nflowOf(1, 2, 3)\n  .retry(retry)\n  .rateLimiter(rateLimiter)\n  .timeLimiter(timeLimiter)\n  .circuitBreaker(circuitBreaker)\n  .collect { println(it) }",
      "language": "kotlin"
    }
  ]
}
[/block]

[block:api-header]
{
  "title": "Bulkhead"
}
[/block]

Decorating a suspend function or Flow with a `Bulkhead` special attention needs to be paid to configuration value of `maxWaitTime`.  If `maxWaitTime` is non-zero, the call will *block* until the max wait time is reached or permission is obtained. This blocking is restricted to the dispatcher `Dispatchers.IO`. Although this helps mitigate some of the performance impact introduced by the usage of the blocking API, it is not recommended to use this extension function with Bulkheads with non-zero max wait times.

If the coroutine scope is cancelled, either normally or exceptionally, the acquired permission will be released. After which no success or failure events will be recorded.

No extension functions for thread-pool based bulkheads are provided.

[block:api-header]
{
  "title": "CircuitBreaker"
}
[/block]

Decorating a suspend function or Flow with a `CircuitBreaker` does not add any additional suspension points. In the case of decorated Flows, attempts to collect will throw a `CallNotPermittedException` if the circuit breaker state is `OPEN`.

If the coroutine scope is cancelled, either normally or exceptionally, the acquired permission will be released. After which no success or failure events will be recorded.

[block:api-header]
{
  "title": "Rate Limiter"
}
[/block]

Suspend functions decorated with a `RateLimiter` use `delay()` in order to suspend before executing the decorated function if the rate limit has been reached.

Flows decorated with a `RateLimiter` will invoke `delay()` on attempts to collect if the rate limit has been reached.

[block:api-header]
{
  "title": "Retry"
}
[/block]

Suspend functions and Flows decorated with a `Retry` use `delay()` in order to suspend between retries.

[block:api-header]
{
  "title": "Time Limiter"
}
[/block]

The `TimeLimiter` extension functions simply uses `withTimeout()` from `kotlinx-coroutines`, using the timeout from the receiver's configuration.  Specifically, this means:

* On timeout, a `TimeoutCancellationException` is raised, rather than a `TimeoutException` as with methods for non-suspending functions.
* When a timeout occurs, the coroutine is cancelled, rather than the thread being interrupted as with methods for non-suspending functions.
* After the timeout, the given block can only be stopped at a cancellable suspending function call.
* The `cancelRunningFuture` configuration setting is ignored - on timeout, the suspend function is always cancelled even if the `cancelRunningFuture` is set to `false`.

Flows decorated with a `TimeLimiter` will ensure that the entire Flow is consumed within the configured limit once collection has begun.