Microservices patterns
Service boundaries, discovery, inter-service calls, and decomposition patterns.
BFF aggregation pattern: combine multiple service responses in Python
Mock three backend services and aggregate their responses into one unified payload — the BFF pattern every Python microservice gateway relies on.
from dataclasses import dataclass
from typing import Any
@dataclass
class Service:
name: str
data: dict[str, Any]
def get_user_service() -> Service:
return Service("user", {"id": 1, "name": "Alice"})
def get_orders_service() -> Service:
return Service("orders", {"total": 299.99, "count": 2})
de…
Correlation ID HTTP header mock in Python
A lightweight HTTP server that echoes or generates correlation IDs to help test distributed systems.
import json
import uuid
from http.server import BaseHTTPRequestHandler, HTTPServer
class CorrelationHandler(BaseHTTPRequestHandler):
CORRELATION_HEADER = "X-Correlation-ID"
def do_GET(self):
correlation_id = self.headers.get(self.CORRELATION_HEADER) or str(uuid.uuid4())
response = {
…
How to Build a Health Check Service Registry in Python
Build a minimal Python service registry that handles registration, deregistration, health checks, and service listing in one simple class.
import random
import time
class ServiceRegistry:
def __init__(self):
self.services = {}
def register(self, name, address):
self.services[name] = {
"address": address,
"status": "healthy",
"registered_at": time.time(),
"checks": 0
}
…
How to Build a Microservice Helper in Python
A beginner-friendly Python helper that validates input, normalizes service responses, and simulates user management—showing clean patterns for microservice development.
import json
from typing import Any, Dict, List
class DataValidator:
"""Simple validator for common data patterns."""
@staticmethod
def is_valid_email(value: str) -> bool:
"""Check if value looks like an email."""
return "@" in value and "." in value.split("@")[-1]
@staticmethod
…
How to Compose Parallel API Calls in Python with asyncio.gather
Compose multiple mock API responses in parallel using asyncio.gather with per-service simulated latency.
import asyncio
import random
import time
async def mock_api(name: str, delay: float) -> dict:
await asyncio.sleep(delay)
return {"service": name, "value": random.randint(1, 100)}
async def fetch_all():
services = {
"users": mock_api("users", 0.2),
"orders": mock_api("orders", 0.3),
…
How to Deduplicate Events in Python with SHA256 Hashing
Build an event deduplicator that identifies duplicate inbox messages using SHA256 hashes and tracks duplicate counts per event type.
```python
import hashlib
import json
from collections import defaultdict
class EventDeduplicator:
def __init__(self):
self.seen_hashes = set()
self.duplicate_counts = defaultdict(int)
def process_event(self, event):
event_key = f"{event['event_id']}:{event['timestamp']}"
even…
How to Implement a Data Helper for Microservices in Python
Create a reusable helper class to serialize, deserialize, and wrap data for microservice communication using dataclasses and JSON.
import json
from dataclasses import dataclass, asdict
from typing import Any, Dict, List
@dataclass
class ServiceResponse:
status: str
data: Any
message: str = ""
class DataHelper:
"""Simple helper for microservice data handling."""
@staticmethod
def serialize(data: Dict[str, Any]) -> str:…
How to Implement an Exactly-Once Deduplication Store in Python
Implement a Python class that deduplicates keys exactly once, tracking first-seen timestamps and duplicate counts.
from datetime import datetime
from typing import Any, Hashable
class ExactlyOnceStore:
def __init__(self) -> None:
self._seen: set[Hashable] = set()
self._first_seen: dict[Hashable, datetime] = {}
self._counts: dict[Hashable, int] = {}
def add(self, key: Hashable, value: Any = None) …
How to Mock Eventual Consistency UI Notes in Python
Simulates a UI note that shows local state until a pending server update is confirmed, mocking eventual consistency behavior in distributed systems.
class EventualConsistencyNote:
def __init__(self, entity_id, note):
self.entity_id = entity_id
self.note = note
self.confirmed = False
self.pending_updates = []
def add_pending_update(self, update):
self.pending_updates.append(update)
def confirm_update(self):
…
How to Mock Service Versioning URI in Python
Run a minimal HTTP server in Python that routes requests to different versions of a service URI like /v1/users vs /v2/users.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class VersionedHandler(BaseHTTPRequestHandler):
def _send_json(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
…
How to Mock a GraphQL Backend in Python
Create an in-memory GraphQL mock backend using dataclasses and resolver methods returning plain dictionaries.
from dataclasses import dataclass, asdict
from typing import Any, Dict, List
@dataclass
class Product:
id: int
name: str
price: float
@dataclass
class User:
id: int
username: str
class MockGraphQLBackend:
def __init__(self) -> None:
self.products = [
Product(id=1, name…
How to Mock a Schema Registry Avro Record in Python
Encode a Python dict into Avro binary using an inline schema, mimicking a schema registry record for tests or mocks.
import io
from avro.schema import parse
from avro.io import DatumWriter, BinaryEncoder
schema_json = """
{
"type": "record",
"name": "User",
"fields": [
{"name": "name", "type": "string"},
{"name": "age", "type": "int"},
{"name": "email", "type": ["null", "string"], "default": null}
]
}
"""
schem…
How to Mock a Server-Side Load Balancer in Python
A simple Python class that mimics a server-side load balancer with round-robin, random, and least-connections selection strategies.
import itertools
import random
class LoadBalancer:
def __init__(self, servers=None):
self.servers = servers if servers else ["server1", "server2", "server3"]
self.counter = itertools.count(1)
def round_robin(self):
return next(self.counter) % len(self.servers)
def random_selectio…
How to Mock a Service Mesh Sidecar Proxy in Python
Simulate a service mesh sidecar proxy with route registration, service discovery, and request proxying using a simple Python class.
class SidecarProxy:
def __init__(self, name):
self.name = name
self.routes = {}
self.services = {}
self.requests_processed = 0
def register_service(self, service_name, address, port):
self.services[service_name] = f"{address}:{port}"
def add_route(self, path, servi…
How to Mock a Service Registry in Python with an In-Memory Dict
A lightweight ServiceRegistry class backed by a dict, exposing register, unregister, lookup, list, and health-check methods.
class ServiceRegistry:
def __init__(self):
self._services = {}
def register(self, name, endpoint, version="1.0"):
self._services[name] = {
"endpoint": endpoint,
"version": version,
"status": "healthy"
}
def unregister(self, name):
return…
How to Order Partition Key Events in Python (Mock Stream)
Generate a mock event stream grouped by partition key and sort it deterministically by key then sequence in Python.
import itertools
import random
def partition_key_events(keys, events_per_key=3, seed=None):
"""Produce a realistic-looking, but mock, event stream grouped by partition key.
Args:
keys: iterable of partition keys (e.g. strings or ints).
events_per_key: how many events we want per key.
…
How to mock an external service in Python with an anti-corruption facade
This code implements an anti-corruption facade that mocks an external API, allowing client code to interact with a simulated service while keeping the same interface.
class AntiCorruptionFacade:
"""Mocks a real API while keeping the same interface."""
def __init__(self, data_store):
self._data_store = data_store
self._calls = []
def get_user(self, user_id):
self._calls.append(f"get_user({user_id})")
return self._data_store.get(u…
Retry idempotent GET requests in Python
A Python function that retries an idempotent GET request a fixed number of times with a delay between attempts, raising a RuntimeError only after all retries fail.
import time
import urllib.error
import urllib.request
from http.client import HTTPException
def fetch_with_retry(url, max_retries=3, delay=1.0):
for attempt in range(1, max_retries + 1):
try:
with urllib.request.urlopen(url, timeout=5) as response:
return response.read().decode…
Scatter Gather Aggregate Pattern in Python
Simulates a scatter/gather/aggregate pattern by distributing work across items, gathering results, and aggregating them.
import random
def process_items(items, scatter_fn, gather_fn, aggregate_fn):
"""Simple scatter/gather/aggregate pattern simulation."""
scattered = [scatter_fn(item) for item in items]
gathered = [gather_fn(item) for item in scattered]
return aggregate_fn(gathered)
if __name__ == "__main__":
data …
Strangler Fig Migration Pattern in Python
Gradually reroute calls from a legacy service to a modern replacement using a runtime switch and feature detection.
from dataclasses import dataclass
@dataclass
class PaymentService:
def process(self, amount: float) -> str:
return f"Legacy processed ${amount:.2f}"
class StranglerFig:
def __init__(self):
self._new_service = None
def attach_new(self, service):
self._new_service = service
de…
Browse by section
Each section groups closely related Python snippets.
Microservices patterns — Python code examples
What you will find here
This page collects microservices patterns snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.