Module 8: Microservices & Architecture

Learn microservices architecture, service communication, API gateway patterns, and container orchestration with Node.js.

Back to Course|5 hours|Advanced

Microservices & Architecture

Learn microservices architecture, service communication, API gateway patterns, and container orchestration with Node.js.

Progress: 0/4 topics completed0%

Select Topics Overview

Microservices Architecture

Understand microservices architecture principles, benefits, and implementation patterns

Content by: Parth Patel

Node.js Developer

Connect

What are Microservices?

Microservices is an architectural style where an application is built as a collection of small, independent services that communicate over well-defined APIs. Each service is responsible for a specific business capability and can be developed, deployed, and scaled independently.

Microservices vs Monolith

  • **Monolith**: Single, large application with all functionality in one codebase
  • **Microservices**: Multiple small services, each handling specific business logic
  • **Benefits of Microservices**: Independent deployment, technology diversity, fault isolation, scalability
  • **Challenges**: Distributed system complexity, network latency, data consistency, operational overhead

Basic Microservice Structure

Code Example
// User Service (users-service/index.js)
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

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

// Connect to User Service Database
mongoose.connect('mongodb://localhost:27017/users-service');

// User Schema
const userSchema = new mongoose.Schema({
    username: String,
    email: String,
    password: String,
    createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

// User Service Routes
app.get('/api/users', async (req, res) => {
    try {
        const users = await User.find({}, '-password');
        res.json(users);
    } catch (error) {
        res.status(500).json({ error: 'Failed to fetch users' });
    }
});

app.get('/api/users/:id', async (req, res) => {
    try {
        const user = await User.findById(req.params.id, '-password');
        if (!user) {
            return res.status(404).json({ error: 'User not found' });
        }
        res.json(user);
    } catch (error) {
        res.status(500).json({ error: 'Failed to fetch user' });
    }
});

app.post('/api/users', async (req, res) => {
    try {
        const user = new User(req.body);
        await user.save();
        res.status(201).json({ id: user._id, username: user.username, email: user.email });
    } catch (error) {
        res.status(400).json({ error: 'Failed to create user' });
    }
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`User service running on port ${PORT}`);
});

// Order Service (orders-service/index.js)
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const axios = require('axios');

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

// Connect to Order Service Database
mongoose.connect('mongodb://localhost:27017/orders-service');

// Order Schema
const orderSchema = new mongoose.Schema({
    userId: String,
    products: [{
        productId: String,
        quantity: Number,
        price: Number
    }],
    total: Number,
    status: { type: String, default: 'pending' },
    createdAt: { type: Date, default: Date.now }
});

const Order = mongoose.model('Order', orderSchema);

// Order Service Routes
app.get('/api/orders', async (req, res) => {
    try {
        const orders = await Order.find();
        res.json(orders);
    } catch (error) {
        res.status(500).json({ error: 'Failed to fetch orders' });
    }
});

app.post('/api/orders', async (req, res) => {
    try {
        const { userId, products } = req.body;
        
        // Verify user exists (inter-service communication)
        try {
            await axios.get(`http://localhost:3001/api/users/${userId}`);
        } catch (error) {
            return res.status(400).json({ error: 'User not found' });
        }
        
        const order = new Order({
            userId,
            products,
            total: products.reduce((sum, product) => sum + (product.price * product.quantity), 0)
        });
        
        await order.save();
        res.status(201).json(order);
    } catch (error) {
        res.status(400).json({ error: 'Failed to create order' });
    }
});

const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {
    console.log(`Order service running on port ${PORT}`);
});
Swipe to see more code

🎯 Practice Exercise

Test your understanding of this topic:

Additional Resources

📚 Recommended Reading

  • Microservices Patterns
  • API Gateway Design
  • Container Orchestration Guide

🌐 Online Resources

  • Microservices Architecture Tutorial
  • Docker Compose Documentation
  • Kubernetes Getting Started

Ready for the Next Module?

Continue your learning journey and master the next set of concepts.

Continue to Module 9