Bulkhead

Bulkhead pattern implementation for concurrency isolation.

Limits the number of concurrent calls to protect shared resources from overload. When the maximum number of concurrent calls is reached, additional calls are either queued (up to BulkheadConfig.maxWaitingCalls) or rejected immediately.

Basic usage:

val bulkhead = Bulkhead.create(config = BulkheadConfig(maxConcurrentCalls = 5))

val result = bulkhead.execute {
callExternalService()
}

With waiting queue:

val bulkhead = Bulkhead.create(config = BulkheadConfig(
maxConcurrentCalls = 10,
maxWaitingCalls = 20,
maxWaitDuration = 5.seconds
))

With fallback:

val result = bulkhead.executeOrFallback(
fallback = { cachedResponse() }
) {
callExternalService()
}

DSL builder:

val bulkhead = bulkhead {
maxConcurrentCalls = 5
maxWaitingCalls = 10
maxWaitDuration = 3.seconds
}

With listener:

bulkhead.addListener(object : BulkheadListener {
override fun onCallRejected() {
metrics.incrementRejected()
}
})

Statistics:

val stats = bulkhead.statistics()
println("Total: ${stats.totalCalls}, Rejected: ${stats.rejectedCalls}")
println("Utilization: ${stats.utilizationRate * 100}%")

Types

Link copied to clipboard
object Companion

Factory for Bulkhead.

Properties

Link copied to clipboard

The configuration this bulkhead was created with.

Functions

Link copied to clipboard
suspend fun activeCalls(): Int

Returns the current number of active calls.

Link copied to clipboard

Adds a listener for bulkhead events.

Link copied to clipboard
suspend fun <T> execute(block: suspend () -> T): T

Executes an operation through the bulkhead.

Link copied to clipboard
suspend fun <T> executeOrFallback(fallback: suspend () -> T, block: suspend () -> T): T

Executes an operation with a fallback if the bulkhead is full or times out.

Link copied to clipboard
suspend fun resetStatistics()

Resets all statistics counters to zero.

Link copied to clipboard

Returns a snapshot of the current bulkhead statistics.

Link copied to clipboard
suspend fun <T> tryExecute(block: suspend () -> T): T?

Tries to execute an operation, returning null if the bulkhead is full or times out.

Inherited functions

Link copied to clipboard

Adapts this Bulkhead into a Policy.