Skip to content
MikeRider27Public

About

E-commerce with a Next.js frontend and Flask microservices: JWT, Redis rate limiting, idempotent checkout, observability and CI.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

ShopMicro — E-commerce with Next.js + Flask microservices

English · Español

CI

Sample e-commerce app with a Next.js frontend and a Flask microservices backend, built as a portfolio project: security, tests, CI/CD, observability and documented architecture, not just "it works".

Product catalog

Tech stack

Layer Technology
Frontend Next.js 14 (App Router), React 18, TypeScript, Tailwind CSS
Backend Python 3.12, Flask, SQLAlchemy, Marshmallow, Flask-JWT-Extended
Database PostgreSQL 16 (one database per microservice), Flask-Migrate/Alembic
Cache / rate limiting Redis 7
Gateway Nginx
Observability Structured JSON logs, Prometheus metrics, health/readiness
Testing pytest (backend), Jest + React Testing Library (frontend), Playwright (E2E)
CI/CD GitHub Actions
API documentation OpenAPI 3.0 + Swagger UI (/docs)
Infrastructure Docker Compose

Architecture

flowchart LR
    subgraph Client
        FE["frontend<br/>Next.js :3000"]
    end

    FE -->|"/api/*"| GW["gateway<br/>Nginx :8080"]

    subgraph Microservices
        AUTH["auth-service<br/>Flask :5001"]
        PROD["product-service<br/>Flask :5002"]
        ORD["order-service<br/>Flask :5003"]
    end

    GW -->|"/api/auth/*"| AUTH
    GW -->|"/api/products/*"| PROD
    GW -->|"/api/orders/*"| ORD
    GW -.->|"/api/products/internal/* → 404"| PROD

    ORD -->|"reserve/release stock<br/>(internal, not through gateway)"| PROD

    AUTH --> PG[("Postgres<br/>ecommerce_auth")]
    PROD --> PG2[("Postgres<br/>ecommerce_products")]
    ORD --> PG3[("Postgres<br/>ecommerce_orders")]

    AUTH --> RD[("Redis<br/>rate limiting")]
    PROD --> RD

    style PG fill:#e0e7ff,stroke:#4f46e5
    style PG2 fill:#e0e7ff,stroke:#4f46e5
    style PG3 fill:#e0e7ff,stroke:#4f46e5
    style RD fill:#fee2e2,stroke:#dc2626
