rhythmjs

Search documentation

Search guides, the tutorial and every package.

On this page

See every request#

Three middleware from @rhythmjs/observability cover the request path: log() writes one line per request (method, path, status, duration — never headers or bodies), timing() adds a Server-Timing header, and requestId() puts an id on the context and response. Put them first on the app, outermost first, so log measures and reports everything:

TypeScript
import { log } from "@rhythmjs/observability/log";
import { requestId } from "@rhythmjs/observability/request-id";
import { timing } from "@rhythmjs/observability/timing";

export const appModule = new Rhythm<{}, RhythmHttpContext>({ name: "app" })
  /* ...startup registrations... */
  .use(log())
  .use(timing())
  .use(requestId())       // ctx.requestId: string, for everything mounted after it
  .use(secureHeaders())
  /* ...the rest of the edge stack and the routers... */

A router that wants the id declares RequestIdContext (from @rhythmjs/observability/request-id) in its context type, and mount() checks that the app derives it before the router.

Health checks#

The health service separates liveness (the process is up) from readiness (its dependencies answer). Indicators are small objects with a check(); results are cached briefly so load balancers cannot hammer your database through the endpoint. The service is created in its own file because the routes and the shutdown hook both need the same instance:

TypeScript
// src/health.ts
import { createHealthService } from "@rhythmjs/observability/health";
import { sql } from "drizzle-orm";
import { database } from "./database/database.module";

export const healthService = createHealthService({
  indicators: [
    {
      name: "postgres",
      critical: true,
      timeout: 2_000,
      check: async () => {
        await database.execute(sql`select 1`);
        return { status: "up" };
      },
    },
  ],
});
TypeScript
// src/app.module.ts
import { healthRoutes } from "@rhythmjs/observability/health";

appModule.use(mount(healthRoutes(healthService))); // GET /health/live, GET /health/ready; mount it before the 404 guard

healthRoutes is a router with full paths (/health/live, /health/ready); move them with healthRoutes(service, { path: "/internal" }). If you only want the service on the context — for a handler of your own — register(include(healthModule.forRoot({ indicators }), ({ healthService }) => ({ healthService }))) does the registration for you, but the routes and the shutdown hook need the instance itself, which is why this app builds it directly.

Graceful shutdown#

Production main.ts ties it together: an error boundary around the handler, and signal-driven shutdown that flips readiness, drains, then runs one close hook that stops the server and the app — which runs every cleanup you registered, so the pool closes last:

TypeScript
// src/main.ts
import { gracefulShutdown } from "@rhythmjs/observability/health";
import { errorToResponse, toFetchHandler } from "@rhythmjs/router/fetch";
import { appModule } from "./app.module";
import { appConfig } from "./config/app.config";
import { healthService } from "./health";

const { port } = await appConfig();
const handler = toFetchHandler(appModule);

const server = Bun.serve({
  port,
  async fetch(request, server) {
    Object.assign(request, { ip: server.requestIP(request)?.address }); // for rateLimit
    try {
      return await handler(request, server);
    } catch (error) {
      return errorToResponse(error); // 5xx bodies are generic; details stay in server logs
    }
  },
});

gracefulShutdown({
  healthService,          // readiness flips down first
  drainMs: 5_000,         // let the load balancer notice
  timeoutMs: 15_000,      // watchdog: exit(1) if close hangs
  close: async () => {
    await server.stop();    // finish in-flight requests
    await appModule.stop(); // run the app's cleanups: closes the pool
  },
});

console.log(`listening on ${server.url}`);

With that, deploys are boring: the balancer sees /health/ready go down, traffic drains, in-flight requests finish, the pool closes last, because the app's cleanups say so. Which leaves exactly one thing to prove — that all of it works.