Project 10: A Microservices Application

Node.js and Express: Build a Back End API from Scratch · Ten Portfolio Projects · 12 min read · Updated

One door, three services

  1. The gateway is the only public address. It verifies the token and forwards the request.
  2. The orders service asks the users service who the customer is, with a timeout.
  3. Orders saves the order and publishes order.created. It does not call anyone else.
  4. The notifications service reacts to the event on its own.

The last project is the one that people find hardest to picture, so it is built to be small and runnable. Instead of one app, there are three small services and a front door. Each service has one job, they talk to each other over HTTP and through an event broker, and the only way in from the outside is the gateway. It runs in one process for the test, but every part uses its own port and could be moved to its own machine, which is the whole point. Read lesson 38 first for the reasons to split, and the reasons not to.

What you will build

  • A users service that owns user data.
  • An orders service that creates orders, asks the users service who the customer is, and publishes an order.created event.
  • A notifications service that listens for events and reacts, with no HTTP call from the orders service.
  • An API gateway, the only public address. It checks the JWT and forwards requests to the right service.
  • /health on every service, a 504 for timeouts at the gateway and a clear 503 when a dependency is down.

Design decisions before any code

Each service owns its own data, and nobody reads another service's data directly. The orders service does not open the users data. It asks the users service over HTTP. That is the rule that makes the services independent, and it costs something: a network call can fail, so there must be a timeout and an error. For work that does not need an answer, such as sending a notification, the orders service publishes an event to a broker, and the notifications service subscribes. The orders service neither knows nor cares who listens. In this project the broker is a few lines on top of EventEmitter. In production it would be Redis with BullMQ, RabbitMQ or Kafka, as in lesson 35.

The gateway checks the token once and then forwards the request, so the services behind it can trust that the caller was checked. This only works if the services are not reachable from the internet, so in a real system they sit on a private network, as the Compose file below shows.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express jsonwebtoken.
  3. Copy p-kit.js, p10-microservices.js and p10.test.js into the folder. The shared p-kit.js is in Project 1.
  4. Install the test tools with npm install -D supertest, then run node --test p10.test.js.

All four parts in one file so that you can read the whole system. Each start... function creates one service on a free port and returns its URL.

// Project 10: three small services and a gateway, running in one process so you can test them.
//   users service      owns user data
//   orders service     owns orders, asks the users service who the customer is, publishes "order.created"
//   notifications      listens to events from the broker (a queue between services)
//   gateway            the ONLY public door: checks the token, then forwards to a service
import express from 'express';
import http from 'node:http';
import { EventEmitter } from 'node:events';
import { requireAuth, errorHandler, notFoundHandler, AppError } from './p-kit.js';

const listen = (app) => new Promise((resolve) => { const server = http.createServer(app).listen(0, () => resolve({ server, url: `http://127.0.0.1:${server.address().port}` })); });

// A message broker in miniature. In production this is Redis (BullMQ), RabbitMQ or Kafka.
export function createBroker() {
  const bus = new EventEmitter();
  return { publish: (topic, message) => setImmediate(() => bus.emit(topic, message)), subscribe: (topic, handler) => bus.on(topic, handler) };
}

export async function startUsers() {
  const app = express();
  const users = new Map([[1, { id: 1, name: 'Asha' }], [2, { id: 2, name: 'Ravi' }]]);
  app.get('/users/:id', (req, res) => (users.has(Number(req.params.id)) ? res.json(users.get(Number(req.params.id))) : res.status(404).json({ error: 'User not found' })));
  app.get('/health', (req, res) => res.json({ ok: true }));
  return listen(app);
}