Loading
  • auth-service: user registration/login, issues JWTs (ecommerce_auth).
  • product-service: product and category catalog, seeded with sample data (ecommerce_products).
  • order-service: creates orders by validating and deducting stock through product-service, protected with JWT (ecommerce_orders).
  • gateway: Nginx routes /api/* to each microservice, serves the API docs at /docs, and explicitly blocks internal endpoints (/api/products/internal/* → 404).
  • frontend: catalog, cart (persisted in localStorage), login/registration, checkout and order history.
  • postgres: bundled container with a persistent volume; the project does not depend on any external server to run (see docs/adr for the architecture decisions).
  • redis: shared rate-limiting backend (needed because each service runs 2 gunicorn workers).

Architecture decisions documented in detail (context, alternatives considered, consequences): docs/adr (in Spanish).

Requirements

  • Docker and Docker Compose v2 (docker compose) — the only thing needed to run the whole project.
  • To run the tests outside Docker: Python 3.12 (backend) and Node 20 (frontend).
  • Free host ports: 3000 (frontend) and 8080 (gateway); they can be changed with FRONTEND_PORT / GATEWAY_PORT in .env.

1. Environment variables (required)

The microservices refuse to start if any sensitive variable is missing (fail-fast), instead of falling back to insecure defaults. Copy the template and fill in the values marked as required:

cp .env.example .env

Generate strong secrets for JWT_SECRET_KEY and ADMIN_API_KEY:

python3 -c "import secrets; print(secrets.token_hex(32))"

By default everything runs inside Docker (Postgres and Redis included), without depending on any external IP. If you prefer an existing Postgres of your own, change POSTGRES_HOST/POSTGRES_PORT in .env, remove the postgres service (and its depends_on: condition: service_healthy entries) from docker-compose.yml, and run init-db.sql against that server once.

2. Run everything with Docker

docker compose up --build

Postgres creates the 3 databases automatically on first start (docker/postgres-initdb/01-create-databases.sh). Each microservice applies its own migrations on startup (flask db upgrade, see Migrations); product-service also seeds a sample catalog if it is empty (flask seed).

API documentation

With the stack running, the full documentation (OpenAPI 3.0 + Swagger UI, browsable, with request/response examples and every error code) is at:

http://localhost:8080/docs/

API documentation (Swagger UI)

The raw spec can also be read directly in docs/openapi.yaml. It documents authentication (JWT bearer and X-Admin-Key), every response code with examples, and states explicitly that product-service's /internal/* endpoints are not part of the public API (the gateway blocks them).

Main endpoints

Service Method Path (through gateway) Description
auth POST /api/auth/register Create account
auth POST /api/auth/login Login, returns JWT
auth GET /api/auth/me Authenticated user
products GET /api/products/products List products (?category=&search=)
products GET /api/products/products/<id> Product detail
products GET /api/products/categories List categories
products POST/PUT/DELETE /api/products/products Admin (X-Admin-Key header, see ADMIN_API_KEY)
orders POST /api/orders/orders Create order (requires JWT and Idempotency-Key header)
orders GET /api/orders/orders Authenticated user's history
all GET /api/<auth|products|orders>/health Liveness (depends on nothing external)
all GET /api/<auth|products|orders>/readiness Readiness (checks Postgres and, where relevant, Redis)
all GET /api/<auth|products|orders>/metrics Metrics in Prometheus format

Additional demo data

scripts/seed_demo_data.py adds more products, 3 test users and sample orders by calling the API (it does not touch the database directly):

python3 scripts/seed_demo_data.py
# or, with different ports/host:
GATEWAY_URL=http://localhost:8080 ADMIN_API_KEY=<the value from your .env> python3 scripts/seed_demo_data.py

Users created: ana@example.com, carlos@example.com, maria@example.com (password demo1234).

Migrations

Each microservice uses Flask-Migrate/Alembic (migrations/ folder) instead of db.create_all(). Each container's entrypoint.sh runs flask db upgrade automatically before starting gunicorn, so with docker compose up there is nothing to do by hand.

To change a service's schema (example with product-service):

cd services/product-service

# 1. Change the models in models.py

# 2. Generate the migration against a database with the current schema
#    (you can use the docker-compose Postgres: docker compose up -d postgres)
FLASK_APP=app.py POSTGRES_HOST=localhost POSTGRES_PORT=5432 \
  POSTGRES_USER=... POSTGRES_PASSWORD=... POSTGRES_DB=ecommerce_products \
  CORS_ALLOWED_ORIGINS=http://localhost:3000 ADMIN_API_KEY=... \
  flask db migrate -m "description of the change"

# 3. Review the generated file in migrations/versions/ (Alembic does not always
#    get renames or type changes right) and apply it
flask db upgrade

# Roll back the last migration if something went wrong:
flask db downgrade -1

In production, each service's entrypoint.sh applies pending migrations automatically when the container starts.

Tests

Each microservice has its own pytest suite (in-memory SQLite, no real Postgres needed) with a required minimum coverage of 70%:

cd services/auth-service   # or product-service / order-service
pip install -r requirements-dev.txt
ruff check .
python -m pytest

There is also a real integration test (tests/integration/test_end_to_end.py) that exercises the full auth → order → product → stock reservation flow against the deployed stack:

docker compose up -d
pip install pytest requests
GATEWAY_URL=http://localhost:8080 python -m pytest tests/integration -v

Frontend — unit/component tests with Jest + React Testing Library:

cd frontend
npm install
npm test

And a Playwright E2E test that runs in a real browser against the full stack (sign-up → products → cart → checkout → history):

docker compose up -d
cd frontend
npm install
npx playwright install --with-deps chromium   # once
E2E_BASE_URL=http://localhost:3000 npm run test:e2e

CI/CD

.github/workflows/ci.yml runs on every push/PR to main:

  • backend-tests: lint (ruff) + pytest with coverage for the 3 microservices (matrix).
  • frontend-tests: frontend unit/component tests with Jest.
  • docker-build: builds every image with docker compose build to catch build errors early.

The Playwright E2E test does not run in CI (it needs the full stack running with a real browser); it is meant to be run locally or, later, in a separate job with docker compose up.

Security

  • No secret has a default value in the code: POSTGRES_PASSWORD, JWT_SECRET_KEY, ADMIN_API_KEY, CORS_ALLOWED_ORIGINS and REDIS_URL are required; if any is missing, the service does not start.
  • CORS restricted to the origins listed in CORS_ALLOWED_ORIGINS (not *).
  • Rate limiting (Flask-Limiter + Redis) on /register, /login (10/min) and on the product admin endpoints (20/min). Redis is needed because each service runs 2 gunicorn workers and an in-memory limit would not be consistent across processes.
  • JWT with configurable expiration (JWT_ACCESS_TOKEN_EXPIRES_MINUTES, default 60 min). Refresh tokens were considered and left out of scope for simplicity — the frontend simply asks for login again when the token expires (see 401 handling in frontend/lib/api.ts).

Consistency between order-service and product-service

order-service does not share a database with product-service (each has its own), so creating an order is a two-step distributed operation: reserve stock there, save the order here. Without extra care that can leave inconsistencies, so:

  • Idempotency: POST /orders requires an Idempotency-Key header (the frontend generates one UUID per purchase attempt, see frontend/app/checkout/page.tsx). If two requests arrive with the same key (network retry, double click), the second returns the already-created order (200) instead of reserving stock and charging twice.
  • Compensation: if product-service already deducted the stock but order-service fails to save the order (database down, unexpected exception), it calls POST /internal/release-stock to return that reservation before responding with the error. It is best-effort: if that compensation call also fails, it is logged and the inventory stays inconsistent until a manual reconciliation — there are no automatic retries or pending-compensation queue yet.
  • Why not an event-driven architecture: an event bus (outbox + broker) would give stronger guarantees (retries, at-least-once, auditing), but it adds another infrastructure component, eventual consistency in the UI, and operational complexity that is not justified at this project's size. Synchronous reservation + Idempotency-Key + compensation covers the real cases (client retry, a service briefly down) at a much lower cost. If the system grew to more microservices or needed better failure decoupling, it would be worth revisiting.

Request validation

All three microservices validate the body of their write endpoints with Marshmallow (schemas.py in each service) instead of scattered ifs:

  • Types and ranges: valid email format (auth-service), numeric non-negative price/stock, positive integer quantity/product_id (product-service, order-service).
  • Arbitrary fields rejected: marshmallow uses unknown="raise" by default — sending an undeclared field (e.g. is_admin on registration, or total when creating an order) returns 400 instead of being silently ignored.
  • Before touching the database or another service: validation runs first; only if it passes is the database queried or product-service called.

Error handling

All three microservices return every error in the same format:

{ "error": { "code": "PRODUCT_NOT_FOUND", "message": "producto no encontrado" } }

details appears only when relevant (validation errors, with marshmallow's per-field detail). This is handled by global handlers (errors.py in each service), not by each endpoint separately:

  • Validation errors (marshmallow.ValidationError) → 400 VALIDATION_ERROR with details.
  • Any Flask/Werkzeug HTTPException (404 for a route that does not exist, 405, 429 from the rate limiter, etc.) → same format, with a generic code based on the status (NOT_FOUND, METHOD_NOT_ALLOWED, RATE_LIMITED...).
  • JWT failures (auth-service, order-service) → MISSING_TOKEN / TOKEN_EXPIRED (401) or INVALID_TOKEN (422), instead of flask-jwt-extended's default {"msg": "..."}.
  • Any unexpected exception → generic 500 INTERNAL_ERROR; the real detail (traceback, SQL message, etc.) is logged server-side but never sent to the client.
  • Business errors have their own code (EMAIL_ALREADY_REGISTERED, INSUFFICIENT_STOCK, INVALID_ADMIN_KEY, ORDER_NOT_FOUND, etc.), so the frontend (or any API consumer) can react to a code instead of parsing the message text (messages are in Spanish).
  • When order-service forwards an error from product-service (e.g. when reserving stock), it propagates the original code/message instead of hiding them behind a generic message (see parse_upstream_error in services/order-service/errors.py).

Communication between microservices

  • Explicit timeouts: every call from order-service to product-service has a 10 s timeout (PRODUCT_SERVICE_TIMEOUT_SECONDS) — it never waits forever if the other service does not respond.
  • Retries, but only where safe: reserve-stock and release-stock are not idempotent (calling them twice deducts/returns stock twice), so order-service retries (up to 2 times, with a short backoff) only on ConnectionError — the request never reached the other service, so retrying is risk-free. A read timeout (ReadTimeout, the request may have arrived and been processed) is not retried: it is propagated as 503 immediately, to avoid risking a double reservation. See _post_to_product_service in services/order-service/app.py.
  • Correlation ID (X-Request-ID): the frontend generates a UUID per request (frontend/lib/api.ts); the gateway keeps it if present, or generates one with nginx's $request_id if not; each microservice reads it (or generates one if called directly), returns it in the response, and includes it in every log line (middleware.py in each service) — including propagation from order-service to product-service on internal calls. This makes it possible to follow a single request through the logs of several services (see the example in the Observability section).
  • Centralized service URLs: docker-compose.yml is the single source of truth for how services address each other (PRODUCT_SERVICE_URL=http://product-service:5002, service names = Docker hostnames); each service's config.py only has a fallback for running it standalone (tests, local flask run).

Observability

  • Structured logs (JSON): every log line from the 3 services is a JSON object (timestamp, level, logger, message, request_id, plus any extra field), ready to ship to ELK/Loki/CloudWatch without parsing plain text (JsonFormatter in middleware.py). Real example, an order being created — note the same request_id in both services:
    {"timestamp": "2026-09-17T20:20:22+0000", "logger": "product-service", "message": "stock_reserved", "request_id": "ecac48b7...", "event": "stock_reserved", "items": [{"product_id": 1, "quantity": 1}]}
    {"timestamp": "2026-09-17T20:20:22+0000", "logger": "order-service", "message": "order_created", "request_id": "ecac48b7...", "event": "order_created", "order_id": 1, "user_id": 1, "total": 29.99, "item_count": 1}
  • Credentials are never logged: no passwords, JWTs, X-Admin-Key or request bodies. Business events (log_event) only carry IDs, quantities and amounts — for example user_registered logs user_id, never the email.
  • Business events recorded: user_registered (auth-service), stock_reserved / stock_released (product-service), order_created / order_idempotent_replay / order_stock_compensated (order-service).
  • Basic metrics: each service exposes GET /metrics in Prometheus format — http_requests_total, http_request_duration_seconds and http_request_errors_total, labelled by method/endpoint/status. No extra infrastructure required; any Prometheus can scrape it directly.
  • Health vs. readiness: GET /health (liveness) depends on nothing external — if it responds, the process is alive. GET /readiness checks Postgres (and Redis where relevant) and returns 503 if either fails; it is what the docker-compose.yml healthcheck uses so a service is not marked healthy before it can really serve traffic.

Docker

  • Non-root user: the 4 services we build (auth/product/order-service and frontend) run as an unprivileged user (appuser / nextjs), not as root. Postgres/Redis/nginx are official images that already handle this internally.
  • Pinned base image versions: python:3.12.14-slim-bookworm, node:20.20.2-alpine, nginx:1.27.5-alpine, postgres:16.15-alpine, redis:7.4.11-alpine — no floating tags (python:3.12-slim, etc.) that could silently pull a different version on each build.
  • Exact dependency versions: every requirements.txt uses == (never a range); package.json pins exact Next/React versions.
  • Per-service .dockerignore: each Python microservice excludes tests/, pytest/ruff caches, requirements-dev.txt and any .env from the build context, so development tools and secrets never end up inside the image.
  • Multi-stage frontend build: deps → builder → runner; the final image carries no devDependencies (TypeScript, Tailwind, etc.) or source code, only Next.js's standalone output.
  • Known limitation: python:3.12.14-slim-bookworm still ships some reported vulnerabilities at the OS-package level (not in our code) — a reality of any Debian/Alpine base image that requires periodic updates (e.g. Dependabot/Renovate for automatic rebuild PRs), not something solved once.

Frontend

  • API error handling: lib/api.ts distinguishes a network error (fetch() rejects — server down, no connection) from an HTTP error from the backend, with a typed ApiError (code, status, message) instead of raw messages like "Failed to fetch".
  • Loading/success/error/empty states: present on every page that fetches data (catalog, product detail, cart, orders) — text spinner while loading, red banner on error, explicit message when the list is empty, and a green confirmation after a successful order.
  • Client-side form validation (lib/validation.ts): registration, login and checkout validate email/password/address before calling the API — same rules as the backend's Marshmallow schemas (see Request validation), but with immediate feedback instead of waiting for the round trip.
  • Session and expiration:
    • When the app loads, a stored token is validated against GET /auth/me instead of blindly trusting localStorage — if it has expired, it is detected right away rather than when the user tries to buy something.
    • Any 401 on an authenticated request clears the session and redirects to /login?reason=session_expired, which shows a notice explaining why instead of a silent redirect.
    • Every visit to /checkout generates its own Idempotency-Key (see Consistency between order-service and product-service).

The user interface is in Spanish.

Design notes / simplifications

  • Each microservice uses its own database inside the same Postgres (logical isolation, no shared tables).
  • Catalog writes (POST/PUT/DELETE /products) are protected by a simple X-Admin-Key header (ADMIN_API_KEY variable), intended for internal administration, not for the public frontend.
  • The shopping cart lives on the client (localStorage); there is no cart persisted in the database.

Roadmap

This covered the 16 phases identified in the original improvement plan. What remains, already scoped but out of this release:

  • A real Prometheus/Grafana scraping each service's /metrics (today they are only exposed; nothing scrapes them).
  • Centralized log aggregation (today logs stay in docker compose logs, not in ELK/Loki/CloudWatch).
  • Automatic base-image updates (Dependabot/Renovate) — see the Docker section.
  • Running the Playwright E2E test in CI (today it is manual; it needs the full stack running with a browser).
  • Using Issues and Pull Requests for every change from now on (commits have followed Conventional Commits from the start), now that the templates (.github/) and the contribution guide (CONTRIBUTING.md) exist.

Contributing

Want to contribute? See CONTRIBUTING.md for the workflow, how to run the tests before a PR, and the commit conventions. To report a security issue, follow SECURITY.md instead of opening a public Issue.

Author

Miguel Villalba — mike.mavc27@gmail.com

License

This project is licensed under the MIT License.

About

E-commerce with a Next.js frontend and Flask microservices: JWT, Redis rate limiting, idempotent checkout, observability and CI.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages