English

Build scalable microservices with Node.js using modern patterns and best practices.

Service Communication

REST Communication

// user-service/src/index.ts
import express from 'express';

const app = express();
app.use(express.json());

app.get('/users/:id', async (req, res) => {
  const user = await getUserById(req.params.id);
  res.json(user);
});

app.listen(3001);

Message Queue Pattern

// Using RabbitMQ
import amqp from 'amqplib';

async function publishMessage(queue: string, message: object) {
  const connection = await amqp.connect('amqp://localhost');
  const channel = await connection.createChannel();

  await channel.assertQueue(queue, { durable: true });
  channel.sendToQueue(queue, Buffer.from(JSON.stringify(message)));
}

API Gateway

import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';

const app = express();

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

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

app.listen(3000);

Docker Compose Setup

version: '3.8'
services:
  api-gateway:
    build: ./api-gateway
    ports:
      - '3000:3000'
    depends_on:
      - user-service
      - product-service

  user-service:
    build: ./user-service
    environment:
      - DATABASE_URL=postgresql://postgres:password@db:5432/users

  product-service:
    build: ./product-service
    environment:
      - DATABASE_URL=postgresql://postgres:password@db:5432/products

  db:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD: password

Health Checks

app.get('/health', (req, res) => {
  const health = {
    status: 'healthy',
    uptime: process.uptime(),
    timestamp: Date.now(),
  };
  res.json(health);
});

Best Practices

  1. Single Responsibility - Each service does one thing well
  2. API Versioning - Version your APIs for backward compatibility
  3. Circuit Breaker - Handle failures gracefully
  4. Centralized Logging - Aggregate logs from all services
  5. Service Discovery - Use tools like Consul or Kubernetes
0
0
0
0