Lesson 193 of 296
Configuration, signals and graceful shutdown
What you will learn
- Configuration with environment variables
- Validating configuration at start-up
- What signals are (SIGTERM, SIGINT)
- Graceful shutdown step by step
- Health checks: liveness and readiness
- Handling uncaught errors
On this page
Configuration from the environment
The same code runs in development, testing and production with different settings: database URL, API keys, port. The standard approach (the Twelve-Factor App principles) is to read config from environment variables:
PORT=3000
DATABASE_URL=postgres://app:secret@localhost:5432/app
JWT_SECRET=a-long-random-value
NODE_ENV=productionIn code: process.env.PORT. Locally, values often come from a .env file (Node.js can load it with node --env-file=.env server.js). Never commit .env files with secrets to Git; commit a .env.example with placeholder values instead. In production, secrets come from the platform or a secrets manager (Lesson 251).
Validate config at start-up
Environment variables are always strings or undefined. A missing or wrong value should stop the app immediately at start-up with a clear message, not cause a confusing error at 3 a.m. Use Zod (Lesson 114):
import { z } from "zod";
const EnvSchema = z.object({
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
DATABASE_URL: z.url(),
JWT_SECRET: z.string().min(32, "JWT_SECRET must be at least 32 characters"),
LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info")
});
export type Env = z.infer<typeof EnvSchema>;
export function loadEnv(source: Record<string, string | undefined>): Env {
const result = EnvSchema.safeParse(source);
if (!result.success) {
const problems = result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
throw new Error(`Invalid environment configuration: ${problems}`);
}
return result.data;
}Call const env = loadEnv(process.env) once, and import env everywhere else. z.coerce.number() converts the string "3000" to a number.
Signals
A signal is a message the operating system sends to a process.
| Signal | Sent when |
|---|---|
| SIGINT | You press Ctrl+C in the terminal |
| SIGTERM | A platform asks the process to stop: Docker docker stop, Kubernetes during a deployment, systemd, Heroku and others |
| SIGKILL | Force kill; cannot be caught. Docker and Kubernetes send it if the process has not stopped after a grace period (often 10 to 30 seconds) |
Graceful shutdown
During every deployment, old instances receive SIGTERM. If the process just dies, in-flight requests fail, database transactions are cut off and jobs are lost. Graceful shutdown means:
- Stop accepting new work: mark the service as not ready (so the load balancer stops sending traffic) and stop the HTTP server listening.
- Finish in-flight work: let current requests complete.
- Close resources: database pools, Redis, queue consumers.
- Exit, with a timeout that forces exit if something hangs.
import type { Server } from "node:http";
type Closable = { name: string; close: () => Promise<void> };
export function setupGracefulShutdown(server: Server, resources: Closable[], timeoutMs = 10_000) {
let shuttingDown = false;
async function shutdown(signal: string): Promise<void> {
if (shuttingDown) return;
shuttingDown = true;
console.log(`${signal} received: shutting down`);
const forceExit = setTimeout(() => {
console.error("Shutdown timed out; forcing exit");
process.exit(1);
}, timeoutMs);
forceExit.unref();
await new Promise<void>((resolve) => {
server.close(() => resolve());
server.closeIdleConnections();
});
for (const resource of resources) {
try {
await resource.close();
} catch (err) {
console.error(`Failed to close ${resource.name}`, err);
}
}
process.exitCode = 0;
}
process.once("SIGTERM", () => void shutdown("SIGTERM"));
process.once("SIGINT", () => void shutdown("SIGINT"));
return { isShuttingDown: () => shuttingDown, shutdown };
}server.close()stops accepting new connections and calls back when existing ones finish.closeIdleConnections()closes keep-alive connections that are idle, which otherwise keep the server open.forceExit.unref()means this timer alone will not keep the process alive.- Setting
process.exitCodeand letting the process end naturally is cleaner than callingprocess.exit(0)immediately, which can cut off logs.
Health checks
Platforms ask the service whether it is healthy, usually by HTTP:
| Check | Question | Endpoint example | If it fails |
|---|---|---|---|
| Liveness | Is the process alive and not stuck? | GET /healthz | The platform restarts the container |
| Readiness | Can it handle traffic now? (database connected, not shutting down) | GET /readyz | The load balancer stops sending traffic, without restarting |
During shutdown, readiness should return 503 immediately while liveness stays OK.
Uncaught errors
process.on("unhandledRejection", (reason) => { log it; then exit });
process.on("uncaughtException", (err) => { log it; then exit });After an uncaught exception the process may be in an unknown state. Log, then exit, and let the platform restart a fresh instance. Do not try to keep running.
How to say it in an interview
"I read configuration from environment variables, never commit secrets, and validate everything at start-up with a Zod schema so a bad config fails fast with a clear message. Platforms send SIGTERM on deployments, so I implement graceful shutdown: fail readiness, stop accepting connections with server.close, let in-flight requests finish, close database and queue connections, and force exit after a timeout before the platform's SIGKILL. I expose separate liveness and readiness checks, and on uncaught exceptions I log and exit so the process is restarted cleanly."
Key words
| Word | Meaning |
|---|---|
| Environment variable | A setting given to a process by its environment |
| Twelve-Factor App | Principles for building deployable services, including config in the environment |
| Signal | A message from the OS to a process (SIGTERM, SIGINT, SIGKILL) |
| Graceful shutdown | Stopping without dropping in-flight work |
| Liveness check | "Is the process alive?" Failure means restart |
| Readiness check | "Can it take traffic now?" Failure means no traffic |
| Keep-alive | Reusing one TCP connection for several HTTP requests |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.