Advanced Node.js

Master advanced Node.js concepts including microservices, performance optimization, and production deployment.

advanced Backend Development 7 hours

Chapter 6: Microservices Architecture

Chapter 6 of 15

Chapter 6: Microservices Architecture

6.1 Microservices Patterns

Microservices architecture breaks applications into small, independent services that communicate over well-defined APIs.

Key Principles:

  • Single Responsibility - Each service does one thing well
  • Independent Deployment - Services can be deployed separately
  • Technology Diversity - Services can use different technologies
  • Fault Isolation - Failure in one service doesn't break others
// Service structure
services/
  user-service/
    src/
      controllers/
      services/
      models/
      routes/
    package.json
    Dockerfile
  
  order-service/
    src/
      ...
    package.json
    Dockerfile

6.2 Service Communication

// HTTP/REST communication
const axios = require('axios');

class UserService {
    async getUser(userId) {
        const response = await axios.get(`http://user-service:3001/users/${userId}`);
        return response.data;
    }
}

// Message Queue (RabbitMQ)
const amqp = require('amqplib');

async function publishMessage(queue, message) {
    const connection = await amqp.connect('amqp://localhost');
    const channel = await connection.createChannel();
    await channel.assertQueue(queue);
    channel.sendToQueue(queue, Buffer.from(JSON.stringify(message)));
}

// gRPC communication
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');

const packageDefinition = protoLoader.loadSync('user.proto');
const userProto = grpc.loadPackageDefinition(packageDefinition);
const client = new userProto.UserService('localhost:50051', grpc.credentials.createInsecure());

6.3 Service Discovery

// Using Consul for service discovery
const consul = require('consul')();

// Register service
consul.agent.service.register({
    name: 'user-service',
    address: 'localhost',
    port: 3001,
    check: {
        http: 'http://localhost:3001/health',
        interval: '10s'
    }
});

// Discover service
consul.health.service({ service: 'user-service', passing: true }, (err, result) => {
    const service = result[0];
    const serviceUrl = `http://${service.Service.Address}:${service.Service.Port}`;
});

6.4 API Gateway Pattern

// Express API Gateway
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

app.use('/users', createProxyMiddleware({
    target: 'http://user-service:3001',
    changeOrigin: true
}));

app.use('/orders', createProxyMiddleware({
    target: 'http://order-service:3002',
    changeOrigin: true
}));

app.listen(3000);