export async function startOrders({ usersUrl, broker }) {
  const app = express();
  app.use(express.json());
  const orders = [];

  app.post('/orders', async (req, res) => {
    // Service-to-service call with a time limit: never wait forever for another service.
    let customer;
    try {
      const reply = await fetch(`${usersUrl}/users/${req.body.userId}`, { signal: AbortSignal.timeout(1000) });
      if (reply.status === 404) return res.status(422).json({ error: 'Unknown user' });
      customer = await reply.json();
    } catch {
      return res.status(503).json({ error: 'User service is not available, try again later' });   // fail clearly, do not crash
    }
    const order = { id: orders.length + 1, userId: customer.id, item: String(req.body.item ?? ''), status: 'created' };
    orders.push(order);
    broker.publish('order.created', { orderId: order.id, userName: customer.name, item: order.item });    // others react later
    res.status(201).json(order);
  });

  app.get('/orders', (req, res) => res.json(orders.filter((o) => o.userId === Number(req.query.userId))));
  app.get('/health', (req, res) => res.json({ ok: true }));
  return listen(app);
}

export function startNotifications({ broker }) {
  const sent = [];
  broker.subscribe('order.created', (event) => sent.push(`Thanks ${event.userName}, we got your order for ${event.item}`));
  return { sent };
}

export async function startGateway({ usersUrl, ordersUrl }) {
  const app = express();
  app.use(express.json());
  const auth = requireAuth();

  const forward = (base) => async (req, res) => {
    const reply = await fetch(base + req.originalUrl.replace(/^\/api/, ''), {
      method: req.method,
      headers: { 'content-type': 'application/json' },
      body: ['GET', 'HEAD'].includes(req.method) ? undefined : JSON.stringify({ ...req.body, userId: req.user.id }),   // the user id comes from the TOKEN, never from the client
      signal: AbortSignal.timeout(2000),
    });
    res.status(reply.status).json(await reply.json());
  };

  app.get('/api/users/me', auth, (req, res, next) => { req.url = `/users/${req.user.id}`; req.originalUrl = req.url; next(); }, forward(usersUrl));
  app.post('/api/orders', auth, forward(ordersUrl));
  app.get('/api/orders', auth, (req, res, next) => { req.originalUrl = `/orders?userId=${req.user.id}`; next(); }, forward(ordersUrl));
  app.get('/health', (req, res) => res.json({ ok: true }));

  app.use(notFoundHandler);
  app.use((err, req, res, next) => (err.name === 'TimeoutError' ? res.status(504).json({ error: 'Service timed out' }) : errorHandler(err, req, res, next)));
  return { ...(await listen(app)), app };
}

How the same four parts would run as containers. This file was not run. Only the gateway publishes a port to the outside.

# The same system as separate containers. NOT run in this course.
services:
  gateway:
    build: ./gateway
    ports: ["3000:3000"]
    environment:
      USERS_URL: http://users:3001
      ORDERS_URL: http://orders:3002
      JWT_SECRET: ${JWT_SECRET}
    depends_on: [users, orders]

  users:
    build: ./users                    # no ports: only the gateway can reach it
    environment:
      MONGODB_URI: mongodb://users-db:27017/users
    depends_on: [users-db]

  orders:
    build: ./orders
    environment:
      USERS_URL: http://users:3001
      REDIS_HOST: redis
      MONGODB_URI: mongodb://orders-db:27017/orders
    depends_on: [orders-db, redis]

  notifications:
    build: ./notifications
    environment:
      REDIS_HOST: redis
    depends_on: [redis]

  users-db:
    image: mongo:7
  orders-db:
    image: mongo:7
  redis:
    image: redis:7-alpine

The test starts all the services, logs in through the gateway, creates an order and waits for the notification, and then stops the users service to see that the orders service answers with a clear 503.

import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createBroker, startUsers, startOrders, startNotifications, startGateway } from './p10-microservices.js';
import { signToken } from './p-kit.js';

const as = (id) => ({ Authorization: `Bearer ${signToken({ id, role: 'user', name: `u${id}` })}` });

