- โก Node.js Cluster Simulation (TypeScript) ๐
- A Production-Grade Process Cluster Demonstration
- ๐ Table of Contents
- ๐ฏ Project Overview
- โจ Key Features
- ๐๏ธ System Architecture
- ๐ ๏ธ Tech Stack
- ๐ Project Structure
- โ๏ธ How It Works
- ๐ Example Output
- โ๏ธ Installation & Setup
- ๐ Running the Simulation
- ๐ Core Concepts Implemented
- ๐๏ธ Design Principles
- ๐ Performance Characteristics
- ๐ฎ Future Enhancements
- ๐ Learning Outcomes
- ๐ก Key Takeaways
- ๐ค Common Questions
- ๐จโ๐ป Author
- ๐ License
- ๐ Acknowledgments
This project provides a deep dive into Node.js process clustering by simulating how production systems handle multi-process execution, load distribution, and fault tolerance. Built from scratch without frameworks, it demonstrates the fundamental patterns behind scaling Node.js applications across multiple CPU cores.
| Concept | Implementation |
|---|---|
| Multi-process execution | Each worker runs in a separate process |
| Load balancing | Round-robin scheduler distributes tasks evenly |
| Worker lifecycle management | Spawn, monitor, and restart workers |
| Fault tolerance | Automatic recovery from worker crashes |
| IPC communication | Master-worker message passing |
| CPU-aware scaling | Workers match CPU core count |
| Category | Feature | Status |
|---|---|---|
| Process Management | Multi-process execution with child processes | โ |
| Load Balancing | Round-robin task distribution algorithm | โ |
| Fault Tolerance | Automatic worker restart on crash | โ |
| IPC Communication | Bidirectional message passing | โ |
| CPU Detection | Automatic core count detection | โ |
| Task Execution | CPU-intensive computation simulation | โ |
| Random Failures | Simulated worker crashes for testing | โ |
| Logging System | Comprehensive execution logging | โ |
| Type Safety | Full TypeScript implementation | โ |
| Modular Architecture | Separation of concerns | โ |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ MASTER PROCESS โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ WORKER MANAGER โ โ
โ โ โข Spawns workers based on CPU cores โ โ
โ โ โข Monitors worker health โ โ
โ โ โข Restarts crashed workers automatically โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ TASK SCHEDULER โ โ
โ โ โข Generates CPU-intensive tasks โ โ
โ โ โข Distributes tasks using round-robin โ โ
โ โ โข Tracks execution flow and results โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ IPC LAYER โ โ
โ โ โข Sends tasks to workers โ โ
โ โ โข Receives computation results โ โ
โ โ โข Handles worker exit events โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
IPC Messages (send/receive)
โ
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโผโโโโโโโโโโโโฌโโโโโโโโโโโโโโ
โ โ โ โ โ
โผ โผ โผ โผ โผ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
โ WORKER 1 โ โ WORKER 2 โ โ WORKER 3 โ โ WORKER N โ
โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ
โ โ Execute โ โ โ โ Execute โ โ โ โ Execute โ โ โ โ Execute โ โ
โ โ Tasks โ โ โ โ Tasks โ โ โ โ Tasks โ โ โ โ Tasks โ โ
โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ
โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ
โ โ Return โ โ โ โ Return โ โ โ โ Return โ โ โ โ Return โ โ
โ โ Results โ โ โ โ Results โ โ โ โ Results โ โ โ โ Results โ โ
โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ
โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ
โ โSimulate โ โ โ โSimulate โ โ โ โSimulate โ โ โ โSimulate โ โ
โ โCrashes โ โ โ โCrashes โ โ โ โCrashes โ โ โ โCrashes โ โ
โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ โ โโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
| Component | Responsibility | Files |
|---|---|---|
| Master Process | Orchestrates workers and task distribution | index.ts |
| Worker Manager | Spawns, monitors, and restarts workers | workerManager.ts |
| Task Scheduler | Generates and distributes tasks | taskScheduler.ts |
| Worker | Executes CPU-intensive tasks | worker.ts |
| IPC Layer | Handles inter-process communication | Built into Node.js |
| Logger | Provides structured logging | logger.ts |
| Types | TypeScript interfaces | message.ts |
| Technology | Purpose | Badge |
|---|---|---|
| Node.js | JavaScript Runtime | |
| TypeScript | Static Typing | |
| child_process | Process Creation | |
| IPC | Process Communication | |
| OS Module | CPU Detection |
node-cluster-simulation/
โ
โโโ ๐ src/
โ โ
โ โโโ ๐ types/
โ โ โโโ ๐ message.ts # IPC message interfaces
โ โ
โ โโโ ๐ utils/
โ โ โโโ ๐ logger.ts # Structured logging utility
โ โ
โ โโโ ๐ worker/
โ โ โโโ ๐ worker.ts # Worker process implementation
โ โ
โ โโโ ๐ master/
โ โ โโโ ๐ workerManager.ts # Worker lifecycle management
โ โ โโโ ๐ taskScheduler.ts # Round-robin task distribution
โ โ
โ โโโ ๐ index.ts # Master process entry point
โ
โโโ ๐ package.json # Dependencies & scripts
โโโ ๐ tsconfig.json # TypeScript configuration
โโโ ๐ .gitignore # Git ignore rules
โโโ ๐ README.md # DocumentationThe master process is the orchestrator that manages everything:
// Simplified master process flow
1. Detect available CPU cores
2. Spawn worker processes (one per core)
3. Initialize task scheduler
4. Monitor worker health
5. Handle graceful shutdownResponsibilities:
- Detects CPU core count using
os.cpus() - Spawns workers using
child_process.fork() - Manages worker lifecycle
- Coordinates IPC communication
- Handles system signals (SIGINT, SIGTERM)
Each worker runs independently and handles tasks:
// Simplified worker flow
1. Initialize and register with master
2. Wait for task messages
3. Execute CPU-intensive computation
4. Send result back to master
5. Simulate random crash (for testing)Responsibilities:
- Execute CPU-heavy computations
- Simulate random failures
- Return results via IPC
- Handle task cancellation
Round-robin algorithm ensures fair distribution:
// Round-robin scheduler logic
Tasks: T1 T2 T3 T4 T5 T6
Worker1: T1 T3 T5
Worker2: T2 T4 T6Characteristics:
- Even distribution across all workers
- No worker starvation
- Simple and predictable
- Low overhead
Automatic recovery from worker failures:
// Fault tolerance flow
1. Worker crashes (simulated or real)
2. Master detects 'exit' event
3. Logs the failure
4. Automatically spawns replacement worker
5. Continues task distributionKey properties:
- No single point of failure
- Automatic recovery
- Minimal downtime
- Continuous operation
[INFO] ========================================
[INFO] Node.js Cluster Simulation Starting
[INFO] ========================================
[INFO] Detected 8 CPU cores
[INFO] Spawning 8 worker processes...
[INFO] Started worker 1024 (PID: 1024)
[INFO] Started worker 1025 (PID: 1025)
[INFO] Started worker 1026 (PID: 1026)
[INFO] Started worker 1027 (PID: 1027)
[INFO] Started worker 1028 (PID: 1028)
[INFO] Started worker 1029 (PID: 1029)
[INFO] Started worker 1030 (PID: 1030)
[INFO] Started worker 1031 (PID: 1031)
[INFO] All 8 workers ready
[INFO] Starting task distribution...
[INFO] Sending task 1 to worker 1024
[INFO] Task 1 completed by worker 1024. Result: 4839201
[INFO] Sending task 2 to worker 1025
[INFO] Task 2 completed by worker 1025. Result: 7234156
[INFO] Sending task 3 to worker 1026
[WARN] Worker 1026 crashed unexpectedly!
[INFO] Restarting worker 1026...
[INFO] Started replacement worker 1040
[INFO] Task 3 reassigned to worker 1040
[INFO] Task 3 completed by worker 1040. Result: 5678902
[INFO] Sending task 4 to worker 1027
[INFO] Task 4 completed by worker 1027. Result: 3456789
[INFO] ========================================
[INFO] Simulation Complete
[INFO] Total tasks: 100
[INFO] Completed tasks: 98
[INFO] Failed tasks: 2
[INFO] Restarts performed: 2
[INFO] ========================================- โ Node.js (v18 or higher)
- โ npm or yarn package manager
- โ Git (for cloning)
# 1. Clone the repository
git clone https://github.com/elyse502/cluster-simulation.git
# 2. Navigate to project directory
cd cluster-simulation
# 3. Install dependencies
npm install
# 4. Run the simulation
npm run devnpm run devFeatures:
- Auto-restarts on file changes
- Source maps for debugging
- Real-time log output
npm run buildCompiles TypeScript to JavaScript in the
dist/folder
npm startRuns the compiled JavaScript from
dist/folder
{
"scripts": {
"dev": "nodemon --watch src --exec ts-node src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
}| Concept | Implementation Details |
|---|---|
| Process Management | Using child_process.fork() to create independent processes |
| Inter-Process Communication | Message passing via process.send() and process.on('message') |
| Scheduling Algorithm | Round-robin with index-based worker selection |
| Resilience Pattern | Auto-restart strategy with event listeners |
| CPU Scaling | Worker count matches os.cpus().length |
| Event-Driven Architecture | Node.js EventEmitter for process events |
| Graceful Shutdown | SIGINT/SIGTERM handlers for cleanup |
Worker Creation:
const worker = fork(path.join(__dirname, "worker.js"));
worker.on("message", handleResult);
worker.on("exit", handleCrash);Task Distribution:
const workerIndex = taskCount % workers.length;
workers[workerIndex].send({ type: "task", data });Worker Logic:
process.on("message", async (msg) => {
const result = await computeIntensiveTask(msg.data);
process.send({ type: "result", data: result });
});| Layer | Location | Responsibility |
|---|---|---|
| Worker Logic | worker.ts |
Task execution only |
| Scheduling Logic | taskScheduler.ts |
Task distribution only |
| Process Management | workerManager.ts |
Worker lifecycle only |
| Utilities | logger.ts |
Logging only |
Single Core โ 1 worker
Dual Core โ 2 workers
Quad Core โ 4 workers
Octa Core โ 8 workers
- No single point of failure - Workers are independent
- Automatic recovery - Failed workers restart automatically
- Graceful degradation - System continues with fewer workers
- Self-healing - Returns to full capacity after crashes
| Metric | Expected Value | Notes |
|---|---|---|
| Worker startup time | ~50ms | Per worker process |
| IPC message latency | <1ms | Local communication |
| Task throughput | Scales linearly | With CPU cores |
| Recovery time | ~50ms | After worker crash |
| Memory overhead | ~10MB/worker | Additional per process |
| Feature | Priority | Description |
|---|---|---|
| ๐ฆ Task Queue Buffer | High | Queue tasks when all workers busy |
| ๐ Health Monitoring | High | Periodic health checks with timeouts |
| ๐ Metrics Integration | Medium | Prometheus metrics export |
| ๐ REST API Control | Medium | HTTP endpoints for management |
| ๐ก Real-time Dashboard | Low | Socket.IO visualization |
| ๐ณ Docker Support | Low | Containerized deployment |
| โก Worker Pool | Low | Pre-warmed worker pool |
| ๐ Task Priorities | Low | Priority-based scheduling |
This project helps you understand:
- How
child_processworks internally - Event loop across multiple processes
- Memory isolation between processes
- Trade-offs between single vs multi-process
- Consistency vs availability
- Failure detection patterns
- Horizontal scaling strategies
- Load balancing algorithms
- Resilient system patterns
- Process spawning and termination
- Signal handling (SIGINT, SIGTERM)
- Graceful shutdown procedures
- EventEmitter patterns
- Asynchronous message passing
- Non-blocking operations
- TypeScript for process communication
- Interface-based design
- Compile-time safety
| Concept | Takeaway |
|---|---|
| Multi-processing | Node.js can utilize multiple CPU cores via child processes |
| IPC | Message passing is the primary way to communicate between processes |
| Load Balancing | Round-robin is simple but effective for homogeneous tasks |
| Fault Tolerance | Automatic restart is the first line of defense against failures |
| Process Isolation | Each worker has its own memory space - no shared state |
| CPU Scaling | Worker count should match CPU cores for optimal performance |
Q: Why not use the built-in cluster module?
A: This project intentionally avoids frameworks to demonstrate low-level concepts.
Q: How does this handle shared state? A: Each worker has isolated memory. State must be managed by the master.
Q: Can this run on Windows? A: Yes, Node.js child processes work on all platforms.
Q: What's the maximum number of workers? A: Limited by system memory and CPU cores. Typically 8-16 workers.
Junior Fullstack Software Engineer
This project is licensed under the MIT License - see the LICENSE file for details.
- Node.js Team - For the amazing child_process API
- TypeScript Team - For type-safe JavaScript
- Open Source Community - For inspiration and patterns
Built with ๐ป, TypeScript, and Deep System Understanding
This project intentionally avoids frameworks to focus on native Node.js behavior, process-level communication, and system-level architecture.