Skip to content

About

A Go-based e-commerce microservices platform featuring gRPC communication, event-driven messaging with NATS, independent PostgreSQL databases, Redis caching, transactional checkout with compensating actions, and distributed observability using Prometheus, OpenTelemetry, Jaeger, and Grafana. Containerized with Docker.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

E-Commerce Microservices Platform

A microservice-based e-commerce backend written in Go, developed as the final project for the Advanced Programming 2 course. Four domain services talk gRPC, publish domain events over NATS and keep their own PostgreSQL databases. An HTTP gateway exposes a REST/JSON API to a browser client. The stack is instrumented with Prometheus metrics, OpenTelemetry tracing and a provisioned Grafana dashboard.


Table of Contents

  1. Features
  2. Architecture
  3. Technology Stack
  4. Getting Started
  5. Configuration
  6. REST API Reference
  7. gRPC Services
  8. Domain Events
  9. Observability
  10. Testing
  11. Project Structure
  12. Development Workflow
  13. Design Decisions
  14. Course Requirements Coverage

Features

  • Accounts: registration, login with JWT (HS256), profile updates, password changes, address book, self-service account deletion.
  • Roles: customer and admin. The gateway re-checks the admin role with the user service on every admin request, so a demoted or deleted account loses access straight away. A bootstrap administrator is created on first start.
  • Catalog: categories and products with pagination, category filtering, full-text-style search (escaped LIKE), stock adjustment and Redis read-through caching.
  • Cart and checkout: stock is checked when items are added. Checkout reserves stock for each line and writes the order in one database transaction. If any step fails, stock already reserved is released again (saga-style compensation). Prices are always taken from the catalog, never from the client.
  • Order lifecycle: CONFIRMED → SHIPPED → DELIVERED, or CONFIRMED → CANCELLED. Transitions are checked in the domain layer and applied with compare-and-set updates. Cancelled orders return their items to stock.
  • Notifications: an orders.placed event triggers an order-confirmation e-mail. Each message is stored with its delivery status, and users can list their notifications, mark them as read and delete them.
  • Web client: a dependency-free single-page application served by nginx, which also reverse-proxies /api to the gateway (same origin, strict Content-Security-Policy).
  • Observability: per-service Prometheus metrics, distributed traces exported to Jaeger over OTLP, and a Grafana dashboard provisioned on startup.

Architecture

                 ┌──────────────────────┐
  Browser ──────▶│  web (nginx)  :8081  │  static SPA + /api reverse proxy
                 └──────────┬───────────┘
                            │ HTTP/JSON
                 ┌──────────▼───────────┐
                 │   gateway    :8080   │  JWT auth, RBAC, REST → gRPC
                 └──┬───────┬───────┬───┴──────────┐
              gRPC  │       │       │              │
        ┌───────────▼┐ ┌────▼──────┐ ┌▼───────────┐ ┌▼──────────────────┐
        │user-service│ │catalog-svc│ │order-svc   │ │notification-svc   │
        │   :50051   │ │  :50052   │ │  :50053    │ │     :50054        │
        └──┬──────┬──┘ └─┬──────┬──┘ └─┬───────┬──┘ └──┬──────────┬─────┘
           │      │      │      │      │ gRPC  │       │ gRPC     │
           │      │      │      │      └──▶ catalog    └──▶ user  │ SMTP
        userdb  Redis catalogdb Redis  orderdb │     notificationdb ▼
                                               │                MailHog
                         NATS  orders.placed ◀─┘──▶ catalog (cache invalidation)
                                                └─▶ notification (confirmation e-mail)

Each service follows a clean-architecture layout:

