Skip to content

Repository files navigation

Bazaar API Gateway

Kong Version Docker OpenTelemetry

The Bazaar API Gateway is a reverse proxy and API Gateway service built on Kong Gateway (v3.6) running in db-less (declarative) mode. It serves as the single entry point for all client requests in the Bazaar ecosystem, orchestrating routing, enforcing JWT-based authentication, injecting identity headers for downstream microservices, handling CORS, and exporting distributed tracing telemetry.


Table of Contents

  1. Core Features
  2. System Architecture
  3. Technology Stack
  4. Environment Configuration
  5. Getting Started

Core Features

  • Centralized Routing & Reverse Proxy:
    • Acts as the single entry point for client applications (mobile, web).
    • Routes traffic to the appropriate backend microservices: User Service, Catalog Service, Cart Service, and Orders Service.
  • Authentication & JWT Validation:
    • Uses Kong's built-in JWT Plugin to validate tokens signed with a shared HMAC secret.
    • Enforces expirations (exp) and token issuer (iss) matching for protected routes.
  • Identity Header Injection (Lua Post-Functions):
    • Automatically decodes the Base64Url JWT payload on successful validation.
    • Injects critical context headers (X-User-Id and X-User-Role) before forwarding requests downstream, keeping backend microservices decoupled from JWT parsing logic.
  • Smart Login Source Tracking (Pre-Function):
    • Dynamically inspects the Origin header during /auth/login requests.
    • If the request originates from the Backoffice portal (matching CLIENT_BACKOFFICE_URL), it injects an X-Login-Source: BACKOFFICE header; otherwise, it assigns X-Login-Source: OTHER.
  • Global CORS Policy:
    • Standardizes cross-origin policies across the entire gateway, handling preflight OPTIONS requests seamlessly.
  • Distributed Tracing & Telemetry:
    • Integrates with OpenTelemetry to collect request traces and push them to a centralized collector (e.g. Jaeger, Tempo).
  • Dynamic Gateway Health Checks:
    • Exposes health endpoints (/livez, /health) that respond immediately with 200 OK and a gateway status payload: {"status": "UP", "gateway": "Kong"}.

System Architecture

Clients communicate only with the API Gateway. The Gateway handles validation, transforms the request headers, and proxies the traffic:

graph TD
    Client([Client / App Mobile / Web]) -->|HTTP Requests| Gateway[Bazaar API Gateway]
    
    subgraph API Gateway Kong
        Gateway -->|1. CORS check & OTEL Trace| CORS[CORS / OTEL Plugins]
        Gateway -->|2. Validate JWT & exp claim| JWT[JWT Validator Plugin]
        Gateway -->|3. Extract sub & role| LuaPost[Lua Post-Function Script]
    end

    LuaPost -->|Proxies with X-User-Id & X-User-Role| UserService[User Microservice]
    LuaPost -->|Proxies with X-User-Id & X-User-Role| CatalogService[Catalog Microservice]
    LuaPost -->|Proxies with X-User-Id & X-User-Role| CartService[Cart Microservice]
    LuaPost -->|Proxies with X-User-Id & X-User-Role| OrdersService[Orders Microservice]
Loading

Note

Behind the gateway, downstream microservices rely on trust-based authorization. They extract user context directly from the custom injected headers: X-User-Id and X-User-Role.


Technology Stack

  • Proxy Engine: Kong Gateway 3.6 (Db-less mode)
  • Deployment: Docker, Docker Compose
  • Configuration Engine: declarative YAML (kong.template.yml) with environment variable substitution (envsubst)
  • Telemetry: OpenTelemetry Plugin
  • Authentication: JWT Plugin (HMAC-SHA256 verification)
  • Scripting & Hooks: Lua serverless functions (Kong pre-function and post-function hooks)
  • Testing: k6 (Performance and stress tests)

Environment Configuration

To configure the API Gateway, create a .env file in the root directory based on the .env.example template:

cp .env.example .env

Required Configuration Properties

Variable Description Default / Example
JWT Verification
JWT_ALGORITHM Secret hashing algorithm for JWT signatures HS256
JWT_ISSUER Expected token issuer (iss claim) bazaar-auth
JWT_SECRET Secret HMAC key used to verify the signature your-super-jwt-secret
Downstream Services
SERVICE_USER_URL Base URL of the User Microservice http://user-service:8080
SERVICE_CATALOG_URL Base URL of the Catalog Microservice http://catalog-service:8081
SERVICE_CART_URL Base URL of the Cart Microservice http://cart-service:8082
SERVICE_ORDERS_URL Base URL of the Orders Microservice http://orders-service:8083
Kong Network Ports
PORT_PROXY Mapped HTTP proxy port on host 8000
PORT_PROXY_SSL Mapped HTTPS proxy port on host 8443
PORT_ADMIN Mapped Admin HTTP port on host 8001
PORT_ADMIN_SSL Mapped Admin HTTPS port on host 8444
Telemetry & Backoffice
OTEL_EXPORTER_OTLP_ENDPOINT OpenTelemetry collector endpoint for traces http://otel-collector:4317
OTEL_EXPORTER_OTLP_AUTH Optional authentication key for OTLP exporter (Optional)
OTEL_SERVICE_NAME Service label reported in OpenTelemetry traces api-gateway
CLIENT_BACKOFFICE_URL URL matching pattern for Backoffice requests http://backoffice.bazaar.com

Getting Started

Prerequisites

  • Docker & Docker Compose

Running with Docker Compose

  1. Create the shared Docker network (if not already created):

    docker network create bazaar-network
  2. Build and start the Gateway container:

    docker-compose up --build

    This starts the gateway on port 8000 (HTTP) and 8443 (HTTPS) by default, mapping them to the configured host ports.

  3. Verify Gateway Health: You can verify that the gateway is running and healthy by sending a GET request to the health route:

    curl http://localhost:8000/health

    Expected response:

    {"status": "UP", "gateway": "Kong"}

Stopping the Gateway

To tear down the container and preserve volumes:

docker-compose down

Stress & Performance Testing (k6)

Load test configurations and scripts are available under test/k6/scripts. Ensure the complete stack is up and running before executing stress tests.

To run tests within a Dockerized k6 instance inside the shared network:

  • On macOS/Linux (Bash):
    docker run --rm --network bazaar-network -v "$(pwd)/test/k6:/io" -w /io grafana/k6 run scripts/<test_name>.js
  • On Windows (PowerShell):
    docker run --rm --network bazaar-network -v "$($pwd.Path)/test/k6:/io" -w /io grafana/k6 run scripts/<test_name>.js

Available Test Scripts

  • login-stress.js: Stress tests the Authentication / login endpoint under load.
  • register-stress.js: Validates registration endpoint throughput.
  • create-product-stress.js: Measures performance of catalog insertions.
  • checkout-stress.js: Exercises the checkout and payment transaction flow.

About

This module validates JWT tokens and routes requests accordingly

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages