Python Microservices & Distributed Systems
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.
π Select Python Experience Track
π 1. Foundations
π 2. Blueprints (A)
π 3. CloudShop (B)
π 4. API Gateway
π― 5. Audit & Quiz
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.
Stage 1 β Foundations of Microservices
π 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:
π» 2. Code Explanation: Monolith to Decoupled Services
# Tightly coupled memory lookup:
USERS_DB = {"usr_101": {"name": "Alice"}}
ORDERS_DB = {}
def place_order(user_id, item, amount):
# Direct memory read - Zero isolation!
user = USERS_DB.get(user_id)
if not user:
raise ValueError("User not found")
order_id = f"ord_{len(ORDERS_DB)+1}"
ORDERS_DB[order_id] = {"item": item}
return ORDERS_DB[order_id]
# Order Service calls User Service via HTTP REST:
try:
resp = requests.get(
f"{USER_SERVICE_URL}/api/v1/users/{user_id}",
timeout=2.0
)
if resp.status_code == 404:
return jsonify({"error": "User missing"}), 404
except requests.exceptions.Timeout:
return jsonify({"error": "Gateway Timeout"}), 504
except requests.exceptions.ConnectionError:
return jsonify({"error": "Service Unavailable"}), 503
πΉοΈ 3. Interactive Stage 1 Request Console
Execute simulated network calls between the User Service (Port 8001) and Order Service (Port 8002):
test_health_check (Probe returns status 200)β
test_get_existing_user & test_get_nonexistent_user_returns_404β
test_create_user_success & test_create_user_duplicate_returns_409β
test_place_order_success_when_user_exists (Order created after 200 OK verification)β
test_place_order_returns_503_when_user_service_down (ConnectionError caught & mapped to 503)β
test_place_order_returns_504_when_user_service_times_out (Timeout caught & mapped to 504)
Stage 2 β Python Engineering Standards
π 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.
@dataclass(frozen=True) models (Money, ChargeRequest) with validation.
typing.Protocol contracts for gateways and repositories. Zero direct coupling.
πΉοΈ 2. Interactive Stage 2 Payment Service Console
Test business rule validation, idempotency deduplication, and error mapping in service_template.py:
test_money_valid & test_money_negative_or_zero_raises_validation_errorβ
test_config_defaults & test_config_from_env (12-Factor compliance)β
test_simulated_gateway_satisfies_payment_gateway_protocol (Protocol subtyping)β
test_execute_charge_idempotency_deduplication (Guarantees zero duplicate card charges)β
test_execute_charge_declined_raises_422 & test_execute_charge_gateway_downstream_error_raises_502β
test_service_lifespan_starts_and_stops_cleanly (Async lifecycle context manager)
Milestone 2 β Real Services, Databases & Inter-Service Communication
π 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.
/docs, and Depends(get_db) session management.
πΉοΈ 2. Interactive Milestone 2 Service Console
Test the live interaction between the Catalog Service (Port 8002) and Order Service (Port 8003):
test_catalog_health (Validates database connectivity)β
test_create_product_success & test_create_product_duplicate_sku_returns_409β
test_create_product_negative_price_fails_pydantic_validation (Pydantic v2 gt=0 constraint)β
test_list_products_paginated & test_get_nonexistent_product_returns_404β
test_reserve_stock_insufficient_inventory_returns_422 (Atomic inventory check)β
test_order_healthβ
test_create_order_success_with_data_snapshotting (Price & title saved locally; zero cross-DB joins)β
test_create_order_idempotency_deduplication (Replay returns 200 with cached order without double RPC)β
test_create_order_downstream_catalog_offline_returns_503 (Exponential backoff retry exhausted)β
test_create_order_downstream_timeout_returns_504 (Timeout guard triggers 504)
Milestone 3 β Asynchronous Event-Driven Messaging & JWT Identity
π 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.
order.created via background tasks. The customer receives their HTTP 201 response in milliseconds, without waiting for third-party email latency.
event_id to avoid double-processing. Poison messages fail 3 times and route safely to the Dead Letter Queue.
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:
security.py
event_bus.py
notification_service.py
secured_order_service.py
test_milestone3.py (12/12 passing β’ 100% test coverage)
Milestone 4 β Production Engineering, Docker, Chaos & Observability
π 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.
python:3.12-slim with an unprivileged appuser. Docker Compose wires catalog, orders, and workers on an isolated network.
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:
observability.py
chaos_and_contracts.py
production_service.py
Dockerfile & docker-compose.yml
test_milestone4.py (12/12 passing β’ 100% test coverage)
Milestone 5 β Unified API Gateway & Ingress Orchestration
π 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:
- 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.
- Single base URL
http://api.cloudshop.internal:8080for all clients. - Centralized Sliding Window Rate Limiter (60 req/min) protects backends.
- Automatic
X-Correlation-IDpropagation for end-to-end tracing. - Single
/healthz/gatewayendpoint audits entire cluster health in parallel.
πΊοΈ 2. Dynamic Reverse Proxy Ingress Routing
The Gateway dynamically dispatches requests across all microservices using non-blocking asynchronous streaming:
| Public Gateway Route (:8080) | Target Microservice | Internal Destination | Primary Capability |
|---|---|---|---|
/api/v1/identity/* |
Identity | http://127.0.0.1:8001/identity/* |
JWT auth, user registration, profiles |
/api/v1/catalog/* |
Catalog | http://127.0.0.1:8002/catalog/* |
Products, real-time stock reservations |
/api/v1/order/* |
Order | http://127.0.0.1:8003/order/* |
Checkout orchestration, idempotent orders |
/api/v1/notification/* |
Notification | http://127.0.0.1:8004/notification/* |
Event delivery, Dead Letter Queue (DLQ) |
/healthz/gateway |
Cluster Ingress | Aggregates all 4 services | Concurrent health sweep in <15ms |
π» 3. Implementation Blueprint: gateway.py
π§ͺ 4. Interactive Simulation & Ingress Testing
Test the live Gateway capabilities: reverse proxy routing, sliding window rate limiter, correlation tracking, and cluster health sweep:
test_gateway.py
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.
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.
STAGE 01
1. Core Microservices Overview
Client ingress, unified API Gateway routing, core business domains, and synchronous (REST/gRPC) vs asynchronous (Message Broker) traffic separation.
STAGE 02
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
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
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
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
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
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
8. Span Context & RPC Metadata
W3C TraceContext propagation across gRPC hops (`CurrencyService/Convert`), capturing custom business attributes (USD to CHF) and availability zones.
Microservices Architecture Studio & Simulation
1. Core Microservices Architecture Overview
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.
# 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()
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!
π Proceed to SECTION B: CloudShop 4 Services Studio βProject: 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.
Select a CloudShop Service to Inspect & View Microservice Code:
1. Product Service
Product catalogue, multi-attribute search, categories, stock levels, and product management UI.
π» View Python Microservice Code Expand Code βΌ
# 1. Product Service: FastAPI + Async Redis
@app.get("/api/v1/products")
async def list_products(category: str = None, page: int = 1):
cache_key = f"catalog:{category}:p{page}"
cached = await redis_client.get(cache_key)
if cached:
return json.loads(cached) # Sub-5ms hit
products = await db.fetch_all("SELECT * FROM products WHERE category = :c")
await redis_client.setex(cache_key, 300, json.dumps(products))
return products
2. Identity Service
User registration, login, JWT token issuance & verification, roles (Admin/Customer), and profile security.
π» View Python Microservice Code Expand Code βΌ
# 2. Identity Service: Argon2id + RS256 JWT
@app.post("/api/v1/auth/login")
async def login(credentials: LoginRequest):
user = await db.fetch_one("SELECT * FROM users WHERE email = :e", {"e": credentials.email})
if not user or not argon2.verify(credentials.password, user.password_hash):
raise HTTPException(401, "Invalid credentials")
token = jwt.encode({"sub": str(user.id), "role": user.role}, PRIVATE_KEY, "RS256")
return {"access_token": token, "token_type": "bearer"}
3. Order Service
Order creation, status workflow (Pending, In Transit, Fulfilled), and inter-service coordination.
π» View Python Microservice Code Expand Code βΌ
# 3. Order Service: Transactional Outbox Pattern
@app.post("/api/v1/orders")
async def checkout(order_data: OrderCreate, db: Session = Depends(get_db)):
with db.begin():
order = Order(user_id=order_data.user_id, status="PAID", total=order_data.total)
db.add(order)
db.flush()
# Atomic Outbox event ensures zero dual-write bugs
db.add(OutboxEvent(aggregate_id=order.id, event_type="OrderCreated", payload=json.dumps({"order_id": order.id})))
return {"order_id": order.id, "status": "CONFIRMED"}
4. Notification Service
Decoupled event worker consuming Order and Shipment queue events from RabbitMQ.
π» View Python Microservice Code Expand Code βΌ
# 4. Notification Service: RabbitMQ aio-pika Worker
async def process_order_event(message: aio_pika.IncomingMessage):
async with message.process():
event = json.loads(message.body.decode())
print(f"[*] Processing OrderCreated event for Order #{event['order_id']}")
await send_email_async(to=event['user_id'], order_id=event['order_id'])
CloudService Architecture Studio & Implementation
1. Product Service (FastAPI & Redis Caching)
Product catalogue lifecycle, category categorization, multi-attribute filtering (brand, rating, price range), stock availability read-probes, and sub-10ms response times via Redis caching.
GET /api/v1/productsβ Filterable paginated catalogGET /api/v1/products/{id}β Detailed spec & inventoryPOST /api/v1/productsβ Admin product insertion
# 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
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.
Early MVP stage, small engineering teams (1β4 developers), ACID transactions requiring single-database rollbacks, zero network RPC latency, and minimal operational 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.
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.
β Return to SECTION A: Architectural Blueprints (8 Stages)Unified API Gateway: The CloudShop Front Door
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.
1. Dynamic Route Mapping & Cluster Topology
(Port 8080)
β’ Rate Limiter (60/min)
β’ Correlation Tracing
πΉοΈ 2. Interactive Simulated API Gateway Console
Test the live reverse proxy dispatcher, rate limiter throttling, correlation ID auto-injection, and parallel cluster health aggregation:
gateway.py
test_gateway.py
pytest.ini
Python Microservices: Acceptance Audit & Learning Flowchart
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
:8001 & :8002. 12-Factor App environment configuration.
Idempotency-Key deduplication.
/healthz/live and /healthz/ready probes, Prometheus /metrics, multi-stage Dockerfile, and docker-compose orchestration.
:8005 behind the Gateway. Enable LLM tool-calling agents to query catalog and place orders via API.
β Real-World Scenario Assessment
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?
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?
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!
π 20-Point Production Acceptance Checklist
ποΈ 1. Architecture Audit (4 Checks)
β¨ 2. Code Quality Audit (4 Checks)
π 3. Security Audit (4 Checks)
π‘οΈ 4. Reliability & Resilience Audit (4 Checks)
π 5. Deployment & Ingress Audit (4 Checks)
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.
β Rate Track: Python Microservices & Distributed Architecture (1 to 5 Stars)
Your rating is stored directly in the database. Average: 4.9 / 5 (1 rating)