Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Microservices Architecture Overview

Introduction to Microservices Architecture

A microservices architecture decomposes a system into independently deployable services, each handling a specific business function. This blueprint integrates an API Gateway for routing, authentication (OAuth2/JWT) and authorization (RBAC) for security, service discovery for dynamic communication, dedicated databases for isolation, caching for performance, and monitoring for observability. Security measures like mTLS and AES-256 encryption ensure robust protection, making the system scalable, resilient, and secure.

Microservices enable independent scaling and deployment, while robust security ensures safe client and inter-service interactions.

Architecture Diagram

The diagram below illustrates the microservices architecture, showcasing a Client authenticating with an Auth Server to obtain a JWT, which is validated by the API Gateway before routing to microservices (User, Order, Payment) with RBAC. Services leverage Service Discovery, access dedicated Databases and Cache, and are monitored via Prometheus. Security is enforced with mTLS. Arrows are color-coded: yellow (dashed) for client traffic, orange-red for authenticated routing, blue (dotted) for service discovery, and green (dashed) for data access.

graph TD A[Client] -->|Login Request| B[Auth Server] B -->|Issues JWT| A A -->|Client Traffic with JWT| C[API Gateway] C -->|Validates JWT| B C -->|Rate Limiting| C C -->|Routes| D[User Service] C -->|Routes| E[Order Service] C -->|Routes| F[Payment Service] D -->|mTLS| D E -->|mTLS| E F -->|mTLS| F C -->|Queries| G[Service Discovery] G -->|Locates| D G -->|Locates| E G -->|Locates| F D -->|Data Access| H[(User DB)] E -->|Data Access| I[(Order DB)] F -->|Data Access| J[(Payment DB)] D -->|Cache Access| K[(Cache)] E -->|Cache Access| K F -->|Cache Access| K C -->|Metrics| L[(Monitoring)] subgraph Authentication Layer B C end subgraph Microservices Layer D E F G H I J K end subgraph Monitoring Layer L end classDef gateway fill:#ff6f61,stroke:#ff6f61,stroke-width:2px,rx:10,ry:10; classDef service fill:#405de6,stroke:#405de6,stroke-width:2px,rx:5,ry:5; classDef db fill:#2ecc71,stroke:#2ecc71,stroke-width:2px; classDef utility fill:#fweb3b,stroke:#ffeb3b,stroke-width:2px; class C gateway; class D,E,F service; class H,I,J,K,L db; class G utility; linkStyle 0 stroke:#ff6f61,stroke-width:2.5px linkStyle 1 stroke:#ff6f61,stroke-width:2.5px linkStyle 2 stroke:#ffeb3b,stroke-width:2.5px,stroke-dasharray:6,6 linkStyle 3 stroke:#ff6f61,stroke-width:2.5px linkStyle 4 stroke:#ff6f61,stroke-width:2.5px linkStyle 5 stroke:#ff6f61,stroke-width:2.5px linkStyle 6 stroke:#ff6f61,stroke-width:2.5px linkStyle 7 stroke:#ff6f61,stroke-width:2.5px linkStyle 8 stroke:#ff6f61,stroke-width:2.5px linkStyle 9 stroke:#ff6f61,stroke-width:2.5px linkStyle 10 stroke:#ff6f61,stroke-width:2.5px linkStyle 11 stroke:#405de6,stroke-width:2.5px,stroke-dasharray:4,4 linkStyle 12 stroke:#405de6,stroke-width:2.5px,stroke-dasharray:4,4 linkStyle 13 stroke:#405de6,stroke-width:2.5px,stroke-dasharray:4,4 linkStyle 14 stroke:#2ecc71,stroke-width:2.5px,stroke-dasharray:5,5 linkStyle 15 stroke:#2ecc71,stroke-width:2.5px,stroke-dasharray:5,5 linkStyle 16 stroke:#2ecc71,stroke-width:2.5px,stroke-dasharray:5,5 linkStyle 17 stroke:#2ecc71,stroke-width:2.5px,stroke-dasharray:5,5 linkStyle 18 stroke:#2ecc71,stroke-width:2.5px,stroke-dasharray:5,5 linkStyle 19 stroke:#2ecc71,stroke-width:2.5px,stroke-dasharray:5,5 linkStyle 20 stroke:#ff6f61,stroke-width:2.5px
The API Gateway enforces JWT validation and rate limiting, while microservices use RBAC, mTLS, and dedicated databases for security and isolation.

Key Components

