0
0
Expressframework~5 mins

Microservice communication basics in Express

Choose your learning style9 modes available
Introduction

Microservices need to talk to each other to work together. Communication basics help them share data and tasks smoothly.

When building a shopping app where the cart service talks to the product service.
When a user service needs to check permissions from an auth service.
When an order service sends payment info to a billing service.
When a notification service sends alerts after an event happens.
When scaling parts of an app independently but they still need to work together.
Syntax
Express
HTTP request example:
GET /service-endpoint HTTP/1.1
Host: service-host

OR

Message queue example:
Producer sends message to queue
Consumer listens and processes message

Microservices often use HTTP or messaging to communicate.

HTTP is simple and synchronous; messaging is good for async tasks.

Examples
This shows a microservice calling another via HTTP GET to get product info.
Express
GET /products/123 HTTP/1.1
Host: product-service

Response: 200 OK
{
  "id": 123,
  "name": "Shoes",
  "price": 50
}
This shows async communication using a message queue between services.
Express
Producer sends message:
{
  "orderId": 456,
  "status": "paid"
}

Consumer listens and updates order status.
Sample Program

This example shows two microservices in one app: a product service and an order service. The order service calls the product service using HTTP to get product details.

Express
const express = require('express');
const app = express();
const port = 3000;

// Product service
app.get('/product/:id', (req, res) => {
  const product = { id: req.params.id, name: 'Book', price: 20 };
  res.json(product);
});

// Order service calls product service
const fetch = require('node-fetch');

app.get('/order/:id', async (req, res) => {
  const productId = 1;
  const response = await fetch(`http://localhost:3000/product/${productId}`);
  const product = await response.json();
  res.json({ orderId: req.params.id, product });
});

app.listen(port, () => {
  console.log(`Services running on port ${port}`);
});
OutputSuccess
Important Notes

Use REST or messaging based on your app needs.

Keep communication simple and clear to avoid confusion.

Handle failures gracefully, like retries or fallbacks.

Summary

Microservices communicate mainly via HTTP or messaging.

Choose sync or async communication based on task needs.

Design communication to be reliable and easy to maintain.