diff --git a/backend/src/api/disk-cache.ts b/backend/src/api/disk-cache.ts index 50f66b6c5..2f74fe3a5 100644 --- a/backend/src/api/disk-cache.ts +++ b/backend/src/api/disk-cache.ts @@ -1,5 +1,6 @@ +const config = require('../../mempool-config.json'); import * as fs from 'fs'; -import * as cluster from 'cluster'; +import * as process from 'process'; import memPool from './mempool'; import blocks from './blocks'; @@ -7,15 +8,17 @@ class DiskCache { static FILE_NAME = './cache.json'; constructor() { - process.on('SIGINT', () => { - this.saveCacheToDisk(); - process.exit(2); - }); + if (process.env.workerId === '0' || !config.CLUSTER_NUM_CORES || config.CLUSTER_NUM_CORES === 1) { + process.on('SIGINT', () => { + this.saveCacheToDisk(); + process.exit(2); + }); - process.on('SIGTERM', () => { - this.saveCacheToDisk(); - process.exit(2); - }); + process.on('SIGTERM', () => { + this.saveCacheToDisk(); + process.exit(2); + }); + } } saveCacheToDisk() { diff --git a/backend/src/index.ts b/backend/src/index.ts index 36676d944..3673a31be 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -37,12 +37,19 @@ class Server { const numCPUs = config.CLUSTER_NUM_CORES; for (let i = 0; i < numCPUs; i++) { - cluster.fork(); + const env = { workerId: i }; + const worker = cluster.fork(env); + worker.process['env'] = env; } cluster.on('exit', (worker, code, signal) => { - console.log(`Mempool Worker #${worker.process.pid} died. Restarting in 10 seconds...`, signal || code); - setTimeout(() => { cluster.fork(); }, 10000); + const workerId = worker.process['env'].workerId; + console.log(`Mempool Worker PID #${worker.process.pid} workerId: ${workerId} died. Restarting in 10 seconds...`, signal || code); + setTimeout(() => { + const env = { workerId: workerId }; + const newWorker = cluster.fork(env); + newWorker.process['env'] = env; + }, 10000); }); } else { this.startServer(true);