Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

High-Level System Diagram

Introduction to the System Architecture

This microservices architecture orchestrates independent services to deliver scalable and secure functionality to clients like web and mobile applications. The API Gateway routes requests to services (Auth, Payment, Orders), which implement RBAC for authorization and manage dedicated databases. An Auth Server issues OAuth2/JWT tokens for authentication, validated at the gateway. Security is enhanced with mTLS for inter-service communication and AES-256 encryption. Services use Service Discovery for dynamic routing, Redis for caching, and integrate with Third-Party APIs for external functionality. Prometheus ensures observability, making the system modular, resilient, and secure.

The API Gateway centralizes routing and security, while services maintain isolation with dedicated databases and secure communication.

High-Level System Diagram

The diagram visualizes Web and Mobile clients authenticating via an Auth Server to obtain JWTs, which the API Gateway validates before routing to microservices (Auth, Payment, Orders) with RBAC. Services access dedicated Databases, use Service Discovery (Consul), Cache (Redis), and integrate with Third-Party APIs. Prometheus monitors metrics. Arrows are color-coded: yellow (dashed) for client flows, orange-red for authenticated service flows, blue (dotted) for third-party/service discovery flows, green (dashed) for data/cache flows, and purple for monitoring.

graph TD A[Web Client] -->|HTTP Request| B[API Gateway] C[Mobile Client] -->|HTTP Request| B A -->|Login| D[Auth Server] C -->|Login| D D -->|Issues JWT| A D -->|Issues JWT| C B -->|Validates JWT| D B -->|Rate Limiting| B B -->|Routes| E[Auth Service] B -->|Routes| F[Payment Service] B -->|Routes| G[Orders Service] E -->|mTLS| E F -->|mTLS| F G -->|mTLS| G B -->|Queries| H[Service Discovery] H -->|Locates| E H -->|Locates| F H -->|Locates| G E -->|Access| I[(Auth DB)] F -->|Access| J[(Payment DB)] G -->|Access| K[(Orders DB)] E -->|Cache| L[(Cache)] F -->|Cache| L G -->|Cache| L F -->|Calls| M[Third-Party Payment API] E -->|Calls| N[Third-Party Auth API] B -->|Metrics| O[(Monitoring)] subgraph Clients A C end subgraph Authentication D B end subgraph Microservices E F G H I J K L end subgraph Third-Party M N end subgraph Monitoring O 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:#ffeb3b,stroke:#ffeb3b,stroke-width:2px; classDef monitoring fill:#9b59b6,stroke:#9b59b6,stroke-width:2px; class B gateway; class E,F,G service; class I,J,K,L db; class H,D utility; class O monitoring; linkStyle 0,1 stroke:#ffeb3b,stroke-width:2.5px,stroke-dasharray:6,6 linkStyle 2,3,4,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,9,10 stroke:#ff6f61,stroke-width:2.5px linkStyle 11,12,13 stroke:#ff6f61,stroke-width:2.5px linkStyle 14 stroke:#405de6,stroke-width:2.5px,stroke-dasharray:4,4 linkStyle 15,16,17 stroke:#405de6,stroke-width:2.5px,stroke-dasharray:4,4 linkStyle 18,19,20 stroke:#2ecc71,stroke-width:2.5px,stroke-dasharray:5,5 linkStyle 21,22 stroke:#2ecc71,stroke-width:2.5px,stroke-dasharray:5,5 linkStyle 23,24 stroke:#405de6,stroke-width:2.5px,stroke-dasharray:2,2 linkStyle 25 stroke:#9b59b6,stroke-width:2.5px
The API Gateway ensures secure routing with JWT validation, while services integrate with third-party APIs and use mTLS for secure communication.

Key Components

The core components of the enhanced microservices architecture include:

  • Clients (Web, Mobile): User interfaces sending HTTP requests to the API Gateway.
  • Auth Server: Issues OAuth2/JWT tokens for secure authentication (e.g., Keycloak).
  • API Gateway: Routes requests, validates JWTs, and enforces rate limiting (e.g., Kong).
  • Microservices (Auth, Payment, Orders): Independent services with RBAC for authorization.
  • Service Discovery: Dynamically locates services using Consul.
  • Databases: Dedicated MongoDB (Auth), DynamoDB (Payment), PostgreSQL (Orders) with encryption.
  • Cache: Redis for low-latency data access.
  • Third-Party APIs: External services for payment processing and authentication.
  • Monitoring: Prometheus and Grafana for observability.
  • Security: mTLS for inter-service communication, AES-256 encryption for data.

Benefits of the Architecture

  • Security: JWT, RBAC, mTLS, and encryption ensure robust protection.
  • Scalability: Independent services and databases scale based on demand.
  • Resilience: Service discovery and isolated databases reduce failure impact.
  • Performance: Caching and optimized routing minimize latency.
  • Flexibility: Third-party API integration enables rapid feature adoption.
  • Observability: Monitoring provides insights into system health and security.

Implementation Considerations

Building a secure microservices architecture requires strategic planning:

  • Authentication Setup: Deploy Keycloak for OAuth2/JWT with short-lived tokens.
  • Authorization Design: Implement RBAC in services, mapping roles to endpoints.
  • Security Hardening: Use mTLS and encrypt data with AES-256.
  • API Gateway Configuration: Enable JWT validation, rate limiting, and metrics in Kong.
  • Service Discovery: Use Consul with health checks and mTLS.
  • Database Isolation: Choose MongoDB, DynamoDB, PostgreSQL with encrypted connections.
  • Cache Strategy: Implement Redis with TTLs and event-driven invalidation.
  • Third-Party Integration: Use retries and circuit breakers for external API reliability.
  • Monitoring: Deploy Prometheus and Grafana for metrics and ELK for logs.
Regular security audits, mTLS testing, and cache optimization are critical for a robust system.

Example Configuration: Kong API Gateway with JWT and mTLS

Below is a Kong configuration for JWT validation, rate limiting, and mTLS:

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

# Define a route
curl -i -X POST http://kong:8001/services/payment-service/routes \
  --data 'paths[]=/payments' \
  --data methods[]=POST

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

# Enable rate-limiting plugin
curl -i -X POST http://kong:8001/services/payment-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: Payment Service with RBAC and mTLS

Below is a Node.js Payment Service with 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' });
    }
};

// Endpoint restricted to payment role
app.post('/payments', checkRBAC('payment'), async (req, res) => {
    const payment = await db.save('payments', req.body);
    res.json(payment);
});

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