Timeout

  1. Usage
  2. How It Works
  3. Timeouts with Retries
  4. Timeout vs Context
  5. Event Listeners

Timeouts can be used to cancel executions that take too long to complete or limit load on systems.

Usage

Creating and using a Timeout is simple:

// Timeout after 10 seconds
timeout := timeout.With[any](10*time.Second)
err := failsafe.Run(Connect, timeout)

How It Works

If an execution is canceled by a Timeout, the execution and policies composed inside the timeout will return timeout.ErrExceeded. See the execution cancellation page for more on cancellation.

Timeouts with Retries

When a Timeout is composed outside a RetryPolicy, a timeout occurrence will cancel any inner retries:

failsafe.Run(Connect, timeout, retryPolicy)

When a Timeout is composed inside a RetryPolicy, each attempt will get its own timeout, and a timeout occurrence will not automatically cancel any outer retries:

failsafe.Run(Connect, retryPolicy, timeout)

Timeout vs Context

While a Timeout is similar to a Context, in that they both can cause an execution to be canceled, Timeouts can be composed with other policies. Additionally, when a Timeout is triggered, it can be reset by an outer RetryPolicy, whereas a Context cannot be reset once it is done.

With this in mind, prefer a Timeout when you want to limit execution time or use retries, and prefer a Context when you want to cancel an entire execution.

Event Listeners

A Timeout can notify you with an ExecutionEvent when a timeout has been exceeded by an execution attempt:

builder.OnTimeoutExceeded(func(e failsafe.ExecutionEvent[Connection]) {
  logger.Error("Connection timed out")
})