Layer Package Responsibility
Domain internal/<svc>/domain Entities, domain errors, business rules (for example CanTransition)
Use case internal/<svc>/usecase Application logic. Depends only on port interfaces it declares itself (Repository, Cache, Catalog, Publisher, …)
Adapters internal/<svc>/adapter/* PostgreSQL repositories, Redis caches, gRPC servers, NATS subscribers
Composition cmd/<svc>/main.go Configuration, wiring, graceful shutdown

Shared infrastructure lives in internal/platform (config, embedded migrations, DB connection with retry, gRPC server bootstrap with health and reflection, NATS connection, SMTP mailer, telemetry).

Technology Stack

Concern Technology
Language Go 1.26
RPC gRPC, Protocol Buffers (generated with buf)
HTTP net/http with method-based routing
Persistence PostgreSQL 16 via pgx/v5, one database per service, embedded SQL migrations
Cache Redis 7
Messaging NATS 2.10 (queue groups)
Auth golang-jwt/jwt/v5, bcrypt
E-mail SMTP (STARTTLS when offered), MailHog for development
Observability Prometheus, Grafana, OpenTelemetry, Jaeger
Web Vanilla JavaScript, nginx (unprivileged)
Packaging Docker multi-stage builds on distroless, Docker Compose
CI GitHub Actions

Getting Started

Prerequisites

  • Docker with Docker Compose v2
  • Go 1.26+ (only for local development and tests)
  • make (optional)

Run the full stack

cp .env.example .env      # optional: override secrets and ports
docker compose up --build -d
Component URL
Web client http://localhost:8081
REST API (gateway) http://localhost:8080/api/v1
MailHog (captured e-mail) http://localhost:8025
Grafana http://localhost:3000 (admin / admin)
Prometheus http://localhost:9091
Jaeger http://localhost:16686

All ports are bound to 127.0.0.1. If a port is already taken, change POSTGRES_PORT, GATEWAY_PORT or WEB_PORT in .env.

On first start the user service creates an administrator from ADMIN_EMAIL / ADMIN_PASSWORD (development defaults: admin@example.com / admin12345). Change these, and JWT_SECRET, before running the stack anywhere other than your own machine.

Each service applies its own migrations at startup. The catalog migrations include sample categories and products.

Stop the stack with docker compose down, or with docker compose down -v to also delete the data volumes.

Configuration

All services are configured through environment variables. The Compose file sets sensible values; the table lists what each binary reads.

Variable Used by Default Description
GRPC_ADDR domain services :5005x gRPC listen address
HTTP_ADDR gateway :8080 HTTP listen address
METRICS_ADDR all :9090 Address for /metrics and /healthz
DATABASE_URL domain services local DSN PostgreSQL connection string
REDIS_ADDR user, catalog localhost:6379 Redis address
NATS_URL catalog, order, notification nats://localhost:4222 NATS server
USER_GRPC, CATALOG_GRPC, ORDER_GRPC, NOTIFICATION_GRPC gateway, order, notification localhost:5005x Downstream service addresses
JWT_SECRET gateway insecure dev value (warns) HS256 signing key; must be at least 32 characters when set
CORS_ORIGINS gateway * Comma-separated allowed origins
ADMIN_EMAIL, ADMIN_PASSWORD user — Bootstrap administrator (created only if no admin exists)
SMTP_HOST, SMTP_PORT, SMTP_FROM, SMTP_USER, SMTP_PASS user, notification MailHog Outgoing mail. Authentication is used only when credentials are set
OTEL_EXPORTER_OTLP_ENDPOINT all localhost:4317 OTLP/gRPC trace collector, or disabled

For a real mail provider (for example Gmail with an app password, or Microsoft 365), set SMTP_HOST, SMTP_PORT=587, SMTP_USER and SMTP_PASS. The mailer upgrades the connection with STARTTLS before it authenticates.

REST API Reference

Base path: /api/v1. Request and response bodies are JSON with snake_case fields. Errors always have the form {"error": "message"}. 🔒 means a bearer token is required (Authorization: Bearer <access_token>); 🛡 means the admin role is required.

Method Path Auth Description
POST /auth/register Create a customer account (email, password ≥ 8 chars, full_name)
POST /auth/login Returns access_token, expires_in and user (including role)
GET / PUT / DELETE /me 🔒 Read, update (full_name) or delete the current account
PUT /me/password 🔒 Change password (old_password, new_password)
GET / POST /addresses 🔒 List or add addresses (line1, city, country)
GET / PUT / DELETE /addresses/{id} 🔒 Manage one address
GET /categories, /categories/{id} Browse categories
POST / PUT / DELETE /categories[/{id}] 🛡 Manage categories
GET /products?category_id=&limit=&offset= Paginated product list (limit 1–100)
GET /products/search?q=&limit= Search by name or description
GET /products/{id} Product details
POST / PUT / DELETE /products[/{id}] 🛡 Manage products
POST /products/{id}/stock 🛡 Adjust stock by delta
GET / DELETE /cart 🔒 Show or empty the cart
POST /cart/items 🔒 Add product_id × quantity (1–99, limited by stock)
PUT / DELETE /cart/items/{id} 🔒 Change quantity or remove a line
POST /checkout 🔒 Place an order from the cart
GET /orders, /orders/{id}, /orders/{id}/items 🔒 Own orders
POST /orders/{id}/cancel 🔒 Cancel a CONFIRMED order and restock its items
GET /notifications, /notifications/stats 🔒 Own notifications and counters
POST /notifications/{id}/read 🔒 Mark as read
DELETE /notifications/{id} 🔒 Delete
GET /admin/users 🛡 List users
DELETE /admin/users/{id} 🛡 Deactivate a user
GET /admin/orders 🛡 List all orders
PATCH /admin/orders/{id}/status 🛡 Move an order to SHIPPED, DELIVERED or CANCELLED
GET /healthz Liveness probe

gRPC status codes are translated to HTTP: InvalidArgument → 400, Unauthenticated → 401, PermissionDenied → 403, NotFound → 404, AlreadyExists/FailedPrecondition → 409, Unavailable → 503, DeadlineExceeded → 504. For 5xx responses the gateway logs the internal error and sends the client a generic message.

Example:

TOKEN=$(curl -s localhost:8080/api/v1/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"email":"admin@example.com","password":"admin12345"}' | jq -r .access_token)

curl -s localhost:8080/api/v1/products?limit=3
curl -s -X POST localhost:8080/api/v1/cart/items -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' -d '{"product_id":"<id>","quantity":1}'
curl -s -X POST localhost:8080/api/v1/checkout -H "Authorization: Bearer $TOKEN"

gRPC Services

Protocol definitions live in api/proto. Generated code is committed under api/gen/go.

Service Package RPCs Database
UserService user.v1 13: register, login, user CRUD, list, change password, validate, address CRUD userdb
CatalogService catalog.v1 14: product and category CRUD, list, search, adjust/decrement/release stock catalogdb
OrderService order.v1 13: cart operations, checkout, get/list orders, cancel, status update, order items orderdb
NotificationService notification.v1 12: send/bulk e-mail, template CRUD, notification history, read, delete, stats notificationdb

Every server also registers the standard gRPC health service and server reflection, so it can be explored with grpcurl:

grpcurl -plaintext localhost:50052 list
grpcurl -plaintext -d '{"limit":2}' localhost:50052 catalog.v1.CatalogService/ListProducts

Domain Events

Subject Publisher Consumers (queue group) Effect
orders.placed order-service, after the checkout transaction commits catalog-service Invalidates cached products whose stock changed
notification-service Looks up the customer over gRPC and sends an order confirmation

Queue groups make sure each event is handled once per consuming service, even when a service runs several replicas. NATS connections retry on startup and reconnect without limit.

Observability

  • Metrics: every process serves Prometheus metrics on METRICS_ADDR, including Go runtime metrics, ecommerce_grpc_requests_total{method,code}, ecommerce_grpc_request_duration_seconds, and on the gateway ecommerce_http_requests_total{method,route,status} and ecommerce_http_request_duration_seconds. HTTP routes are labelled by mux pattern (for example /api/v1/products/{id}) to keep cardinality low.
  • Tracing: client and server gRPC calls are instrumented with otelgrpc, and traces are exported to Jaeger over OTLP/gRPC. Each trace covers the full path, gateway → order → catalog.
  • Dashboards: Grafana provisions the Ecommerce Services dashboard with request rate, error rate, p95 latency, runtime and service health panels.

Testing

make test                 # unit tests
make test-race            # unit tests with the race detector (requires cgo)
make test-integration     # migrations against real PostgreSQL (see below)

Unit tests use in-memory fakes of the port interfaces and cover:

  • Order: checkout totals, stock reservation, event publishing, compensation on out-of-stock and on persistence failure, cancellation restocking (exactly once), ownership checks and status transitions.
  • User: registration and login, e-mail normalisation, duplicate detection, input validation, bootstrap admin idempotency.
  • Notification: order-confirmation flow, delivery-failure recording, ID validation.
  • Catalog: input validation.
  • Gateway: JWT validation (expired, wrong key, missing exp, alg: none), role enforcement including forged role claims, notification ownership, gRPC→HTTP error mapping without leaking internals, body validation, JSON 404/405 responses, CORS preflight and route labels.
  • Mailer: header injection protection.

Integration tests (build tag integration) run every service's migrations twice against PostgreSQL, which checks that they are idempotent, and then verify the schema. With the Compose stack running:

export INTEGRATION_USER_DATABASE_URL=postgres://ecommerce:ecommerce@localhost:5432/userdb?sslmode=disable
export INTEGRATION_CATALOG_DATABASE_URL=postgres://ecommerce:ecommerce@localhost:5432/catalogdb?sslmode=disable
export INTEGRATION_ORDER_DATABASE_URL=postgres://ecommerce:ecommerce@localhost:5432/orderdb?sslmode=disable
export INTEGRATION_NOTIFICATION_DATABASE_URL=postgres://ecommerce:ecommerce@localhost:5432/notificationdb?sslmode=disable
make test-integration

The CI pipeline (.github/workflows/ci.yml) runs formatting checks, go vet, race-enabled unit tests, integration tests against a PostgreSQL service container, buf lint and Docker image builds.

Project Structure

.
├── api/
│   ├── proto/<svc>/v1/*.proto     # gRPC contracts
│   ├── gen/go/                    # generated Go code (buf generate)
│   ├── buf.yaml, buf.gen.yaml
├── cmd/<svc>/main.go              # one binary per service + gateway
├── internal/
│   ├── <svc>/                     # user | catalog | order | notification
│   │   ├── domain/                # entities and domain rules
│   │   ├── usecase/               # application logic + ports + tests
│   │   ├── adapter/               # postgres, rediscache, grpcsvc, natsbus
│   │   └── migrations/            # embedded SQL migrations
│   ├── gateway/httpapi/           # REST gateway, auth middleware, tests
│   ├── platform/                  # config, migrate, server, natsx, mailer, telemetry, events
│   └── integration/               # integration tests (build tag)
├── web/                           # SPA (index.html, app.js, styles.css) + nginx config
├── deploy/
│   ├── Dockerfile                 # parameterised Go image (SERVICE build arg)
│   ├── postgres-init/             # creates the per-service databases
│   ├── prometheus/, grafana/      # observability configuration
├── docker-compose.yml
├── Makefile
└── .env.example

Development Workflow

make tools        # install buf, protoc-gen-go, protoc-gen-go-grpc
make proto        # regenerate code after changing .proto files
make lint-proto   # buf lint
make fmt vet test # format, vet, test
make build        # binaries in ./bin

To run one service on the host against the Compose infrastructure, start the infrastructure (docker compose up -d postgres redis nats mailhog jaeger) and run, for example, go run ./cmd/catalog-service. The defaults point to localhost.

Design Decisions

  • Database per service. Services never share tables. Cross-service data such as product prices or user e-mails is fetched over gRPC when needed.
  • Compensating actions instead of distributed transactions. Checkout first reserves stock in the catalog service, then commits the order locally. Failures release reservations through context.WithoutCancel, so a cancelled client request cannot leave stock stranded.
  • Authoritative authorization at the edge. Tokens carry the role for convenience. Admin access is still confirmed with the user service, and per-user resources are always scoped by the token subject, never by IDs supplied in the request body.
  • Explicit ports. Use cases declare the narrow interfaces they need, so tests run without databases or network, and adapters can be replaced.
  • Safe defaults. Strict JSON decoding with size limits, generic 5xx messages, escaped LIKE patterns, CRLF-sanitised mail headers, non-root distroless containers, CSP on the web client, and loopback-only port bindings in Compose.

Course Requirements Coverage

Requirement Implementation
Clean architecture Domain / use case / adapter layering with use-case-owned ports
≥ 12 gRPC endpoints per member 52 RPCs across four services
Message queue NATS orders.placed with queue-group consumers
Database, cache, migrations, transactions PostgreSQL per service, Redis caching, embedded migrations, transactional checkout
E-mail SMTP mailer (STARTTLS, optional auth), MailHog in development
Unit and integration tests Fakes-based use-case and gateway tests, migration integration tests
Frontend (bonus) SPA served by nginx with an API reverse proxy
Metrics, tracing, dashboards (bonus) Prometheus, OpenTelemetry → Jaeger, provisioned Grafana dashboard

About

A Go-based e-commerce microservices platform featuring gRPC communication, event-driven messaging with NATS, independent PostgreSQL databases, Redis caching, transactional checkout with compensating actions, and distributed observability using Prometheus, OpenTelemetry, Jaeger, and Grafana. Containerized with Docker.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages