Production-ready microservices architecture for distributed inventory management with gRPC, PostgreSQL, Redis, and NATS.
.
βββ proto/ # Shared generated Go protobuf module
β βββ *.proto # Synced from service-local proto files
β βββ sync_service_protos.sh # Sync + regenerate helper
β βββ {catalog,order,...}/ # Generated .pb.go files
β
βββ services/
β βββ inventory/ # Inventory Microservice
β β βββ proto/ # inventory.proto + events.proto (source of truth)
β β βββ internal/
β β β βββ domain/ # Entities & interfaces
β β β βββ application/ # Business logic (usecases)
β β β βββ infra/ # Repository, Cache, Publisher
β β β βββ delivery/ # gRPC handlers
β β β βββ migrations/ # SQL migrations
β β βββ cmd/ # Service entrypoint
β β
β βββ catalog-service/ # Catalog Microservice
β β βββ proto/ # catalog.proto (source of truth)
β β βββ cmd/
β β
β βββ order-service/ # Order Microservice
β β βββ proto/ # order.proto (source of truth)
β β βββ cmd/
β β
β βββ notification-service/ # Notification Microservice
β β βββ proto/ # notification.proto (+ events.proto copy)
β β βββ cmd/
β β
β βββ auth-service/ # Authentication Service (HTTP)
β βββ cmd/
β
βββ api-gateway/ # REST β gRPC API Gateway
β βββ internal/app/
β β βββ server.go # REST handlers & routing
β βββ cmd/
β
βββ frontend/ # React UI
β βββ src/App.js
β
βββ docker-compose.yml # Service orchestration
βββ k8s/ # Kubernetes manifests for app + ingress + HPA
βββ monitoring/ # Prometheus, Grafana, Alertmanager configs
βββ terraform/ # IaC scaffold for cloud deployment
βββ loadtesting/ # Locust scenarios for SRE demos
βββ scripts/ # Demo helpers and traffic spikes
βββ demo/ # Presentation runbook
βββ .github/workflows/ # CI/CD pipeline
βββ Dockerfile # Multi-service build
βββ API_ENDPOINTS.md # Complete endpoint reference
Core stock management with ACID transactions, distributed locking, and real-time caching.
Endpoints:
- ReserveStock - Atomic reservation with FOR UPDATE lock
- ReleaseStock - Unreserve on order cancellation
- ConfirmStockDeduction - Permanent deduction after payment
- GetStockBySKU - Availability across warehouses
- ListStocksByWarehouse - Per-location breakdown
- AddStockReceipt - Supply chain intake
- TransferStock - Inter-warehouse movement
- UpdateSafetyStockLevel - Threshold configuration
- GetLowStockItems - Replenishment alerts
- CreateWarehouse - New location registration
- UpdateWarehouseInfo - Warehouse metadata
- ListWarehouses - All locations
Product information and pricing management.
Endpoints:
- CreateProduct
- GetProduct
- SearchProducts
- UpdatePrice
- BulkGetProducts
- DeleteProduct
- ListProducts
- UpsertProduct
- BatchUpdatePrice
- GetProductsByPriceRange
- AdjustPriceByPercent
- GetCatalogStats
Order lifecycle and cart calculations.
Endpoints:
- CreateOrder
- GetOrder
- CancelOrder
- UpdateStatus
- CalculateTotal
- BulkGetOrders
- ListOrdersByUser
- ListOrdersByStatus
- ConfirmOrder
- MarkOrderPaid
- ShipOrder
- GetOrderStats
Email and alert notifications via NATS events.
Endpoints:
- SendEmail
- SendOrderConfirmation
- SendStockAlert
JWT token issuance and user management.
Endpoints:
- POST /auth/register
- POST /auth/login
- GET /auth/me
REST β gRPC proxy with auth middleware, rate limiting, and metrics.
All service endpoints exposed as HTTP endpoints.
- warehouses - Warehouse locations
- product_stocks - Stock per SKU/warehouse with reservation tracking
- stock_reservations - Order-level reservations (PENDING/CONFIRMED/RELEASED)
- stock_movements - Audit trail of all stock changes
Indexes on SKU, available qty, and order_id for fast lookups.
- products - Product master data
- orders - Order records with status tracking
- users - Authentication records
Runtime: Go 1.25 Protocol: gRPC (proto3) Transport: HTTP/2 (gRPC), HTTP/1.1 (REST) Database: PostgreSQL 15 Cache: Redis 7 Queue: NATS 2.x Container: Docker & Docker Compose Orchestration: Kubernetes + HPA IaC: Terraform CI/CD: GitHub Actions Observability: Prometheus, Grafana, Alertmanager
flowchart LR
U[Users] --> F[Frontend]
U --> G[API Gateway]
F --> G
G --> A[Auth Service]
G --> O[Order Service]
G --> C[Catalog Service]
G --> I[Inventory Service]
O --> N[NATS]
I --> N
A --> P[(PostgreSQL)]
O --> P
C --> P
I --> P
I --> R[(Redis)]
G --> M[Metrics Listener]
M --> PR[Prometheus]
PR --> GF[Grafana]
PR --> AM[Alertmanager]
ACID Transactions - All stock deductions wrapped in DB transactions with SELECT FOR UPDATE Distributed Locking - Redis SetNX with TTL for concurrent reservation safety Caching - Real-time stock snapshots in Redis Event Driven - NATS pub/sub for order.created and inventory.stock.low Metrics - Prometheus counter/histogram for all gRPC and HTTP operations Circuit Ready - Separate health/readiness endpoints Clean Architecture - Domain β Usecase β Infra β Delivery layer separation
- Docker & Docker Compose
- Go 1.25 (local development)
- PostgreSQL 15, Redis 7, NATS (or use provided docker-compose)
-
Start services docker compose up -d --build
Or use the one-shot platform target:
make all
-
Register & Login
- Frontend: http://localhost:3000
- Username: demo, Password: pass
- Or use curl for auth service on http://localhost:8090
-
API Gateway available at http://localhost:8080 All endpoints require Authorization: Bearer <jwt_token>
-
View metrics http://localhost:9095/metrics
-
Run load testing
make locust
k8s/backend/backend.yamldeploys the API gateway and services.k8s/frontend/frontend.yamldeploys the web UI and nginx proxy.k8s/ingress/ingress.yamlexposes the app through a single ingress.k8s/autoscaling/hpa.yamlscales the main workloads on CPU/memory..github/workflows/ci-cd.ymlruns tests, builds images, pushes to GHCR, and deploys to the cluster.terraform/contains reusable infrastructure scaffolding and environment examples.- Root Terraform uses a local backend by default so
terraform initworks without S3 inputs.
-
Start infrastructure docker compose up -d postgres_inventory redis nats
-
Apply migrations cat services/inventory/migrations/002_schema.sql | psql -U postgres -d inventory_db
-
Build and run services go build ./services/inventory/cmd go build ./services/catalog-service/cmd go build ./services/order-service/cmd go build ./services/notification-service/cmd go build ./services/auth-service/cmd
Set env vars: export DATABASE_URL=postgres://postgres:pass@localhost:5432/inventory_db?sslmode=disable export REDIS_ADDR=localhost:6379 export NATS_URL=nats://localhost:4222 export JWT_SECRET=dev-jwt-secret
Services configured via environment variables:
Inventory Service:
- DATABASE_URL=postgres://... (required)
- REDIS_ADDR=host:port (default localhost:6379)
- NATS_URL=nats://host:port (default nats://localhost:4222)
- GRPC_ADDR=:50051 (default)
- METRICS_ADDR=:9090 (default)
Auth Service:
- JWT_SECRET=secret (required, default dev-jwt-secret)
- HTTP_ADDR=:8090 (default)
API Gateway:
- HTTP_ADDR=:8080 (default)
- INVENTORY_GRPC_ADDR=inventory-service:50051
- JWT_SECRET=secret (same as auth-service)
- RATE_LIMIT_PER_MINUTE=120 (default)
Frontend available at http://localhost:3000
Available test data created during initialization:
- Warehouses: A, B, C (New York, Los Angeles, Chicago)
- SKUs: SKU-001, SKU-002, SKU-003
Test Flows:
- Login with demo/pass
- View inventory (SKU lookup, low stock)
- Make reservations (with qty constraints)
- Manage warehouses (create, view)
- Transfer stock between locations
- Manage products and orders (when proxies are enabled)
See API_ENDPOINTS.md for complete endpoint documentation with request/response examples.
Prometheus scrapes the service metrics listeners:
api-gatewayviaMETRICS_ADDR=:9095inventory-serviceviaMETRICS_ADDR=:9090catalog-serviceviaHTTP_ADDR=:8081order-serviceviaHTTP_ADDR=:8082auth-serviceviaHTTP_ADDR=:8090notification-serviceviaMETRICS_ADDR=:8083
Key series:
api_gateway_http_requests_total- request counter by method/path/statusapi_gateway_http_request_duration_seconds- request latency histogramorder_http_requests_total/order_http_request_duration_secondscatalog_http_requests_total/catalog_http_request_duration_seconds- gRPC interceptors measure latency for inventory and notification calls
Local monitoring stack:
prometheusonhttp://localhost:9091grafanaonhttp://localhost:3001alertmanageronhttp://localhost:9093k8s/monitoring/mirrors the same stack for cluster deploymentmonitoring/grafana/dashboards/now has a dashboard per service with traffic, latency, error ratio, andΠΠΈΠ²Ρ Π»ΠΈ ΠΎΠ½ΠΈ
Logs - Structured JSON logs with correlation IDs from gateway
Health Checks:
- /healthz - Basic health (200 OK if running)
- /readyz - Readiness (checks dependencies)
docs/sre.md- SLIs, SLOs, error budgets, and the demo operating model.k8s/autoscaling/hpa.yaml- CPU/memory HPA manifests for the main services.loadtesting/locustfile.py- Locust scenarios for traffic and reservation flows.loadtesting/requirements.txt- Python dependency list for the load-test harness.scripts/traffic_spike.sh- staged spike script for autoscaling validation.demo/demo-script.md- presentation flow for dashboards, alerts, and rollout.
Quick start for the load test:
- Install dependencies:
pip install -r loadtesting/requirements.txt - Run the spike:
bash scripts/traffic_spike.sh - Watch metrics and HPA reactions in the dashboard / cluster view
- Database: Use managed PostgreSQL (AWS RDS, GCP Cloud SQL)
- Cache: Use managed Redis (AWS ElastiCache, GCP Memorystore)
- Queue: Use managed NATS (NATS Cloud) or deploy clustered NATS
- Auth: Integrate with Keycloak, Auth0, or proper OAuth2 provider
- TLS: Enable HTTPS on API Gateway and service-to-service gRPC
- Secrets: Use HashiCorp Vault or cloud secret manager
- Monitoring: Enable OpenTelemetry traces to Grafana/Jaeger
- Scaling: Use Kubernetes with HPA for autoscaling
Clean Architecture Pattern:
- domain/: Interfaces & entities (database agnostic)
- application/: Business logic & usecases (framework independent)
- infra/: Concrete implementations (DB, cache, queue)
- delivery/: Transport layer (gRPC, HTTP)
Redis Locks Pattern:
- SetNX with expiration for distributed mutual exclusion
- Prevents overselling in concurrent scenarios
NATS Subscriptions:
- order.created β triggers inventory.reserve
- inventory.stock.low β published on threshold breach
Testing:
- Unit tests in usecases (mock repository)
- Integration tests for postgres repository
- Note: All tests omitted for faster demo
- OpenTelemetry spans and traces
- User persistence in PostgreSQL (auth-service)
- Product variants and bulk pricing
- Multi-currency support
- Inventory aging and obsolescence tracking
- Supplier integration for auto-replenishment
- Machine learning for demand forecasting