DefaultHedgingPolicy

class DefaultHedgingPolicy(config: HedgingConfig, onHedgingUsed: (Int) -> Unit = {}) : HedgingPolicy

A default implementation of HedgingPolicy that executes a given block of code multiple times in parallel and returns the result of the first one to complete successfully.

This policy launches a configurable number of parallel attempts (HedgingConfig.attempts). A delay (HedgingConfig.stagger) can be introduced between the start of each subsequent attempt.

If the first attempt to complete is successful, its result is returned immediately, and all other running attempts are canceled to save resources.

If the first attempt to complete fails with an exception, the policy waits for other attempts to complete. If any subsequent attempt succeeds, its result is returned. If all attempts fail, the exception from the first failing attempt is re-thrown.

Parameters

config

The HedgingConfig to configure the behavior of the policy, such as the number of attempts and the delay between them.

onHedgingUsed

Optional callback invoked when the result comes from a non-primary attempt (attemptIndex > 0); useful for telemetry.

Constructors

Link copied to clipboard
constructor(config: HedgingConfig, onHedgingUsed: (Int) -> Unit = {})

Functions

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

Executes a given suspending block of code according to the hedging policy.