1. Frontend Gateway‐ MongoDB Edition‐ **Step‐by‐step process** - Wiz-DevTech/prettygirllz GitHub Wiki

Here’s a step-by-step implementation guide for setting up the Frontend Gateway module with MongoDB caching and Maven (Java), designed for clarity and testability:


Frontend Gateway Implementation Guide

Architecture: Stateless Composite UI with MongoDB caching
Prerequisites: Java 11+, Maven, Node.js 16+, Docker


Step 1: Set Up MongoDB for Caching

1.1 Start MongoDB Container

docker run -d -p 27017:27017 --name mongo \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=pass \
  mongo:latest

1.2 Initialize Collections

docker exec -it mongo mongosh --username admin --password pass --eval "
  db.createCollection('ssr_cache');
  db.createCollection('api_responses');
  db.api_responses.createIndex({ expiry: 1 }, { expireAfterSeconds: 0 });  # TTL index
"

Step 2: Build the API Composition Layer (Java/Maven)

2.1 Configure Maven

Edit acl-module/pom.xml:

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
  </dependency>
</dependencies>

2.2 Implement Caching

// acl-module/src/main/java/com/yourpackage/CachedResponse.java
@Document(collection = "api_responses")
public class CachedResponse {
  @Id private String id;
  private String apiKey;
  private String responseJson;
  @Indexed private Instant expiry;  // Auto-expires via TTL
}

2.3 Run the ACL Service

mvn spring-boot:run -pl acl-module
# Verify: http://localhost:8081/actuator/health

Step 3: Set Up SSR Templates (Java/Maven)

3.1 Configure Fallback Cache

Edit ssr-module/src/main/resources/application.yml:

spring:
  data:
    mongodb:
      uri: mongodb://admin:pass@localhost:27017/ssr_cache

3.2 Test SSR Fallback

# Insert a test template
docker exec -it mongo mongosh --username admin --password pass --eval "
  db.ssr_cache.insertOne({
    route: '/product',
    html: '<div>Fallback: Product Details</div>',
    expiry: new Date()
  })"

# Trigger fallback (mock Catalog Service down)
curl -H "Accept: text/html" http://localhost:8080/product?simulate_error=500

Step 4: Configure Client Adaptors (Node.js)

4.1 Connect to MongoDB

Edit client-adaptors/services/db.js:

const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://admin:pass@localhost:27017/client_profiles');

async function getMobileProfile() {
  await client.connect();
  return client.db().collection('profiles').findOne({ type: 'mobile' });
}

4.2 Start Adaptors

cd client-adaptors
npm install
npm start  # Runs on http://localhost:3000

Step 5: Test the Full Flow

5.1 Simulate Microservices

# Mock Catalog Service (returns product data)
docker run -d -p 8082:8080 -e MOCK_ENDPOINTS='{"/products/123": {"name": "Test Product"}}' mock-server:latest

# Mock Social Service (returns reviews)
docker run -d -p 8083:8080 -e MOCK_ENDPOINTS='{"/reviews/123": [{"rating": 5}]}' mock-server:latest

5.2 Verify Composition

curl "http://localhost:8080/api/composite?productId=123"

Expected Output:

{
  "product": {"name": "Test Product"},
  "reviews": [{"rating": 5}],
  "source": "cache"  // After first call, subsequent hits show this
}

Step 6: Monitor Performance

6.1 Start Prometheus/Grafana

docker-compose -f monitoring/docker-compose.yml up -d
  • Grafana: http://localhost:3000 (admin/admin)
  • Import dashboard ID 2583 for MongoDB metrics.

6.2 Key Metrics to Track

Metric Healthy Threshold Command to Verify
mongodb_cache_hit_ratio >90% curl http://localhost:8081/metrics
http_request_duration_seconds <500ms (p99) Check Grafana dashboard

Step 7: Deploy to Production

7.1 Build Docker Images

# Build ACL Module
mvn spring-boot:build-image -Dspring-boot.build-image.imageName=your-repo/acl-module

# Build Client Adaptors
docker build -t your-repo/client-adaptors ./client-adaptors

7.2 Kubernetes Example

# acl-module-deployment.yaml
apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
        - name: acl
          image: your-repo/acl-module
          env:
            - name: SPRING_DATA_MONGODB_URI
              value: "mongodb://admin:pass@mongo:27017/gateway_cache"

Validation Checklist

  1. Statelessness:
    • Restart the Gateway → API calls should still work (microservices own data).
  2. Cache Isolation:
    • docker stop mongo → Gateway falls back to direct microservice calls.
  3. No Business Logic:
    • Gateway only combines responses (e.g., no product price calculations).

Troubleshooting

Issue Debug Command Solution
MongoDB connection refused docker logs mongo Check credentials in application.yml
ACL not caching curl -v http://localhost:8081/cache/status Verify TTL index
Client Adaptor 404s node inspect client-adaptors/server.js Check User-Agent parsing

Final Architecture

graph TD
  FG[Frontend Gateway] -->|Caches| MongoDB[(MongoDB)]
  FG -->|Aggregates| Catalog[[Catalog Service]]
  FG -->|Aggregates| Social[[Social Service]]
  Catalog -->|Owns| Elasticsearch
  Social -->|Owns| WebSockets

  classDef cache fill:#d0f0c0,stroke:#333
  class MongoDB cache
Loading

Key Compliance:
No shared databases between microservices
Gateway remains stateless (MongoDB for caching only)
Tech isolation (Java for SSR/ACL, Node.js for Client Adaptors)


This guide ensures your Frontend Gateway adheres to the Composite UI pattern while leveraging MongoDB for performance. For advanced scenarios (A/B testing, blue-green deployments), refer to the Extended Deployment Guide.

⚠️ **GitHub.com Fallback** ⚠️