Effect TS · Lesson 3 of 8
Row two of the evaluation table: the retry loop you've copied into every BullMQ project becomes a value you can build, hand around, and attach to anything.
Row two of the evaluation table promised: cross-cutting concerns — like retrying and timeouts — become reusable values, not copy-pasted loops. Today you verify that hands-on, against the backoff code you wrote in BullMQ. Lesson 2's error channel is the other half: retries only make sense once failures are values.
You wrote this loop, or one shaped like it, in the queue infrastructure course:
async function withRetry<T>(fn: () => Promise<T>): Promise<T> {
let delay = 100;
for (let i = 0; ; i++) {
try { return await fn(); }
catch (e) {
if (i >= 4) throw e;
await sleep(delay);
delay *= 2;
}
}
}
// ...and a second copy for timeouts,
// and a third for logging...
Three pains, all yours: copying — every project gets a fresh hand-rolled loop; entanglement — the retry rules live inside the business logic, so you can't change "wait longer" without touching the function; and no composition — a loop can't be handed to anything else. You can't say "this one, but capped tighter" without a new parameter, then a new copy.
In Effect, "when to try again" is not a loop — it's a policy: a plain value that describes the plan. The type is called a Schedule — an unchangeable description of when and how often to act again, built out of small named pieces2. You hand the effect and the policy to Effect.retry, and the runtime does the looping1:
import { Effect, Schedule } from 'effect';
// wait 100ms before each new try:
const policy = Schedule.spaced('100 millis');
const safer = Effect.retry(chargeCard, policy);
Two behaviours, both verified in the sandbox below:
UpstreamDown still compile; nothing about retrying weakens the type.Each constructor makes one simple plan; you snap plans together. All of this is checked against the bundled 3.22.1:
| Builder | Plan it makes | Verified note |
|---|---|---|
Schedule.recurs(5) | Give up after 5 tries | Counts retries, not attempts: first try plus 5 retries = 6 attempts |
Schedule.spaced('50 millis') | Wait 50ms before each new try | Never stops on its own — pair it with a cap |
Schedule.exponential('10 millis', 2) | Wait 10ms, then 20ms, then 40ms… | Delay doubles each time; measured 10+20+40 ≈ 70ms for 3 retries |
Schedule.fixed('1 second') | Start a new try every second, no matter how long the attempt took | Steady drumbeat; spaced waits after each finish instead |
Schedule.once / Schedule.forever | Retry once / never stop | Pre-built values — no parentheses |
Schedule.intersect(a, b) | Both plans at once; the tighter cap wins | intersect(recurs(3), spaced(x)) stops after 3 retries |
Schedule.union(a, b) | Keep going while either plan allows | The longer plan wins: union(recurs(2), recurs(5)) → 5 retries |
Schedule.jittered(s) | Wrap s's waits with randomness | Spreads load when many callers retry at once |
The classic production recipe is a cap plus a delay: intersect(recurs(5), spaced('100 millis')) — "at most five more tries, 100ms apart." In BullMQ you'd express that as job options; here it's a value you could pass as an argument, store in config, or test without waiting.
Run it: three log lines, then green. Now change calls < 3 to calls < 99 (never succeeds): six attempts, then red — the last UpstreamDown comes back out of the error channel. Swap spaced('50 millis') for exponential('10 millis', 2) and watch the gaps grow. Finally replace policy with the shorthand { times: 5 } — same cap, no waiting.
Effect.retry only retries failures in the error channel. A throw inside Effect.sync is a defect — a bug, lesson 2's crash class — and we verified the runtime ignores it: one attempt, straight to the Cause with tag Die. Your BullMQ loop happily retried any thrown error, including the ones that were really bugs. Effect forces the failure-vs-defect decision before retrying is even possible. More rules, yes — but they're the rules that keep "retry three times" from silently masking a broken line of code.
The other cross-cutting concern from your queue work: capping how long you'll wait. Effect.timeout races the effect against a duration; if the clock wins, the slow work is abandoned and a typed failure named TimeoutException lands in the error channel3. And because it's a tagged failure like any other, lesson 2's catchTag is how you recover:
const program = Effect.gen(function* () {
return yield* Effect.timeout(slowProvider, '200 millis');
}).pipe(
Effect.catchTag('TimeoutException', () =>
Effect.succeed('serving cached data'))
);
When exhaustion should switch to a plan B instead of handing the failure upward, Effect.retryOrElse(effect, policy, fallback) runs the fallback and returns its value1. The fallback receives the final error, so the decision can depend on it:
const program = Effect.retryOrElse(
chargeCard,
Schedule.intersect(Schedule.recurs(3), Schedule.spaced('100 millis')),
(error) => Effect.succeed(`queued for manual review: ${error.reason}`)
);
One honest note: in the sandbox we verified retryOrElse with a real Schedule; the docs' { times: 5 } shorthand is for Effect.retry.
recurs, spaced, exponential, intersect, union), duration strings like '50 millis', and a genuine off-by-one trap: recurs(5) means five retries, six attempts.Park your verdict — the services row is next. The schedules cheatsheet holds every builder and rule from this lesson.
Official docs, ~15 minutes: Retrying (retry, retryOrElse, the until/while options), then Scheduling: Introduction (why schedules are values). After the quiz, not before.
Confused about why recurs counts retries and not attempts, when a defect should be retried (almost never), or how intersect picks its winner? Ask before lesson 4 — Layers build on today's "policy as a value" idea. Stuck on something the docs explain badly? Say so; I'll re-teach it your way.
← Lesson 2 · Next: Services & Layers.