Zero to Hero roadmap: Master service boundaries, database-per-service isolation, Docker containerization,
event-driven pub/sub messaging, Istio service mesh, and OpenTelemetry APM observability.
π± Zero to Hero Curriculum β’ Stages 1 & 2 to Milestone 5 (Gateway)
β’ Step-by-Step Practical Blueprint
β 86 Automated Tests Passing
Python 3.12 Standard
Python Microservices: Zero to Hero Curriculum
A complete, production-grade microservices masterclass. Learn HTTP boundaries, engineering standards, independent databases, resilient HTTPX retries, asynchronous pub/sub messaging, Dead Letter Queues, signed JWT security, consumer contracts, Kubernetes observability, and unified API Gateway ingress routing.
π Click a Stage to Display Its Full Practical Lesson:
STAGE 1 β’ BEGINNER
Stage 1 β Foundations of Microservices
Step 1: Master the Network Boundary (Monolith to Two HTTP Services)
REST & HTTP
Ports 8001 & 8002
12-Factor App
π 1. The Lesson: Architecture & Network Boundaries
A microservice is an autonomous, independently deployable software component that models a single business capability. It communicates over a network via language-agnostic protocols (typically HTTP/REST) and strictly encapsulates its own database and state.
Attribute
Classic Monolith
Modular Monolith
Microservices
Deployment
Single deployable unit
Single deployable, clean modules
Multiple independent services
Database
Single shared schema
Single DB, logical separation
Database-per-service (isolated)
Communication
In-memory function calls
In-memory interfaces
Network I/O (HTTP REST, ports)
Failure Radius
High (one bug can crash process)
Medium (memory leak affects all)
Isolated (User crash != Order crash)
π HTTP Status Codes & Failure Semantics:
200 OK: Request succeeded.
201 Created: Resource created successfully.
400 Bad Request: Client payload validation error.
404 Not Found: User or Order missing.
409 Conflict: Duplicate email/username.
502 Bad Gateway: Upstream returned unparseable response.
503 Unavailable: Downstream service offline.
504 Timeout: Downstream service exceeded deadline.
π» 2. Code Explanation: Monolith to Decoupled Services
π 1. The Lesson: Clean Architecture & Type Safety
Enterprise microservices require strict typing, domain invariant enforcement, and decoupled abstractions. By applying Clean Architecture, business logic is isolated from database drivers and external HTTP libraries.
LAYER 1: DOMAIN ENTITIES
Immutable Value Objects
@dataclass(frozen=True) models (Money, ChargeRequest) with validation.
LAYER 2: PROTOCOLS (DI)
Structural Subtyping
typing.Protocol contracts for gateways and repositories. Zero direct coupling.
LAYER 3: USE CASE SERVICE
Business Logic & Idempotency
Enforces currency limits, caps, and deduplication of retried payment requests.
LAYER 4: OBSERVABILITY
JSON Logs & Correlation ID
Single-line JSON logs with request tracing across distributed services.
πΉοΈ 2. Interactive Stage 2 Payment Service Console
Test business rule validation, idempotency deduplication, and error mapping in service_template.py:
[Payment Engine Ready] Click any action above to test typed validation, idempotency caching, and structured logging...
π 1. The Lesson: Production Services & Distributed Data
In this unified milestone, we transition from theoretical templates to real running services with independent databases. Catalog Service manages its own database schema, and Order Service uses Data Snapshotting to preserve transaction history with zero cross-service database joins.
LEVEL 3: FASTAPI & SCHEMAS
Pydantic v2 & Dependency Injection
Strong typing, query parameter bounds (limit/offset), auto-generated Swagger UI at /docs, and Depends(get_db) session management.
LEVEL 4: HTTPX & RETRIES
Exponential Backoff & Timeouts
Order Service calls Catalog with granular timeouts (1s connect, 3s read). Automatically retries transient network drops with increasing delay (0.2s, 0.4s).
LEVEL 5: DISTRIBUTED DATA
Zero Cross-DB Joins (Snapshotting)
Catalog Service and Order Service have separate DB files. Orders store unit price and product name locally at checkout time for immutable accounting records.
πΉοΈ 2. Interactive Milestone 2 Service Console
Test the live interaction between the Catalog Service (Port 8002) and Order Service (Port 8003):
[Milestone 2 Platform Ready] Click any action above to test FastAPI Catalog CRUD, HTTPX inter-service calls, and isolated database snapshots...
Pub/Sub Event Bus + Idempotent Consumer + Dead Letter Queue (DLQ) + JWT & RBAC Security
Pub/Sub Broker
Dead Letter Queue (DLQ)
JWT HS256 & RBAC
π 1. The Lesson: Asynchronous Events & Defense-in-Depth
In Milestone 3, we eliminate synchronous blocking bottlenecks and protect every endpoint. When a customer places an order, the Order Service does not wait for email/SMS notifications to be dispatched. Instead, it emits an order.created domain event to an asynchronous Event Bus and responds instantly. Downstream services consume events independently with idempotent deduplication and Dead Letter Queue (DLQ) safeguards.
LEVEL 6: ASYNC PUB/SUB
Non-Blocking Background Tasks
Order placement dispatches order.created via background tasks. The customer receives their HTTP 201 response in milliseconds, without waiting for third-party email latency.
LEVEL 6: IDEMPOTENCY & DLQ
Deduplication & Poison Isolation
Distributed message brokers guarantee at-least-once delivery. Consumers track event_id to avoid double-processing. Poison messages fail 3 times and route safely to the Dead Letter Queue.
LEVEL 7: SECURITY & RBAC
Signed JWTs & Service Tokens
FastAPI dependencies enforce strict token verification (401) and role checks (403). Only customer can order, only admin can inspect DLQ, and internal services authenticate via M2M tokens.
πΉοΈ 2. Interactive Milestone 3 Security & Event Bus Console
Test JWT authentication, RBAC authorization, async event publishing, consumer idempotency, and DLQ capture:
[Milestone 3 Platform Ready] Click any action above to test JWT Authentication, RBAC, Async Event Bus, Consumer Idempotency, and Dead Letter Queue (DLQ)...
π 1. The Lesson: Production Readiness & Operational Excellence
Building a microservice is only half the battle. In production, services must be monitored, packaged into secure lightweight containers, and tested against real-world network chaos. Milestone 4 completes your journey from beginner to professional cloud engineer.
LEVEL 8: CONTRACTS & CHAOS
Fault Injection & Schema Guards
Consumer-driven contracts catch breaking API field changes before deployment. Chaos fault injection simulates socket hangs and drops to prove the service fails fast with clean 503s instead of crashing.
LEVEL 9: DOCKER & COMPOSE
Multi-Stage Builds & Orchestration
Multi-stage Dockerfiles compile dependencies in a builder stage and run on python:3.12-slim with an unprivileged appuser. Docker Compose wires catalog, orders, and workers on an isolated network.
LEVEL 10: OBSERVABILITY & K8S
Tracing, Metrics & Health Probes
Context-propagated X-Correlation-ID traces requests end-to-end. Prometheus scrapes /metrics for request rates, while Kubernetes uses /healthz/live and /healthz/ready to route traffic.
πΉοΈ 2. Interactive Milestone 4 Production Console
Test Prometheus metrics, Kubernetes health probes, structured logging, and chaos injection:
[Milestone 4 Platform Ready] Click any action above to test Prometheus Metrics, K8s Readiness/Liveness Probes, Structured JSON Logging, and Chaos Engineering...
β Automated Test Suite: test_milestone4.py (12/12 passing β’ 100% test coverage)
β Milestone 4 Passed
MILESTONE 5 β’ CAPSTONE ARCHITECTURE
Milestone 5 β Unified API Gateway & Ingress Orchestration
Step 5: Consolidate Microservices Under a High-Performance Ingress Gateway (:8080)
Port 8080 Ingress
Sliding Window Rate Limit
HTTPX Async Reverse Proxy
Cluster Health Aggregation
π 1. Architectural Role: The Gateway Pattern
In a distributed system with 4, 10, or 50 microservices, exposing individual service ports directly to mobile apps, web single-page apps (SPAs), or third-party integrators causes severe architectural liabilities:
β οΈ Without API Gateway (Anti-Pattern)
Client must know 4+ host/port URLs (:8001, :8002, :8003, :8004).
Security rules & rate limiting must be duplicated in every backend.
Backend network topology is exposed directly to the public internet.
CORS configuration must be synchronized across all services.
π‘οΈ With Unified Ingress Gateway (:8080)
Single base URL http://api.cloudshop.internal:8080 for all clients.
Test the live Gateway capabilities: reverse proxy routing, sliding window rate limiter, correlation tracking, and cluster health sweep:
// API Gateway Interactive Console (:8080)Click one of the buttons above to simulate reverse proxy dispatch, rate limiting, and cluster aggregation.
π§ͺ Automated Test Suite: test_gateway.py
13/13 Passing (100%)
FastAPI + HTTPX AsyncClient
Verifies route dispatching across all 4 services, rate limiter sliding window eviction, correlation ID preservation & injection, parallel health check aggregation, and 503 Bad Gateway fault handling.
π Curriculum Mastered: Zero to Hero + Gateway!
π Foundations & Standards Completed!
Ready for Macro Blueprints & the CloudShop Platform?
You have mastered the foundational building blocks: HTTP network boundaries, ports, type safety, frozen dataclasses, protocol dependency injection, and idempotency. Now explore the 8 progressive architectural blueprints or launch the 4-service CloudShop interactive platform!
8 Progressive Stages: From Monolith to Distributed Cloud Systems
Learn the core engineering blueprints of modern distributed applications.
Explore how monolithic backends transition into independent bounded contexts, implement database-per-service isolation, deploy polyglot persistence, wire resilient service meshes with circuit breakers, and trace end-to-end distributed requests with OpenTelemetry flamegraphs.
πΊοΈ Part 1: Visual Learning Syllabus
Select Any of the 8 Stages to Inspect in Studio:
Click any stage card below to instantly display its architecture screen, layout breakdown, and code recipe in the studio screen below.
Client ingress, unified API Gateway routing, core business domains, and synchronous (REST/gRPC) vs asynchronous (Message Broker) traffic separation.
STAGE 02
Data IsolationClick to View
2. Database-per-Service & Async Flow
Strict persistence isolation (Users DB, Orders DB, Payments DB, Inventory DB) and asynchronous event decoupling to Notification Service.
STAGE 03
Polyglot PersistenceClick to View
3. Docker Host & Polyglot Event Bus
Multi-container host networking with heterogeneous persistence (MongoDB, SQL Server, MySQL) communicating across an internal publish/subscribe Event Bus.
STAGE 04
Enterprise MeshClick to View
4. Istio Mesh & Circuit Breakers
Fault tolerance with circuit breaker isolation, zero-trust Identity Provider auth, rate limiting, Kafka streams, and distributed tracing.
STAGE 05
Cloud DeploymentClick to View
5. Docker Compose & Kubernetes Mesh
Local developer workflow with Docker Compose and ELK stack promoted to production Kubernetes clusters with Helm charts and rolling updates.
STAGE 06
Distributed TracingClick to View
6. OpenObserve APM Service Map
Real-time 40-span trace visualization showing service topology, customer/driver routing latency, MySQL query duration, and Redis cache spans.
STAGE 07
Latency ProfilingClick to View
7. SigNoz Flamegraph Profiling
OpenTelemetry trace flamegraphs showing percentage execution time across services with one-click drilldown into correlated logs, metrics, and attributes.
STAGE 08
RPC MetadataClick to View
8. Span Context & RPC Metadata
W3C TraceContext propagation across gRPC hops (`CurrencyService/Convert`), capturing custom business attributes (USD to CHF) and availability zones.
External clients (Web & Mobile) pass through a centralized API Gateway. Traffic is routed synchronously (REST/gRPC) to decoupled services (User, Product, Order, Notification), each backed by isolated database stores. Asynchronous events route through a message broker.
Single Ingress: API Gateway terminates TLS and decouples internal network addresses.
Sync vs Async: Reads/writes on HTTP/gRPC, while notifications run through Kafka/RabbitMQ.
Bounded Contexts: Each service encapsulates its own business domain and schema.
π‘Production Implementation
FastAPI & ASGI: Deploy services using Uvicorn/Gunicorn workers. Use Pydantic v2 data models for input validation and strict HTTP status code semantics.
service_gateway.py
Interactive Code Recipe
# FastAPI API Gateway Routing Example
from fastapi import FastAPI, HTTPException, Request
import httpx
app = FastAPI(title="TeachCloud API Gateway", version="1.0.0")
SERVICE_REGISTRY = {
"users": "http://user-service:8001",
"products": "http://product-service:8002",
"orders": "http://order-service:8003"
}
@app.get("/api/v1/{service_name}/{endpoint_path:path}")
async def gateway_proxy(service_name: str, endpoint_path: str, request: Request):
if service_name not in SERVICE_REGISTRY:
raise HTTPException(status_code=404, detail="Service not found")
target_url = f"{SERVICE_REGISTRY[service_name]}/{endpoint_path}"
async with httpx.AsyncClient(timeout=5.0) as client:
res = await client.request(
method=request.method,
url=target_url,
params=request.query_params,
headers={k: v for k, v in request.headers.items() if k.lower() != "host"}
)
return res.json()
π Architecture Foundations Completed
Ready to Put Architecture Theory into Practice?
You've mastered the 8 foundational architectural stages: Bounded Contexts, DB-per-Service, Docker Compose, Circuit Breakers, and OpenTelemetry flamegraphs. Now apply these exact patterns to the real-world CloudShop Microservices Platform!
A fictional e-commerce platform that grows from a simple Python application into a distributed system.
Explore the 4 decoupled domain services below: Product Service, Identity Service, Order Service, and Notification Service.
Progressive Cloud Infrastructure: API Gateway, PostgreSQL (DB-per-Service), Redis caching where justified, RabbitMQ event queues, Docker Compose containerization, automated testing, CI/CD, and distributed observability.
π‘ The project teaches you when a microservice is useful, when a monolith is better, and how to manage the extra complexity that comes with distributed systems.
π¦ 4 Domain Services
Select a CloudShop Service to Inspect & View Microservice Code:
Product catalogue lifecycle, category categorization, multi-attribute filtering (brand, rating, price range), stock availability read-probes, and sub-10ms response times via Redis caching.
πREST & gRPC Contracts
GET /api/v1/products β Filterable paginated catalog
GET /api/v1/products/{id} β Detailed spec & inventory
POST /api/v1/products β Admin product insertion
π‘Production Implementation
FastAPI & Redis Cluster: Deploy with 4 Uvicorn workers per container. Use an async Redis connection pool (max_connections=20) with 5-minute cache TTLs and write-through invalidation on catalog updates. Postgres tables indexed on (category_id, price) with composite B-Trees.
πSection A Blueprint Links
β’ Stage 01: Gateway proxy routing
β’ Stage 02: Isolated Products DB (No joins)
β’ Stage 03: Redis cache polyglot storage
product_service.py
Interactive Microservices Code Engine
# FastAPI Product Catalog Service with Redis Caching
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
import redis.asyncio as aioredis
import json
app = FastAPI(title="CloudShop Product Service", version="1.0.0")
redis_client = aioredis.from_url("redis://redis:6379/0", decode_responses=True)
class ProductResponse(BaseModel):
id: int
name: str
price: float
stock_count: int
@app.get("/api/v1/products/{product_id}", response_model=ProductResponse)
async def get_product(product_id: int):
cache_key = f"product:{product_id}"
cached = await redis_client.get(cache_key)
if cached:
return json.loads(cached)
# Query Postgres isolated Products DB
product = await db.fetch_one("SELECT * FROM products WHERE id = :id", {"id": product_id})
if not product:
raise HTTPException(status_code=404, detail="Product not found")
await redis_client.setex(cache_key, 300, json.dumps(dict(product)))
return product
βοΈArchitectural Wisdom: When to Choose Microservices vs. Monolith
β When Microservices are Useful:
Independent scaling (e.g. catalog reads vs payment writes), decoupled deploy cadence across teams, polyglot databases, and isolating payment/auth failures from crushing the entire store.
β οΈ When a Monolith is Better:
Early MVP stage, small engineering teams (1β4 developers), ACID transactions requiring single-database rollbacks, zero network RPC latency, and minimal operational complexity.
π‘οΈ Managing Distributed Complexity:
Use the Transactional Outbox pattern for dual-write safety, idempotency keys on payment endpoints, W3C correlation IDs for tracing, and circuit breakers for graceful degradation.
π Curriculum Navigation
Review the 8 Core Architectural Blueprints?
You can return to SECTION A at any time to review foundational patterns including Bounded Contexts, Docker Compose networking, Circuit Breakers, and OpenTelemetry flamegraphs.
In production microservices, client applications never communicate directly with internal ports. The API Gateway serves as the single public entry point on port 8080, dynamically routing requests to downstream backends, injecting distributed correlation IDs, shielding services with sliding-window rate limiting, and aggregating cluster health.
Before a microservice cluster is promoted to production or integrated with Autonomous AI Agents, it must pass rigorous architectural, security, reliability, and deployment criteria. Explore the step-by-step learning roadmap, audit your codebase, or test your architectural reflexes in the scenario quiz.
πΊοΈ Progressive Curriculum Roadmap: From Zero to Autonomous AI
Follow the sequence below to understand how every layer builds on the previous one:
During high traffic, Order Service calls Catalog Service to reserve inventory. Catalog Service DB lags and takes 10 seconds to respond. How must Order Service behave?
A customer clicks "Pay" on mobile. The network lags, and the mobile app retries the HTTP POST 3 seconds later. Both requests reach the server. How do you prevent double-billing?
Where should JWT signing secrets, database credentials, and API tokens be stored for microservices?
SCENARIO 4 β’ EVENT BUS & POISON PILLS
Unanswered
A malformed event is sent to the message bus and causes the consumer to crash every time it tries to deserialize it. How do you prevent it from blocking the queue?
Your backend contains 4 microservices on ports 8001, 8002, 8003, and 8004. What is the production standard for client ingress?
π 100% PERFECT SCORE!
You Think Like a Senior Distributed Systems Architect!
You have mastered network timeouts, idempotency deduplication, environment security, dead letter queues, and API Gateway ingress shielding. You are fully prepared to connect this cluster to Autonomous Python AI Agents!
Image uses minimal slim runtime and executes under an unprivileged `USER appuser` without compilers.
CloudShop: Multi-stage Dockerfile in Milestone 4
5.4 Ingress API Gateway (:8080) & Tracing Propagation
Centralized ingress reverse proxy with sliding-window rate limiting (429) and `X-Correlation-ID` injection.
CloudShop: gateway.py & test_gateway.py
π 20/20 AUDIT CERTIFIED
Production Architecture Acceptance Complete!
Every single architectural, reliability, security, and ingress requirement has been verified. The CloudShop cluster is officially production-certified and ready to front Autonomous AI Agents.
TeachCloud uses essential cookies for secure login sessions, CSRF protection, and site preferences (such as Dark/Light theme). Temporary session data is automatically cleared when you close your browser.
π Essential SecurityRequired
Manages CSRF tokens, secure authentication cookies, and session integrity.
π¨ Theme & CustomizationActive
Preserves chosen color themes (Day Light, Night Dark, Midnight) and screen accents.
β±οΈ Session LifecycleAuto-Cleared
Session tokens and temporary caches are securely discarded on tab or browser close.