Retrying
In software development, it’s common to encounter situations where an operation may fail temporarily due to various factors such as network issues, resource unavailability, or external dependencies. In such cases, it’s often desirable to retry the operation automatically, allowing it to succeed eventually.
Retrying is a powerful mechanism to handle transient failures and ensure the successful execution of critical operations. In Effect retrying is made simple and flexible with built-in functions and scheduling strategies.
In this guide, we will explore the concept of retrying in Effect and learn how to use the retry and retryOrElse functions to handle failure scenarios. We’ll see how to define retry policies using schedules, which dictate when and how many times the operation should be retried.
Whether you’re working on network requests, database interactions, or any other potentially error-prone operations, mastering the retrying capabilities of effect can significantly enhance the resilience and reliability of your applications.
retry
The Effect.retry function takes an effect and a Schedule policy, and will automatically retry the effect if it fails, following the rules of the policy.
If the effect ultimately succeeds, the result will be returned.
If the maximum retries are exhausted and the effect still fails, the failure is propagated.
This can be useful when dealing with intermittent failures, such as network issues or temporary resource unavailability. By defining a retry policy, you can control the number of retries, the delay between them, and when to stop retrying.
Example (Retrying with a Fixed Delay)
import { Effect, Schedule } from "effect"
let count = 0
// Simulates an effect with possible failuresconst task = Effect.async<string, Error>((resume) => { if (count <= 2) { count++ console.log("failure") resume(Effect.fail(new Error())) } else { console.log("success") resume(Effect.succeed("yay!")) }})
// Define a repetition policy using a fixed delay between retriesconst policy = Schedule.fixed("100 millis")
const repeated = Effect.retry(task, policy)