Skip to content

Persistent Server ​

Introduction ​

@plinthjs/cluster runs your application as a long-lived, high-throughput HTTP server. The application is booted once and the same warm instance handles every request. Between requests the worker resets the per-request state that lives in the container, so one request can never see another request's data. When one process is not enough, the same server forks a pool of worker processes with node:cluster.

bash
pnpm add @plinthjs/cluster

The package depends only on Node built-ins (node:http, node:cluster), @plinthjs/core and @plinthjs/http.

The two classes you use are named ClusterWorker and ClusterServer:

  • ClusterWorker wraps an Application and an HttpKernel, boots them once, runs each request through the kernel, flushes per-request state, and manages lifecycle hooks and periodic ticks. It has no sockets, so you can test it in-process.
  • ClusterServer serves a worker over node:http and optionally forks several worker processes.

The server created by serve() in a generated application's src/server.ts also boots the application once and keeps it. The worker adds the guaranteed per-request flush, lifecycle hooks, ticks, and the multi-process mode. Reach for it when you run in production and need those.

Serving an application ​

Build the application and kernel exactly as you would for a normal entry point, then hand them to a worker and a server.

ts
import { Application } from '@plinthjs/core'
import { HttpKernel, Response, Router } from '@plinthjs/http'
import { ClusterServer, ClusterWorker } from '@plinthjs/cluster'

const app = new Application({ runningInConsole: false })

const router = new Router()
router.get('/ping', () => Response.json({ pong: true }))

const kernel = new HttpKernel(router, { container: app })

const worker = new ClusterWorker({ app, kernel })
const server = new ClusterServer(worker)

await server.start({ port: 8000, host: '0.0.0.0' })

start boots the worker before it opens the socket, so the first request is already served warm, and then starts the worker's tick timers. It resolves with the listening node:http Server (in cluster mode, the primary resolves with a server-shaped handle whose close() stops re-forking and terminates the children). Options are port (default 8000; 0 picks a free port), host, workers, ticks, restart and onFatal (see Cluster mode).

To shut down, call stop(). It closes the listening socket, stops the ticks, calls the application's terminating callbacks and runs your terminate hooks. It is safe to call even if the server never started.

ts
await server.stop()

If you want to control listen() yourself, await server.build() returns an unbound node:http server wrapping the booted worker. getServer() returns the live server once started, and getWorker() returns the worker.

Using your application's bootstrap ​

In a generated application the entry point calls createApplication() from src/bootstrap/app.ts, registers the routes from src/routes/web.ts on a Router, and builds an HttpKernel with the app as its container. You do the same here and replace serve(kernel, port) with a worker and a server:

ts
import { env } from '@plinthjs/core'
import { HttpKernel, Router } from '@plinthjs/http'
import { ClusterServer, ClusterWorker } from '@plinthjs/cluster'

import { createApplication } from '../src/bootstrap/app.js'
import { registerWebRoutes } from '../src/routes/web.js'

const worker = new ClusterWorker({
  factory: async () => {
    const app = await createApplication()
    const router = new Router()
    registerWebRoutes(router)
    return { app, kernel: new HttpKernel(router, { container: app }) }
  },
})

await new ClusterServer(worker).start({ port: Number(env('PORT', '3000')) })

Keep the generated entry's other wiring (security headers, graceful shutdown, closing the database) when you adapt it. The factory form is what you want for cluster mode, described below.

How booting works ​

A worker needs a context: an Application and the HttpKernel that runs the request pipeline. You supply it in one of two ways:

  • new ClusterWorker({ app, kernel }) when you already built both.
  • new ClusterWorker({ factory }) where factory is a function (sync or async) that returns { app, kernel }. It is called once, on the first boot.

await worker.boot() builds the context, calls app.boot() (which is idempotent, so a factory may return an unbooted app or an already booted one), then fires the onBoot hooks. Calling it again does nothing and returns the same context. worker.isBooted() tells you whether it has happened. You rarely call boot() yourself, because handle() and server.start() call it for you.

Per-request state ​

Because the application lives for the whole process, anything left in the container after one request would be visible to the next. After every request, whether it succeeded or threw, the worker calls the application's forgetScopedInstances(). This drops every instance registered with scoped() so that the next request rebuilds it.

ts
let count = 0
app.scoped('cart', () => ({ id: ++count, items: [] as string[] }))
app.singleton('config-cache', () => new Map<string, string>())
  • A scoped binding is shared within a request and rebuilt for the next one. Use it for anything tied to a request: the current user, a cart, a request id.
  • A singleton survives across requests, because the flush touches only scoped instances. Use it for connection pools, caches and configuration.

You can see it with two requests against a route that resolves the scoped binding:

ts
router.get('/cart', () => Response.json(app.make('cart')))

const first = await worker.handle(new Request({ method: 'GET', url: '/cart' }))
const second = await worker.handle(new Request({ method: 'GET', url: '/cart' }))

first.body // => '{"id":1,"items":[]}'
second.body // => '{"id":2,"items":[]}'

The flush runs in a finally block, so it happens even when the kernel or one of your hooks throws. worker.requestsHandled() counts handled requests, failures included.

Lifecycle hooks ​

Hooks are registered on the worker, and every registrar returns the worker so the calls chain.

ts
worker
  .onBoot((app) => warmCaches(app))
  .onRequest((request) => metrics.start(request))
  .onRequestHandled((request, response) => metrics.finish(request, response))
  .onTick(() => flushBuffers(), 5_000)
  .onTerminate((app) => closeConnections(app))
HookWhen it runs
onBootOnce, after the application has booted
onRequestBefore the kernel handles each request
onRequestHandledAfter the kernel returns a response, with the request and response
onTickPeriodically while the server runs (see below)
onTerminateOnce, when the worker terminates

