Timeouts, retries and Schedule

By Esteban Trillo6 min readupdated Effect on the BackendEffectTypeScript

Each attempt gets 2 seconds and the retries back off, but the whole send runs inside one 5 second track. When the flag comes round, the mail gives up and the user is still created.
Each attempt gets 2 seconds and the retries back off, but the whole send runs inside one 5 second track. When the flag comes round, the mail gives up and the user is still created.

Part 13 of a series that builds one backend server on Node with Effect 4. The code is in devtrillo/effect-on-the-backend, and this part is the part-13 tag.

Part 12 ended on a promise: nothing in the server sleeps yet. Now something does. POST /users sends a welcome mail through an HTTP API, and that API is the first thing in this series I don’t control. It can be slow, it can say 503, and it can take the request and never answer.

With plain fetch you’d write this yourself: an AbortSignal.timeout, a loop, a sleep that doubles. Then a status check you’d get slightly wrong the first time. Effect’s HttpClient has most of that built in, and Schedule covers the rest.

A mail service that fails on purpose

There’s no real mail provider in the repo. npm run mail starts a fake one in plain node:http, and MAIL_FAILS decides how it misbehaves for the first attempts of each mail. The default, 503,hang, answers 503, then accepts the second attempt and never replies, then sends on the third.

The client

Mailer is a service like Users, and it asks for an HttpClient instead of a SqlClient. Everything about failure lives on the client, set up once:

src/Mailer.ts (excerpt)
// Read bottom up: retry the attempt, time each attempt out, fail on a non-2xx status.
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.mapRequest(HttpClientRequest.prependUrl(url)),
HttpClient.filterStatusOk,
// Each attempt gets 2 seconds. A timeout counts as transient, so it's retried like a 503.
HttpClient.transformResponse(Effect.timeout("2 seconds")),
// Timeouts, network errors, 408, 429 and 5xx (not 501), with backoff: ~250 ms, ~500 ms, ~1 s.
HttpClient.retryTransient({
schedule: Schedule.exponential("250 millis").pipe(Schedule.jittered),
times: 3,
}),
)

Each step wraps the one above it. The order is the policy. filterStatusOk turns a 503 into an error, Effect.timeout limits one attempt, and retryTransient runs both again. times: 3 means three retries, four attempts in all.

retryTransient decides what’s worth another try. In 4.0.5 that’s a TimeoutError, a transport error (connection refused, socket reset), and the statuses 408, 429, 500, 502, 503 and 504. If the response has a Retry-After header, that becomes the minimum wait. Everything else fails on the first attempt. A 422 for a bad address, a 401 for a bad API key, a 501 from a server that will never do it: retrying those repeats the same answer, slower.

Schedule.exponential("250 millis") waits 250 ms, then 500, then 1,000. Schedule.jittered scales each wait by a random factor between 0.8 and 1.2, so a hundred requests that failed together don’t all come back at the same millisecond.

The deadline

The client bounds each attempt. Nothing bounds the whole send yet. Four attempts of two seconds, plus the waits, is close to ten seconds of POST /users hanging. So welcome gets a deadline of its own:

src/Mailer.ts (excerpt)
welcome: Effect.fn("Mailer.welcome")(
function* (user: { readonly id: string; readonly name: string; readonly email: string }) {
yield* Effect.annotateCurrentSpan("user.id", user.id)
yield* HttpClientRequest.post("/send").pipe(
// Same key on every attempt, and on any later resend: the mail service sends it once.
HttpClientRequest.setHeader("idempotency-key", `welcome-${user.id}`),
HttpClientRequest.bodyJsonUnsafe({ to: user.email, subject: "Welcome", text: `Hi ${user.name}!` }),
client.execute,
)
},
// The whole send, retries and waits included, gets 5 seconds.
Effect.timeout("5 seconds"),
Effect.mapError((cause) => new MailError({ cause })),
),

Part 2 said timeouts and retries go in Effect.fn’s extra arguments. The deadline does, so it runs inside the Mailer.welcome span. The retry doesn’t, and that’s on purpose: on the client it knows about status codes and Retry-After, and it sends the same request object again, header included. It still runs inside the span, because the body calls the client.

The handler calls welcome after users.create returns, outside part 10’s transaction, so no Postgres connection waits on the mail service. By then the user exists, so a mail that never arrives is a logged warning, and the response is still a 201. Failing the request would only make the client POST again and create a second Grace.

What curl sees

Same curl as part 11, against npm start with Postgres and the fake running. Each line is a different MAIL_FAILS:

POST /users, one MAIL_FAILS at a time
503,hang 201 in 2.8 s 503, no answer (client gave up), 202 sent
hang,hang,hang 201 in 5.1 s three attempts, each given up; WARN Operation timed out after '5s'
422 201 in 0.04 s one attempt; WARN non 2xx status code (422 POST .../send)
429 201 in 1.1 s 429 with Retry-After: 1, then 202
mail not up 201 in 1.9 s connection refused, retried; WARN Transport error (POST .../send)