The core components of the microservices architecture include:

  • Auth Server: Issues OAuth2/JWT tokens for secure client authentication (e.g., Keycloak).
  • API Gateway: Centralizes routing, JWT validation, rate limiting, and monitoring (e.g., Kong).
  • Microservices: Independent services (User, Order, Payment) with RBAC for authorization.
  • Service Discovery: Dynamically locates service instances using Consul.
  • Dedicated Databases: MongoDB for users, PostgreSQL for orders, DynamoDB for payments, ensuring data isolation.
  • Cache Layer: Redis for low-latency access to frequently queried data.
  • Monitoring: Prometheus and Grafana for system and security observability.
  • Security: mTLS for inter-service communication and AES-256 encryption for data at rest and in transit.

Benefits of the Architecture

  • Security: OAuth2/JWT, RBAC, mTLS, and encryption ensure robust protection against threats.
  • Scalability: Independent microservices and databases scale based on demand.
  • Resilience: Service discovery and circuit breakers enhance fault tolerance.
  • Performance: Caching and optimized routing reduce latency.
  • Observability: Centralized monitoring provides insights into performance and security events.
  • Maintainability: Modular services enable independent development and deployment.

Implementation Considerations

Building a secure microservices architecture requires strategic planning:

  • Authentication Setup: Deploy Keycloak for OAuth2/JWT token management with short-lived tokens.
  • Authorization Design: Implement RBAC in microservices, mapping roles to endpoints.
  • Security Hardening: Use mTLS for inter-service communication and encrypt data with AES-256.
  • Gateway Configuration: Configure Kong with plugins for JWT validation, rate limiting, and metrics.
  • Service Discovery: Use Consul with health checks and mTLS for secure service location.
  • Database Isolation: Assign dedicated databases per service (MongoDB, PostgreSQL, DynamoDB) with encrypted connections.
  • Cache Strategy: Use Redis with TTLs and event-driven invalidation for dynamic data.
  • Monitoring: Deploy Prometheus, Grafana, and ELK Stack to monitor metrics, logs, and security events.
Regularly audit security policies, test mTLS configurations, and monitor cache hit rates to ensure a secure and performant system.

Example Configuration: Kong API Gateway with JWT and mTLS

Below is an example configuration for a Kong API Gateway to validate JWT tokens, enforce rate limiting, and enable mTLS:

# Define a service in Kong
curl -i -X POST http://kong:8001/services \
  --data name=order-service \
  --data url=https://order-service:3000

# Define a route for the service
curl -i -X POST http://kong:8001/services/order-service/routes \
  --data 'paths[]=/orders' \
  --data methods[]=GET \
  --data methods[]=POST

# Enable JWT plugin
curl -i -X POST http://kong:8001/services/order-service/plugins \
  --data name=jwt

# Enable rate-limiting plugin
curl -i -X POST http://kong:8001/services/order-service/plugins \
  --data name=rate-limiting \
  --data config.second=5 \
  --data config.hour=1000 \
  --data config.policy=redis \
  --data config.redis_host=redis-host

# Enable mTLS plugin
curl -i -X POST http://kong:8001/plugins \
  --data name=mtls-auth \
  --data config.ca_certificates=ca-cert-id

# Enable Prometheus plugin
curl -i -X POST http://kong:8001/plugins \
  --data name=prometheus
                

Example Configuration: Microservice with RBAC and mTLS

Below is an example Node.js configuration for an Order Service implementing RBAC and mTLS:

const express = require('express');
const jwt = require('jsonwebtoken');
const https = require('https');
const fs = require('fs');

const app = express();
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// mTLS configuration
const serverOptions = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),
  ca: fs.readFileSync('ca-cert.pem'),
  requestCert: true,
  rejectUnauthorized: true
};

const checkRBAC = (requiredRole) => (req, res, next) => {
    const authHeader = req.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return res.status(401).json({ error: 'Unauthorized' });
    }

    const token = authHeader.split(' ')[1];
    try {
        const decoded = jwt.verify(token, JWT_SECRET);
        if (!decoded.role || decoded.role !== requiredRole) {
            return res.status(403).json({ error: 'Insufficient permissions' });
        }
        req.user = decoded;
        next();
    } catch (err) {
        return res.status(403).json({ error: 'Invalid token' });
    }
};

// Route restricted to admin role
app.get('/orders', checkRBAC('admin'), async (req, res) => {
    const orders = await db.query('SELECT * FROM orders');
    res.json(orders);
});

https.createServer(serverOptions, app).listen(3000, () => {
    console.log('Order Service running on port 3000 with mTLS');
});