Part 14 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-14tag.
Part 13 left POST /users waiting for a welcome mail: 2.8 seconds on the fake’s default script, five on a bad day. The user already exists by then, and the response doesn’t depend on the mail at all. So the mail should go out after the response. That’s easy to write, and it’s also easy to lose the mail on the way, either when the request ends or when the server stops.
Three ways to fork, two of them wrong
The smallest change is to fork the send and return. Effect has more than one fork, and which one you pick decides who the new fiber belongs to.
Effect.forkChild attaches the new fiber to the one that forked it. Every request runs in a fiber of its own, and that fiber ends when the response is sent, so the child is interrupted right there. I tried it on the server: POST /users answered 201, and the fake mail service never logged a request at all.
Effect.forkDetach belongs to nobody. The mail goes out, and as long as the process stays up for the next few seconds, everything looks fine. Send SIGTERM half a second after the POST and the fake logs the 503, then the second attempt, then “client gave up” as the process exits under it. Nothing in the server’s log says a mail was lost.
Effect.forkScoped attaches the fiber to a Scope, and in a layer that’s the layer’s own scope. The fiber lives as long as the layer, and the layer closes when the server shuts down. That’s the one to use, with a queue in front of it so the handler doesn’t fork anything.
A queue and one worker
WelcomeJobs is a new service. It owns a bounded queue and the fiber that empties it:
const mailer = yield* Mailer// Cause.Done in the error type is what lets Queue.end close it: take fails with Done once it's empty.const queue = yield* Queue.bounded<Welcome, Cause.Done>(100)
const send = Effect.fn("WelcomeJobs.send")( function* (job: Welcome) { yield* mailer.welcome(job).pipe( // Only happens at shutdown, when the drain below runs out of time mid-send. Effect.onInterrupt(() => Effect.logWarning("welcome mail cut off", { user: job.id })), ) }, Effect.catchTag("MailError", (error) => Effect.logWarning("welcome mail not sent", error.message)),)
// One worker: take a job, send it, take the next. It stops when take fails with Done.const worker = yield* Queue.take(queue).pipe( Effect.flatMap(send), Effect.forever, Effect.catchIf(Cause.isDone, () => Effect.log("welcome queue drained")), Effect.forkScoped,)mailer.welcome is part 13’s, unchanged: per-attempt timeout, retries and a 5 second deadline. Its MailError becomes a warning inside the WelcomeJobs.send span, so one bad address never stops the loop. The handler loses its mail code and gains one line:
.handle("create", ({ payload }) => users.create(payload).pipe( // Queue the welcome mail and answer. The worker in WelcomeJobs sends it after the response. Effect.tap((user) => jobs.enqueue({ id: user.id, name: user.name, email: payload.email })), ),)enqueue is Queue.offer in an Effect.fn. With the fake on its default 503,hang, three POSTs in a row took 24 ms, 14 ms and 9 ms. In part 13 each of them took 2.8 seconds.
Running the job outside the request also settles a promise from part 10: a job shouldn’t fork out of a transaction. This one starts after users.create has committed and never touches its connection.
Draining on SIGTERM
forkScoped alone isn’t enough. When the layer’s scope closes, it interrupts the worker, and anything still in the queue is gone. So the layer adds a finalizer of its own:
// Added after forkScoped, so it runs before the fork's own finalizer interrupts the worker.// Stop taking new jobs, give the worker 10 seconds to finish the queued ones, then log what's left.yield* Effect.addFinalizer(() => Effect.gen(function* () { yield* Effect.log("draining welcome queue", { queued: yield* Queue.size(queue) }) yield* Queue.end(queue) yield* Fiber.await(worker).pipe( Effect.timeout("10 seconds"), Effect.catchTag("TimeoutError", () => Effect.flatMap(Queue.clear(queue), (left) => Effect.logWarning("welcome mails not sent", { users: left.map((job) => job.id) }), ), ), ) }),)Queue.end stops new offers and lets take keep returning what’s already buffered; once the queue is empty, take fails with Done and the worker’s loop exits. A scope runs its finalizers in reverse order, which is why the comment matters: forkScoped registered “interrupt the worker” first, so this drain, registered second, runs before it.
Who closes the scope? NodeRuntime.runMain listens for SIGINT and SIGTERM and interrupts the main fiber, which is running Layer.launch.
Then the layers come down in reverse order of how they were built. The HTTP server was built last, so it goes first: it stops accepting connections and waits up to 20 seconds (gracefulShutdownTimeout’s default) for the requests already in flight. WelcomeJobs was built before it, because the handlers need it, so the drain starts only after the last request has answered and queued its mail. The process still exits 130, like it did in part 3.
What the logs show
Three runs against npm start, Postgres and npm run mail, each ending with kill -TERM:
503,hang 3 POSTs draining { queued: 2 }; all 3 sent; "drained" 6.8 s after "draining"hang,hang,hang 4 POSTs draining { queued: 3 }; 2x WARN timed out after '5s'; at exactly 10 s: WARN not sent { users: ['13'] }, WARN cut off { user: '12' }(none) 1 POST body half sent at SIGTERM: new connection ECONNREFUSED 200 ms later, slow POST finished 1.5 s later → 201; drain ran after it; mail sentIn the 503,hang run the worker already had the first job when the signal arrived, which is why the queue held two and not three. The hang run is the deadline doing its job: two mails used their full five seconds each, the third was mid-send when the ten seconds ran out, and the fourth never started. Both lose their mail.
Both ids are in the log, which is the minimum you need to send them again by hand. Part 13’s idempotency key is built from the user id, so a resend can’t double up a mail that did go out.
The third run is the ordering. The request that was half-uploaded when SIGTERM arrived still got its 201, and its mail went out afterwards, because the server’s finalizer waited for it before the queue’s finalizer ran.
Thirty seconds, all of it spoken for
Kubernetes sends SIGTERM, waits for the pod’s grace period, then sends SIGKILL. The default grace period is 30 seconds. The HTTP server can use up to 20 of them on in-flight requests and the queue up to 10, so on the worst day the two together spend the entire 30 and leave nothing for closing the Postgres pool.
The rest of the teardown took between one and three seconds in my runs, so the worst day already goes over. If you run this behind Kubernetes, raise terminationGracePeriodSeconds or lower one of the two timeouts; the numbers here are the defaults, not a recommendation.
A SIGKILL, an OOM kill or a crash skips every finalizer. The queue lives in memory, so whatever was in it is gone, and nothing logs the ids. If that’s not acceptable, the job list has to live in Postgres: part 10’s user_events table already gets a created row in the same transaction as the user, and a worker that polls it for users with no welcome mail survives any kind of restart. That’s an outbox, and it’s more machinery than one welcome mail needs today.
Tests
The tests don’t start a server. Effect.provide(jobs) builds the layer for one effect and closes its scope when the effect is done, which is the same thing SIGTERM does to main.ts. The fake Mailer sleeps on TestClock and records when each mail finished:
it.effect("shutdown sends every queued mail before it returns", () => Effect.gen(function* () { const mail = fakeMailer(1000) yield* enqueueThenShutDown(5, mail.jobs) // One worker, one at a time: done at 1, 2, 3, 4 and 5 seconds. assert.deepStrictEqual( mail.sent.map((m) => m.at), [1000, 2000, 3000, 4000, 5000], ) }),)A second test gives each mail four seconds and expects exactly two sent before the ten second cut. I checked both can fail: delete the drain finalizer and both break, change the timeout to "10 hours" and the second one does. npm test is now 34 passed plus part 12’s expected fail.
Gotchas
Queue.shutdownisn’tQueue.end.shutdownthrows away everything buffered. With three queued and the worker holding the first, it sent one.- Without
Cause.Donein the type,Queue.endwon’t compile.Queue.bounded<Welcome>(100)gives you a queue that can only be shut down or interrupted. TheDonein the error channel is what makes “no more, but finish what’s there” possible. - A full queue slows the request down. One job in the worker’s hands and 100 waiting: the next
offersuspends until the worker takes one, so the 102ndPOST /userswaits for a mail after all.Queue.droppingwould answer at once and lose the mail instead. I’d rather the request wait. - An
offerafterendreturnsfalse. Nothing fails, and the job is dropped. The server’s shutdown order means no handler is left to offer once the drain starts, but code that enqueues from somewhere other than a handler doesn’t get that for free. - One worker means one mail at a time. A hundred queued mails on a mail service that hangs is 500 seconds of work. More workers means more
forkScopedfibers and a drain that awaits all of them. I’d want a reason first, since the mail service’s rate limit is the real ceiling.
Run it
git clone https://github.com/devtrillo/effect-on-the-backendcd effect-on-the-backendgit checkout part-14npm installnpm testdocker compose up -d --waitcp .env.example .envnpm run mailThen npm start in a second terminal, part 11’s curl a few times in a third, and Ctrl-C the server: it logs the drain before it exits. MAIL_FAILS=hang,hang,hang npm run mail with four POSTs shows the ten second cut. The repo stays on effect 4.0.5; 4.0.6 is out, and nothing in this part needed it.
Every request already gets a span, and every mail runs inside WelcomeJobs.send and Mailer.welcome, named since part 2 so a collector could find them. No collector has seen one yet.
Next in the series: logs, spans and metrics with OpenTelemetry.
- Part 15 — Logs, spans and metrics with OpenTelemetry: Effect 4's own OTLP exporter sends the server's logs, spans and one metric to a collector, and the welcome mail joins the trace of the request that queued it.