“Client gave up” is the fake noticing the socket close. The timeout interrupts the fiber, which aborts the fetch, so nothing is left hanging on either side. In the hang row the third attempt starts around 4.75 s and the deadline cuts it off at 5. In the 429 row the backoff wanted 250 ms, and the server asked for a second, so it got a second.

You move HttpClient.transformResponse(Effect.timeout('2 seconds')) below retryTransient in the pipe. The mail service never answers. How many attempts does it get?

The POST that already worked

retryTransient doesn’t look at the method. A timed-out POST gets retried like a GET, and a timeout doesn’t tell you whether the server did the work. RFC 9110 says a client shouldn’t automatically retry a non-idempotent request unless it knows it’s safe. System Design part 2 covers why, and retry budgets too, so I won’t repeat it.

The fake’s slow mode is that case. It sends the mail on the first attempt and answers three seconds later, after the client has given up:

npm run mail, MAIL_FAILS=slow
POST /send key=welcome-12 attempt 1: sent, answering in 3 s
POST /send key=welcome-12 attempt 2: 200, already sent, not sending again

The idempotency-key header is what makes the retry safe. It’s built from the user id, not generated per attempt. A retry here carries the same key, and so would a resend from somewhere else later. The mail service drops the duplicate. Without it, attempt 2 is just a second welcome mail. Stripe calls the header Idempotency-Key; check what your mail provider supports before you rely on it.

TestClock does the waiting

Every number above came from a real clock, and the hang run took five real seconds. The tests use part 12’s TestClock and take none. A fake HttpClient answers from a script, a status per attempt or "hang", and records the clock and the key on each attempt:

test/Mailer.test.ts (excerpt)
it.effect("two 503s, then 202: sent on the third attempt, with backoff between", () =>
Effect.gen(function* () {
const mail = fakeMail([503, 503, 202])
const exit = yield* send.pipe(Effect.provide(mail.layer))
assert.isTrue(Exit.isSuccess(exit))
const [first, second, third] = mail.attempts.map((attempt) => attempt.at)
assert.strictEqual(mail.attempts.length, 3)
assert.strictEqual(first, 0)
// 250 ms, then 500 ms, each jittered by up to 20% either way.
assert.isTrue(second! >= 200 && second! <= 300, `second attempt at ${second}`)
assert.isTrue(third! - second! >= 400 && third! - second! <= 600, `third attempt ${third! - second!} ms later`)
}),
)

send forks welcome, moves the clock a minute with TestClock.adjust, and awaits the fiber. Five more tests check the same key on every attempt, one attempt for a 422, and four for an endless 503 or a refused connection. The last one hangs: still running at 4,999 ms, a TimeoutError at 5,000, three attempts.

I checked that they can fail, too. Delete the per-attempt timeout and the hang test breaks; delete times: 3 and the endless-503 test does.

The part 12 tests get a Mailer that succeeds at once. npm test is 26 passed plus part 12’s one expected fail, in under two seconds of wall time.

Gotchas

  • retryTransient({}) never stops. With no schedule it uses Schedule.forever, which doesn’t wait, and with no times there’s no limit. Against a fake that answers 503 a thousand times, it sent 1,001 requests with the clock still at 0. Pass both.
  • Retries multiply. Wrap welcome in Effect.retry({ times: 3 }) and a dead mail service gets 16 requests. That’s four tries of a client that already tries four times. Retry at one layer.
  • Retry-After can be longer than your patience. A 429 with Retry-After: 30 makes retryTransient wait 30 seconds. The 5 second deadline is what stops that: one attempt, then MailError.
  • jittered isn’t full jitter. Effect’s version keeps each wait within 20% of the schedule’s. The “full jitter” from the AWS write-ups picks anywhere from zero to the full wait. If you want that, Schedule.modifyDelay can do it.
  • The user waits for the mail. Up to five seconds on a bad day, on every POST /users. That’s the wrong place for it.
HttpClient.retryTransient({ times: 3 }) with no schedule, against an upstream that always answers 501. How many requests does it send?

Run it

Terminal window
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-13
npm install
npm test
docker compose up -d --wait
cp .env.example .env
npm run mail

Then npm start in a second terminal and part 11’s curl in a third. MAIL_URL defaults to http://localhost:3001, where npm run mail listens. Try MAIL_FAILS=slow npm run mail for the duplicate. The repo stays on effect 4.0.5; effect/http is still @stability unstable there, retryTransient included.

The retries hold, and the mail goes out on the third try. But a user signing up waits for all of it, and if the server stops in the middle, nobody sends that mail at all. It belongs in the background.

Next in the series: background jobs and graceful shutdown.

  • Part 14 — Background jobs and graceful shutdown: The welcome mail moves into a Queue with one forkScoped worker, POST /users answers in about 10 ms, and SIGTERM drains the queue for up to 10 seconds after the last request.
Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.