Skip to main content

Microservices Reference

Related docs: SDLC/DESIGN · Hosting Infrastructure · API Design


1. Service Registry

Pakashop comprises 19 microservices, each with a dedicated responsibility, language, and port. All services are hosted on AWS EC2 (Ubuntu 22.04 LTS) and managed by systemd.

#ServiceLanguagePortPurposeHealth Endpoint
1pakashop-gatewayNode.js8000API gateway — routing, dual-key security, rate limiting, WebSocket upgradesGET /health
2pakashop-backendNode.js3080Core business logic — auth, orders, products, shops, payments, usersGET /health
3pakashop-configNode.js3085Centralised feature flags & runtime configuration (Redis-cached)GET /health
4pakashop-notificationsNode.js3090Email (Resend/SMTP), in-app notifications, SSE real-time streamGET /health
5pakashop-trackingNode.js3120Real-time delivery tracking — WebSocket server, Redis Pub/Sub, GPS ingestionGET /health
6pakashop-moderationPython3110Sightengine AI content moderation pipeline for uploaded imagesGET /health
7pakashop-recommendationsPython3100Collaborative filtering engine (Jaccard + k-NN) on RedisGET /health
8pakashop-schedulerNode.js3004Background job infrastructure (BullMQ) — periodic cleanup, retriesGET /health
9pakashop-searchGo3005Full-text product search via Meilisearch — typo-tolerant, facetedGET /health
10pakashop-fraudNode.js3006Rules-based fraud detection — velocity checks, anomalies, self-dealingGET /health
11pakashop-analyticsGo3007Business intelligence — vendor/admin dashboards, hourly/daily/weekly aggregationGET /health
12pakashop-couponNode.js3008Promotions & discount engine — creation, validation, redemptionGET /health
13pakashop-loyaltyNode.js3010Points-based loyalty & rewards — earn, redeem, expireGET /health
14pakashop-whatsappNode.js3009WhatsApp Business Cloud API — order alerts, delivery PINs, cart recoveryGET /health
15pakashop-reportsNode.js3011PDF/CSV/Excel report generationGET /health
16pakashop-reconciliationNode.js3012Automated financial reconciliation — internal vs provider settlementsGET /health
17pakashop-invoicingNode.js3013ZRA Smart Invoice VSDC integration — configurable on/off, mock modeGET /health
18pakashop-pricingNode.js3014Dynamic pricing engine — commissions, discounts, markupsGET /health
19pakashop-settlementNode.js3016Automated batch vendor & agent payoutsGET /health

2. Communication Patterns

2.1 External Traffic Flow

Client (Browser/App)


Cloudflare (DNS/WAF/CDN)


Nginx (TLS termination, port 443)


pakashop-gateway (port 8000)

├──► pakashop-backend (port 3080) — /api/v1/auth, /api/v1/orders, etc.
├──► pakashop-search (port 3005) — /api/v1/search
├──► pakashop-tracking (port 3120) — /api/v1/tracking (WebSocket upgrade)
├──► pakashop-notifications (port 3090) — /api/v1/notifications (SSE)
└──► ... other services

2.2 Inter-Service Communication

All service-to-service calls go through the gateway with the x-internal-key header:

// Example: backend calling search service
const response = await fetch('http://localhost:8000/api/v1/search/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-internal-key': process.env.INTERNAL_API_KEY
},
body: JSON.stringify({ query: 'phone', filters: { category: 'electronics' } })
});

2.3 Redis Pub/Sub

Used for real-time event broadcasting (primarily tracking):

pakashop-tracking
│ PUBLISH order:{orderId}:location

Redis Pub/Sub

├──► WebSocket clients (buyer browser)
├──► WebSocket clients (vendor dashboard)
└──► WebSocket clients (admin panel)

2.4 BullMQ Job Queues

Used for asynchronous background processing:

QueueProducerConsumerPurpose
emailbackend, notificationsnotificationsSend transactional emails
moderationbackendmoderationProcess image moderation
reportsbackend, adminreportsGenerate PDF/CSV/Excel reports
settlementbackend, schedulersettlementBatch vendor payouts
reconciliationschedulerreconciliationDaily settlement reconciliation
zra-invoicebackendinvoicingTransmit Smart Invoices to ZRA
whatsappbackendwhatsappSend WhatsApp messages
inventory-alertsbackend, schedulerbackendLow-stock notifications

3. Internal API Key Usage

3.1 Dual-Key Security Model

Key TypeHeaderPurposeScope
External client keyx-pakashop-keyIdentifies external clientsFrontend, mobile apps, third-party integrations
Internal service keyx-internal-keyAuthenticates inter-service requestsAll microservices

3.2 Gateway Routing Logic

// services/gateway/src/middleware/routing.js
const serviceMap = {
'/api/v1/auth': 'http://localhost:3080',
'/api/v1/orders': 'http://localhost:3080',
'/api/v1/payments': 'http://localhost:3080',
'/api/v1/products': 'http://localhost:3080',
'/api/v1/search': 'http://localhost:3005',
'/api/v1/tracking': 'http://localhost:3120',
'/api/v1/notifications': 'http://localhost:3090',
'/api/v1/analytics': 'http://localhost:3007',
'/api/v1/coupons': 'http://localhost:3008',
'/api/v1/loyalty': 'http://localhost:3010',
'/api/v1/reports': 'http://localhost:3011',
'/api/v1/fraud': 'http://localhost:3006',
'/internal': 'http://localhost:3080', // Internal-only routes
};

