Part 17 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-17tag.
Part 16 ended with a server that has two APIs, a Postgres pool, a mail worker and a collector, and has never run anywhere but my laptop. This part puts it in a container. Most of that is ordinary Docker. The parts that aren’t are where Effect meets the platform. Who receives the SIGTERM that part 14 built a drain around? How long does the platform wait, what exit code does it see, and what does it ask the server every ten seconds?
What I ended up with: esbuild bundles the server into one 5 MB file, and a node:24-slim image runs it with node as PID 1. Two probes answer the platform without filling the logs, and a stop after SIGTERM exits 0. Everything below was measured on Docker Desktop 29.9.2 with node:24-slim (Node 24.22.1) and the repo still on effect 4.0.5.
Do you even need a build step?
Part 1 set the repo up so Node runs the .ts files directly. That works in a container too: copy src, install the production dependencies, run node src/main.ts. So I built that image first, then a bundled one, and compared them on the same Postgres:
node src/main.ts + node_modules |
esbuild bundle | |
|---|---|---|
| what the app adds | 84.8 MB node_modules + 307 kB src | one 5.1 MB main.js |
image size (docker image ls) |
447 MB | 356 MB |
docker run to first /health 200 |
1.12–1.46 s | 0.82–1.07 s |
memory after start (docker stats) |
131–134 MiB | 68–70 MiB |
The memory column surprised me. Part of it is Node’s type stripper. A .ts file that prints its own RSS reports about 60 MB; the same file as .js reports 40. I didn’t chase the rest. The production node_modules also carries packages the server never imports (redis, @redis/* and undici come in through @effect/platform-node), which costs disk but not memory.
Half the memory and a quarter of a second is enough for me to add a build step, as long as it’s one file and one command.
The bundle
// npm run build: the server and every dependency it imports, in one file, dist/main.js.// The Dockerfile copies only that file into the image. No node_modules at runtime.import { build } from "esbuild"
await build({ entryPoints: ["src/main.ts"], outfile: "dist/main.js", bundle: true, platform: "node", target: "node24", format: "esm", // ws (under @effect/platform-node) is CommonJS and calls require("events"). An ES module // has no require, so the bundle would throw "Dynamic require of "events" is not supported". banner: { js: `import { createRequire } from "node:module"; const require = createRequire(import.meta.url);` }, logLevel: "info",})npm run build is node build.ts, so the build script is TypeScript too, and esbuild 0.28.2 is the one new dev dependency, pinned like everything else. No minifying: 5 MB is nothing next to a 350 MB base image, and unminified stack traces keep their function names.
The first bundle built fine and died on start with the Dynamic require error in the comment. The second one started and failed before opening the port:
ERROR (#1): MigrationError: Failed to read migrations directory [cause]: PlatformError: NotFound: FileSystem.readDirectory (/…/out/migrations)Part 9’s migrator used PgMigrator.fromFileSystem with import.meta.dirname. After bundling, that’s the directory main.js sits in, and the migrations aren’t there. Copying src/migrations next to the bundle doesn’t help. Node can import the .ts files, but they import effect, and there’s no node_modules to find it in (ERR_MODULE_NOT_FOUND). The migrations have to be in the bundle, which means static imports:
import { NodeServices } from "@effect/platform-node"import { PgClient, PgMigrator } from "@effect/sql-pg"import { Config, Layer } from "effect"import createUsers from "./migrations/0001_create_users.ts"import createUserEvents from "./migrations/0002_create_user_events.ts"import createApiTokens from "./migrations/0003_create_api_tokens.ts"
const PgLive = PgClient.layerConfig({ url: Config.Redacted("DATABASE_URL") })
// Runs every migration the database hasn't seen, while the layer builds.// Part 17: imported, not read from src/migrations at runtime, so the bundle carries them.// A new migration needs a line here too. The keys keep the file names, so ids and names match.const MigratorLive = PgMigrator.layer({ loader: PgMigrator.fromRecord({ "0001_create_users": createUsers, "0002_create_user_events": createUserEvents, "0003_create_api_tokens": createApiTokens, }),}).pipe(Layer.provide(NodeServices.layer))
// provideMerge: the migrator needs the client, and so does everything built on SqlLive.export const SqlLive = MigratorLive.pipe(Layer.provideMerge(PgLive))fromRecord parses each key with the <id>_<name> pattern fromFileSystem uses on file names. A database migrated by the old loader sees ids 1 to 3 as done and runs nothing. The cost is one import line per new migration.
While I was in there I read what happens when two containers start at once against an empty database. On Postgres the migrator first locks its own table (ACCESS EXCLUSIVE), so the second one waits, then finds nothing to run. I read that in Migrator.ts; I didn’t start two replicas to watch it.
The Dockerfile
# Part 17: build the bundle in one stage, run it in another that has Node and one file.FROM node:24-slim AS buildWORKDIR /appCOPY package.json package-lock.json ./RUN npm ciCOPY build.ts ./COPY src ./srcRUN npm run build
FROM node:24-slimWORKDIR /appENV NODE_ENV=productionCOPY --from=build /app/dist/main.js ./USER nodeEXPOSE 3000# The slim image has no curl, so the health check asks Node to fetch /health.HEALTHCHECK --interval=10s --timeout=2s --start-period=10s \ CMD ["node", "-e", "fetch('http://localhost:3000/health').then((r) => process.exit(r.ok ? 0 : 1), () => process.exit(1))"]# Exec form: node is PID 1 and gets the SIGTERM itself. runMain turns it into a graceful shutdown.CMD ["node", "main.js"]The runtime stage is the base image plus one file, running as the image’s node user instead of root. A .dockerignore keeps node_modules, dist and .env out of the build context, so a local .env with a real DATABASE_URL never ends up in a layer. /rpc from part 16 ships too, on the same port and behind the same token check; it’s in the bundle whether anyone calls it or not.
The line that matters most is the last one.
Who gets the SIGTERM
docker stop sends SIGTERM to PID 1 in the container. NodeRuntime.runMain listens for SIGTERM and SIGINT and interrupts the main fiber. That interruption is what closes the server, drains the welcome queue and flushes telemetry. It only works if PID 1 is node.
I ran the same image three ways, posted one user (with the fake mail service set to never answer), then ran docker stop -t 30:
CMD |
PID 1 | docker stop took |
exit | drain logs |
|---|---|---|---|---|
["node", "main.js"] |
node main.js |
4.67 s | 0 | “draining”, “not sent”, “drained” |
node main.js (shell form) |
/bin/sh -c node main.js |
30.6 s | 137 | none |
["npm", "start"] (unbundled image) |
npm start |
0.96 s | 1 | none, plus npm error signal SIGTERM |
The shell form surprised me. I’d expected Debian’s sh to replace itself with node, since there’s only one command; it didn’t. sh sat at PID 1, and PID 1 ignores a SIGTERM it has no handler for, so node never heard anything. The server kept running, logged welcome mail not sent five seconds in, and was SIGKILLed at the 30 s mark.
npm start is worse because it looks fine. It’s quick and it exits. But npm hands the signal to the sh -c it spawned, which dies of it. npm then reports failure and exits, and the container goes down with node still inside. No “draining” line, no “not sent” line, nothing that tells you a mail was lost.
In exec form the stop took 4.67 s. The mail in flight hit its 5 s deadline and got logged as not sent, then the worker reported the queue drained. That’s the only one of the three where part 14’s code runs at all. If you need a wrapper for some other reason, docker run --init puts tini at PID 1, and tini forwards signals.
Exit 130
Part 3 noted that runMain exits 130 after SIGINT or SIGTERM. That’s its default teardown: a main fiber that ended with nothing but interruptions maps to 130, whichever signal caused it. In a container that shows up as Exited (130) on every normal stop, and anything that alerts on non-zero exits alerts on every deploy.
runMain takes a teardown option, so I changed what a clean interruption means:
// Part 17: SIGTERM is how a container platform asks the server to stop, so a clean stop after it// exits 0 instead of runMain's default 130. Any other failure keeps the default exit code.const teardown: Runtime.Teardown = (exit, onExit) => Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause) ? onExit(0) : Runtime.defaultTeardown(exit, onExit)
// Telemetry is provided last, so it's built first and closed last: the drain's spans and logs still get out.Layer.launch(Server.pipe(Layer.provide(TelemetryLive))).pipe(NodeRuntime.runMain({ teardown }))A migration failure at startup or a port clash still exits 1. A drain that gave up on some mails still exits 0, because giving up is part of the drain. The welcome mails not sent warning names the users.
One thing runMain doesn’t do: a second SIGTERM doesn’t force anything. It interrupts the same fiber again and the drain carries on. SIGKILL from the platform is the only hard stop.
How long the platform waits
Part 14’s shutdown can take a while. server.close gives in-flight requests up to 20 s, then the worker gets 10 s to empty the queue. I posted four users with the mail service hanging, so the queue couldn’t empty, and stopped the container twice:
docker stop 3.37 s exit 137 INFO draining welcome queue { queued: 3 }
docker stop -t 30 10.36 s exit 0 INFO draining welcome queue { queued: 3 } WARN welcome mail not sent Operation timed out after '5s' WARN welcome mail not sent Operation timed out after '5s' WARN welcome mails not sent { users: [ '11' ] } WARN welcome mail cut off { user: '10' }Docker’s reference says the default timeout is 10 seconds for Linux containers. On my Docker Desktop 29.9.2 it was about 3. A container that logs SIGTERM and ignores it got SIGKILLed after 3.3 s with no -t, and after 10.5 s with -t 10. I don’t know where the 3 comes from, and it doesn’t change the advice. The default is shorter than the drain, so the drain gets cut and the one log line that names the unsent users never prints. Set the grace period yourself.
Compose calls it stop_grace_period. Kubernetes calls it terminationGracePeriodSeconds, and its default is 30, less than 20 + 10 plus teardown. I set 40 in both.
Kubernetes adds one more wrinkle. Its docs say the control plane starts taking a terminating pod out of the Service’s EndpointSlices at the same time as the kubelet starts the shutdown. So for a moment the pod gets SIGTERM while traffic still points at it, and part 14 found that once server.close runs, a new connection gets ECONNREFUSED. The usual fix is a short preStop sleep, which delays the SIGTERM. Kubernetes has had a built-in sleep action for it since 1.30 (stable in 1.34), so it doesn’t need a sleep binary in the image:
spec: terminationGracePeriodSeconds: 45 containers: - name: app image: effect-on-the-backend:part-17 lifecycle: preStop: sleep: seconds: 5 livenessProbe: httpGet: { path: /health, port: 3000 } readinessProbe: httpGet: { path: /ready, port: 3000 }The sleep counts against the grace period, so it’s 45 here, not 40. I haven’t run this on a cluster. The Docker and Compose numbers are measured; the Kubernetes part comes from its docs.
Two probes
The platform asks two different questions, and they need two endpoints.
/health is liveness: is the process up and answering? If not, restart it. It must not check Postgres, because a database outage would then restart every container at once and fix nothing. /ready is readiness: can this instance do its job right now? If not, stop sending it traffic, but leave it running.
import { Effect, Layer } from "effect"import { HttpMiddleware, HttpRouter, HttpServerResponse } from "effect/http"import { SqlClient } from "effect/sql"
// Part 17: what a container platform asks the server every few seconds.
// The process is up and answering. Nothing else: a restart wouldn't fix a database outage.const Health = HttpRouter.add("GET", "/health", HttpServerResponse.text("ok"))
// The server can do its job: Postgres answers within a second. A load balancer stops sending// traffic while this is a 503, and starts again once it isn't.const Ready = HttpRouter.add( "GET", "/ready", Effect.gen(function* () { const sql = yield* SqlClient.SqlClient yield* sql`SELECT 1`.pipe(Effect.timeout("1 second")) return HttpServerResponse.text("ready") }).pipe( // Without this, every probe's SELECT 1 is a "postgres" span with no parent. Effect.withTracerEnabled(false), Effect.catch((error) => Effect.as(Effect.logWarning("not ready", error), HttpServerResponse.text("not ready", { status: 503 })), ), ),)
// Both routes, without the "Sent HTTP response" log line on every probe.export const Probes = Layer.mergeAll(Health, Ready).pipe(Layer.provide(HttpRouter.disableLogger))
// No server span for a probe either. This one has to be provided around HttpRouter.serve, not the routes.export const ProbesUntraced = HttpMiddleware.layerTracerDisabledForUrls(["/health", "/ready"])Ready can ask for SqlClient because part 9’s provideMerge already passes it to every route inside HttpRouter.serve. In main.ts, Probes replaces the old Health in the route list and ProbesUntraced joins HttpLive: HttpRouter.serve(Routes).pipe(Layer.provide([HttpLive, ProbesUntraced])).
Each of the three quiet-making lines is there because I watched the noise without it, using a small OTLP sink that printed every span it got:
- Without
disableLogger, each probe writes aSent HTTP responseline. At one probe every ten seconds per container, that’s most of the log. layerTracerDisabledForUrlsdoes nothing when provided to the probe routes. The server span opens in the middleware around the router, so the layer has to go aroundHttpRouter.serve. Provided there,GET /healthandGET /readystopped appearing.- Then every
/readystill exported a root span calledpostgres: theSELECT 1, with its parent gone.Effect.withTracerEnabled(false)on the handler removed it.
Then I broke Postgres under it:
Postgres up /health 200 0.004 s /ready 200 0.003 sdocker stop db /health 200 0.001 s /ready 503 0.003 s WARN not ready … ECONNREFUSEDdocker start db /health 200 0.002 s /ready 200 0.019 sdocker pause db /health 200 0.001 s /ready 503 6.02 sA stopped database gives a fast 503. A hung one doesn’t. The Effect.timeout("1 second") fires on time. But a timeout interrupts the query and then waits for the interruption to finish. @effect/sql-pg handles an interrupted query by sending Postgres a cancel request, then waits up to 5 seconds for the connection to drain (abortDrainTimeoutMillis in PgConnection.ts). A paused Postgres answers neither, so the 503 takes 1 + 5 seconds. Kubernetes’ probe gives up after 1 second by default and counts the timeout as a failure, so the pod still goes unready. Your load balancer’s probe might wait longer than that.
The Docker HEALTHCHECK uses /health, not /ready. Plain Docker only marks the container unhealthy, but Swarm replaces unhealthy tasks, which makes it a liveness check.
Compose
# Part 17: the server as it ships, built from the Dockerfile. Only starts with --profile app, # so without it `npm start` still has port 3000 to itself. app: profiles: [app] build: . ports: - "3000:3000" environment: DATABASE_URL: postgres://app:change-me@db:5432/app MAIL_URL: http://host.docker.internal:3001 OTEL_EXPORTER_OTLP_ENDPOINT: http://otel:4318 OTEL_TRACES_EXPORTER: otlp OTEL_LOGS_EXPORTER: otlp OTEL_METRICS_EXPORTER: otlp extra_hosts: - "host.docker.internal:host-gateway" depends_on: db: condition: service_healthy # Up to 20 s for in-flight requests, then 10 s for the welcome queue, then teardown. stop_grace_period: 40sThe OTEL_* lines are part 15’s, all four of them: in 4.0.5 the exporters default to none, so the endpoint alone exports nothing. MAIL_URL points at npm run mail on the host; extra_hosts makes host.docker.internal resolve on Linux too, where Docker Desktop’s built-in name doesn’t exist.
docker compose --profile app up -d --build --wait took 34 s from cold, mostly the build and the collector. It returned once all three services reported healthy, the app through the Dockerfile’s HEALTHCHECK. docker compose stop app took 1.2 s and left Exited (0). The last two log lines were the drain’s.
Gotchas
import.meta.dirnamemoves when you bundle. Anything that reads files relative to its own module (migrations here) reads them next tomain.jsinstead.docker runwithsh -cis the shell form. So is a composecommand:string. Both putshat PID 1, likeCMD node main.js.npm ci --omit=devisn’t small here. 84.8 MB, because@effect/platform-nodebringsredisandundiciwith it.- Exit 137 means SIGKILL, and it hides the evidence. The warning that lists unsent mails comes last, so a short grace period cuts it.
Run it
git clone https://github.com/devtrillo/effect-on-the-backendcd effect-on-the-backendgit checkout part-17npm installnpm testnpm run mailThen, in a second terminal, docker compose --profile app up -d --build --wait, and curl localhost:3000/ready. npm test is unchanged at 42 passed plus part 14’s one expected fail; the probes and the teardown are checked by the runs above, not by tests. The repo stays on effect 4.0.5 even though 4.0.6 is out.
The server runs somewhere other than my laptop now, and stops cleanly when asked. That leaves the question the series started with: was Effect worth it, against the Hono or Express server I’d have written without it?
Next in the series: Effect vs Hono and Express, the verdict.
- Part 18 — Effect vs Hono and Express: the verdict: The same server rebuilt in Hono and Express 5: line counts, what the compiler caught, and the Postgres restart that only the Effect version survived.