Hooks run in registration order and may be async; the worker awaits each. If an onRequest or onRequestHandled hook throws, the request fails with that error (the per-request flush still runs). Keep these hooks fast and defensive, because they sit on the hot path of every request.

Periodic ticks ​

onTick(hook, intervalMs) registers a task and the interval at which it should run. server.start() (or worker.startTicking()) schedules each task on its own timer. Two safety properties are built in:

  • Timers are unref'd, so they never keep the process alive by themselves.
  • A tick that throws or rejects is swallowed, so a failing background task cannot crash the worker. If you need to know about failures, report them inside the hook.

Use ticks for housekeeping that must happen regularly in a long-lived process: flushing the monitor's buffer, pruning inspector entries, refreshing an in-memory cache.

ts
worker
  .onTick(() => monitor.flush(), 5_000)
  .onTick(() => void inspector.prune(Date.now() - 86_400_000), 60_000)

worker.stopTicking() clears the timers. await worker.tick() runs every registered tick task once, in order, which is how you drive them in tests without waiting.

Terminating ​

await worker.terminate() stops the ticks, runs the application's terminating callbacks (registered with app.terminating(...)), then runs your onTerminate hooks. server.stop() calls it for you.

Cluster mode ​

One Node process uses one CPU core. To use more, ask for several workers:

ts
await server.start({ port: 8000, workers: 4 })

With workers greater than 1, the primary process forks that many child processes with node:cluster. Each child runs the same entry script, boots its own warm application and serves on the shared port. If a child exits, the primary forks a replacement after an exponential backoff (500 ms, doubling up to 30 s). A circuit breaker stops this when children keep dying: after more than 5 restarts within 60 s the primary logs a ClusterCrashLoopError, shuts the pool down and sets a non-zero exit code. Tune it with restart: { baseDelayMs, maxDelayMs, maxRestarts, windowMs } and receive the error with onFatal.

Because every child executes your entry file, use the factory form so that the application is built inside each child rather than in the primary:

ts
const worker = new ClusterWorker({
  factory: async () => {
    const app = await createApplication()
    // ...build router and kernel
    return { app, kernel }
  },
})

const server = new ClusterServer(worker)
await server.start({ port: 8000, workers: 4 })
// In every role start() resolves with a server-shaped handle: pass it to gracefulShutdown(handle, ...).

A few consequences to plan for:

  • Each child is a separate process with its own memory. Singletons, in-memory caches (ArrayStore), rate-limiter counters and recorder buffers are not shared between children. Use a shared store such as Redis for anything that must be consistent across processes, as described in Cache and Rate Limiting.
  • Tick hooks run in every child by default, so a periodic task you register runs once per child. Set ticks: 'first-worker' to run them in exactly one child (a replacement takes over if it dies), or ticks: 'primary' to run them in the primary's own warm worker, which serves nothing.
  • A child that crashes during boot is re-forked with backoff and, if it keeps failing, the circuit breaker stops the pool. Make sure the application boots cleanly before turning on workers.
  • Under a test runner (VITEST, JEST_WORKER_ID or NODE_ENV=test set) the server never forks and always runs a single in-process worker.

What to avoid in a long-lived process ​

The usual rules for a short-lived request lifecycle no longer hold, because nothing is discarded between requests.

  • Request data in singletons. Never store the current user, request, session or tenant on a singleton or in a module-level variable. Bind it with scoped(), or pass it as an argument.
  • Module-level mutable state. A let at the top of a file is shared by every request for the life of the process.
  • Unbounded growth. Arrays, maps and in-memory stores that only ever grow, such as the default recorder stores in the inspector and monitor, will eventually exhaust memory. Prune them on a tick.
  • Listeners registered per request. Adding an event listener or timer inside a handler adds another on every request. Register them once, in a provider or an onBoot hook.
  • Configuration read at boot. Values captured at boot, including .env contents, do not change until the process restarts. Deploy by restarting workers.
  • Resources that need closing. Close database pools and other connections in onTerminate or the application's terminating callbacks, so a restart is clean.

Testing ​

ClusterWorker has no sockets, so you can test it by calling handle with a request built in memory. Nothing binds a port.

ts
import { Application } from '@plinthjs/core'
import { HttpKernel, Request, Response, Router } from '@plinthjs/http'
import { ClusterWorker } from '@plinthjs/cluster'
import { expect, it } from 'vitest'

it('isolates scoped state between requests', async () => {
  const app = new Application({ runningInConsole: false })
  let n = 0
  app.scoped('ticket', () => ({ n: ++n }))

  const router = new Router()
  router.get('/ticket', () => Response.json(app.make('ticket')))

  const worker = new ClusterWorker({ app, kernel: new HttpKernel(router, { container: app }) })
  const get = () => worker.handle(new Request({ method: 'GET', url: '/ticket' }))

  expect(JSON.parse((await get()).body ?? '{}')).toEqual({ n: 1 })
  expect(JSON.parse((await get()).body ?? '{}')).toEqual({ n: 2 })
  expect(worker.requestsHandled()).toBe(2)
})

Use await worker.tick() to fire tick hooks on demand. See Testing for the other fakes and in-memory drivers.

Running tasks concurrently ​

The package also exports a tiny helper, concurrently(tasks). It takes an array of functions that return promises, starts all of them at once and resolves with their results in order:

ts
import { concurrently } from '@plinthjs/cluster'

const [users, orders] = await concurrently([() => loadUsers(), () => loadOrders()])

It is a thin wrapper around Promise.all. For parallel work across threads, see Concurrency.

Released under the MIT License.