test('project 10: gateway, services and events', async () => {
  const broker = createBroker();
  const users = await startUsers();
  const orders = await startOrders({ usersUrl: users.url, broker });
  const notifications = startNotifications({ broker });
  const gateway = await startGateway({ usersUrl: users.url, ordersUrl: orders.url });

  assert.equal((await request(gateway.url).get('/api/orders')).status, 401);              // the gateway checks the token

  const me = await request(gateway.url).get('/api/users/me').set(as(1));
  assert.equal(me.body.name, 'Asha');

  // The client tries to order as another user: the gateway overwrites userId from the token.
  const order = await request(gateway.url).post('/api/orders').set(as(1)).send({ item: 'Keyboard', userId: 2 });
  assert.equal(order.status, 201);
  assert.equal(order.body.userId, 1);

  await new Promise((resolve) => setTimeout(resolve, 20));
  assert.deepEqual(notifications.sent, ['Thanks Asha, we got your order for Keyboard']);   // another service reacted to the event

  assert.equal((await request(gateway.url).get('/api/orders').set(as(1))).body.length, 1);
  assert.equal((await request(gateway.url).get('/api/orders').set(as(2))).body.length, 0);
  assert.equal((await request(gateway.url).post('/api/orders').set(as(99)).send({ item: 'X' })).status, 422);    // unknown user

  // Take the users service down: orders fail clearly with 503 instead of hanging or crashing.
  users.server.close();
  users.server.closeAllConnections();
  assert.equal((await request(gateway.url).post('/api/orders').set(as(1)).send({ item: 'Mouse' })).status, 503);

  for (const s of [orders, gateway]) { s.server.close(); s.server.closeAllConnections(); }
});

Rules worth understanding

Synchronous and asynchronous calls. Use a direct HTTP call when you need the answer now, such as *who is this customer*. Use an event when you only need to say *this happened*. Events keep services loosely coupled, and they let you add new reactions without changing the sender.

Timeouts everywhere. Every call between services has a timeout, using AbortSignal.timeout as in lesson 23. When a service does not answer in time, the gateway returns 504 instead of hanging. When the orders service cannot reach the users service at all, it answers 503 with a plain message.

A single public door. Only the gateway is exposed. It verifies the JWT, and the services trust what comes through it. Do not let outside traffic reach a service directly.

Health checks. Each service has /health. A load balancer, Docker or an uptime tool calls it and replaces or avoids a sick service.

Failure is normal. The test stops one service on purpose and checks that the system fails in a controlled way. When you design for several services, think about what happens when each of them is down.

Security and honesty notes

Services should not trust each other blindly. A production system adds service-to-service authentication, and keeps private networks, logs with a shared request id, and monitoring. Distributed systems also make data consistency harder: an order may exist while its notification is still on the way. Think about retries and idempotency as in lessons 35 and 37.

Be honest about the trade. For most projects, one well-organised app is easier to build, test and run. Choose several services when you can say why, and be ready to explain that choice in an interview.

Extend it

Your task

  1. Add a fourth service for products and make the orders service check stock through it.
  2. Pass a request id from the gateway to every service and log it, as in lesson 33.
  3. Replace the broker with BullMQ and Redis, and run everything with Docker Compose.

How to check it worked

  • The only public address is the gateway.
  • A stopped users service gives a clear 503 and not a hang.
  • The notification arrives without the orders service calling it.

On your resume. "Built a small microservices system with an API gateway, service-to-service calls with timeouts, an event broker and health checks" is a precise line. Say clearly that it was a learning project, and what you would add for production. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.

Frequently asked questions

Why not let services read each other's databases?

Shared databases couple the services together, so changing one breaks the others. Each service should own its data and share it through its API or events.

Why publish an event instead of calling the notification service?

The orders service does not need an answer, and an event lets you add or remove listeners without changing the sender.

Is this how real companies do it?

The ideas are the same. Real systems add message brokers like RabbitMQ or Kafka, service meshes, tracing and orchestration such as Kubernetes.

Practise with interview questions