3.3 Internal-Only Endpoints

Endpoints under /internal/* are never exposed through the external gateway. They are used for:

  • Service health checks
  • BullMQ job processing
  • Database migration triggers
  • Cache invalidation

4. Service Dependencies

4.1 Startup Order

Services must start in the following order to avoid dependency failures:

Phase 1: Infrastructure
├── PostgreSQL
├── Redis
└── Meilisearch

Phase 2: Core Services
├── pakashop-config (feature flags needed by all)
├── pakashop-gateway (depends on config)
└── pakashop-backend (depends on config, PostgreSQL, Redis)

Phase 3: Supporting Services (no strict order within phase)
├── pakashop-search (depends on Meilisearch)
├── pakashop-analytics (depends on PostgreSQL)
├── pakashop-notifications (depends on Redis for SSE)
├── pakashop-tracking (depends on Redis for Pub/Sub)
├── pakashop-moderation (depends on Sightengine API)
├── pakashop-recommendations (depends on Redis)
├── pakashop-scheduler (depends on Redis for BullMQ)
├── pakashop-fraud (depends on PostgreSQL, Redis)
├── pakashop-coupon (depends on PostgreSQL, Redis)
├── pakashop-loyalty (depends on PostgreSQL, Redis)
├── pakashop-whatsapp (depends on Redis for BullMQ)
├── pakashop-reports (depends on PostgreSQL, Redis)
├── pakashop-reconciliation (depends on PostgreSQL)
├── pakashop-invoicing (depends on PostgreSQL)
├── pakashop-pricing (depends on PostgreSQL, Redis)
└── pakashop-settlement (depends on PostgreSQL, Redis)

4.2 Dependency Graph


5. Service-Specific Details

5.1 pakashop-gateway (Port 8000)

  • Language: Node.js
  • Framework: Express with http-proxy-middleware
  • Key Responsibilities:
    • Validate x-pakashop-key or x-internal-key
    • Apply rate limiting (Redis-backed)
    • Route requests to upstream services
    • Handle WebSocket upgrades for tracking
    • TLS termination (delegated to Nginx)
  • Health Check: GET /health{"status":"ok","service":"gateway"}

5.2 pakashop-backend (Port 3080)

  • Language: Node.js
  • Framework: Express + Prisma ORM
  • Key Responsibilities:
    • Authentication (JWT + MFA)
    • Order management
    • Product/shop CRUD
    • Payment orchestration (PawaPay + Flutterwave)
    • User management
    • Inventory management
    • Seller application workflow
  • Health Check: GET /health{"status":"ok","service":"backend"}

5.3 pakashop-search (Port 3005)

  • Language: Go
  • Framework: Standard library + meilisearch-go
  • Key Responsibilities:
    • Index product catalog in Meilisearch
    • Handle search queries (typo-tolerant, faceted)
    • Sync index on product create/update/delete
  • Health Check: GET /health{"status":"ok","service":"search"}

5.4 pakashop-tracking (Port 3120)

  • Language: Node.js
  • Framework: Express + ws (WebSocket library)
  • Key Responsibilities:
    • Ingest GPS location updates from agent devices
    • Apply Kalman filter for GPS smoothing
    • Calculate ETA using Haversine formula
    • Geofence detection (400m radius)
    • Redis Pub/Sub for real-time location broadcast
    • WebSocket server for live tracking UI
  • Health Check: GET /health{"status":"ok","service":"tracking","websocket":{"connectedClients":N}}

5.5 pakashop-moderation (Port 3110)

  • Language: Python
  • Framework: FastAPI + httpx
  • Key Responsibilities:
    • Receive image URLs from backend
    • Call Sightengine API (nudity, violence, offensive detection)
    • Apply retry logic (3 attempts, exponential backoff)
    • Return moderation results to backend
  • Health Check: GET /health{"status":"ok","service":"moderation"}

5.6 pakashop-fraud (Port 3006)

  • Language: Node.js
  • Framework: Express
  • Key Responsibilities:
    • Real-time transaction evaluation
    • Velocity checks (payments per IP/hour)
    • Amount anomaly detection
    • Self-dealing detection (buyer = seller)
    • Risk scoring (0-100 composite score)
    • Admin review queue management
  • Health Check: GET /health{"status":"ok","service":"fraud"}

5.7 pakashop-invoicing (Port 3013)

  • Language: Node.js
  • Framework: Express
  • Key Responsibilities:
    • Generate ZRA Smart Invoice payloads
    • Transmit to ZRA VSDC API
    • Mock mode for testing
    • Retry logic (3 attempts, exponential backoff)
    • Per-vendor TPIN validation
  • Health Check: GET /health{"status":"ok","service":"invoicing"}

6. Scaling Considerations

ServiceScaling StrategyNotes
pakashop-gatewayHorizontal (load balancer)Stateless; sticky sessions for WebSocket
pakashop-backendHorizontal (load balancer)Stateless; session data in Redis
pakashop-searchVertical (Meilisearch scales vertically)Consider Meilisearch Cloud for large catalogs
pakashop-trackingHorizontal (sticky sessions)Kalman filter state per-order per-process
pakashop-moderationHorizontalStateless; Sightengine API is the bottleneck
pakashop-reportsVerticalPDF generation is CPU-intensive
All othersHorizontalStateless with Redis/PostgreSQL

For internal use only. Do not distribute outside Pakashop engineering.