Scale your application across multiple CPU cores with zero-downtime reloads CanxJS's cluster mode is built on top of the Node.js cluster module, but adds significant power:
Traffic is distributed round-robin across all worker processes.
Update code without dropping a single connection.
Dead workers are instantly replaced to maintain availability.
Utilize all available CPU cores for maximum performance.
Use the initCluster() function Typically, you want one worker per CPU core. CanxJS defaults to os.cpus().length. Set workers: 'auto' to automatically detect CPU cores.
1import { initCluster, CanxServer } from 'canxjs';23// Initialize Cluster4initCluster({5enabled: true,6workers: 'auto', // Auto-detect CPU cores7});89const app = new CanxServer();10app.start();
Customize cluster behavior with lifecycle hooks and environment-based settings.
1initCluster({2enabled: process.env.NODE_ENV === 'production',3workers: 4, // Force 4 workers4wrapper: (app) => {5console.log(`Worker ${process.pid} started`);6},7onWorkerExit: (worker, code, signal) => {8console.log(`Worker ${worker.process.pid} died`);9}10});
| Option | Type | Description |
|---|---|---|
| enabled | boolean | Enable/disable cluster mode |
| workers | 'auto' | number | Number of workers or auto-detect |
| wrapper | function | Called when worker starts |
| onWorkerExit | function | Called when worker dies |
Gracefully reload all workers without dropping connections. Workers are replaced one-by-one.
1// Send SIGUSR2 to master process for graceful reload2// All workers are replaced one-by-one34// In your deployment script:5// kill -SIGUSR2 $(cat /var/run/canx.pid)67// Or use the CLI:8// node canx cluster:reload