-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti-backend-server.js
More file actions
53 lines (43 loc) · 1.79 KB
/
Copy pathmulti-backend-server.js
File metadata and controls
53 lines (43 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// backend-cluster.js
const cluster = require('cluster');
const os = require('os');
const express = require('express');
const NUM_SERVERS = 7; // how many backend instances you want
const BASE_PORT = 5001; // first port; others increment automatically
// `cluster.isPrimary` in recent Node; fall back to isMaster for older versions
const isPrimary = cluster.isPrimary ?? cluster.isMaster;
if (isPrimary) {
console.log(`Primary process PID: ${process.pid}`);
for (let i = 0; i < NUM_SERVERS; i++) {
cluster.fork({ PORT: BASE_PORT + i });
}
// (Optional) auto-respawn a crashed worker
cluster.on('exit', (worker, code, signal) => {
const oldPort = worker.process.env?.PORT;
console.log(`Worker ${worker.process.pid} for port ${oldPort} died (${signal || code}). Restarting...`);
// Re-spawn with same port if we know it; otherwise fall back to next available
cluster.fork({ PORT: oldPort || (BASE_PORT + Math.floor(Math.random() * NUM_SERVERS)) });
});
} else {
const port = Number(process.env.PORT);
const app = express();
// identify this worker
const workerId = cluster.worker?.id || 'unknown';
app.get('/', async (req, res) => {
console.log(`Received request on backend worker #${workerId} on port ${port}`);
await new Promise(resolve => setTimeout(resolve, 1000));
res.send(`Hello from backend worker #${workerId} on port ${port}`);
});
app.get('/health', (req, res) => {
res.send('OK');
});
// helpful endpoint to simulate variable response time
app.get('/work', async (req, res) => {
const ms = Number(req.query.ms || 0);
if (ms > 0) await new Promise(r => setTimeout(r, ms));
res.json({ workerId, port, delayedMs: ms });
});
app.listen(port, () => {
console.log(`Worker #${workerId} listening on port ${port}`);
});
}