Legion commander! Consul Caesar.js will teach you how to build an entire network of provinces from a single Roman fort that can conquer all territories of the world! It's time to learn the secrets of scaling and microservices architecture.
Scaling and Microservices are techniques for building applications that can grow and adapt to increasing traffic and business complexity.
1// Load balancer configuration
2const cluster = require('cluster');
3const numCPUs = require('os').cpus().length;
4
5if (cluster.isMaster) {
6 console.log(\`Master \${process.pid} is running\`);
7
8 // Fork workers
9 for (let i = 0; i < numCPUs; i++) {
10 cluster.fork();
11 }
12
13 cluster.on('exit', (worker, code, signal) => {
14 console.log(\`Worker \${worker.process.pid} died\`);
15 cluster.fork(); // Restart worker
16 });
17} else {
18 // Workers can share any TCP port
19 require('./dist/main');
20 console.log(\`Worker \${process.pid} started\`);
21}1// User microservice
2@Controller('users')
3export class UserController {
4 constructor(
5 @Inject('TRIBUTE_SERVICE') private tributeService: ClientProxy,
6 @Inject('LEGION_SERVICE') private legionService: ClientProxy,
7 ) {}
8
9 @Get(':id/tributes')
10 async getUserTributes(@Param('id') userId: string) {
11 const user = await this.userService.findById(userId);
12 const tributes = await this.tributeService
13 .send('get_user_tributes', { userId })
14 .toPromise();
15
16 return { user, tributes };
17 }
18}
19
20// Message patterns
21export const USER_PATTERNS = {
22 GET_USER: 'get_user',
23 CREATE_USER: 'create_user',
24 UPDATE_USER: 'update_user',
25};