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…
Backward Compatible Schema Evolution in Python
A mock schema validator that evolves JSON schemas while preserving backward compatibility by keeping old fields and validating required ones.
import json
from copy import deepcopy
class SchemaValidator:
def __init__(self, schema):
self.schema = schema
def evolve(self, new_schema):
"""Evolve mock schema while keeping backward compatibility."""
for field in self.schema:
if field not in new_schema:
…
Bulkhead Thread Pool per Service Mock in Python
Simulates a bulkhead pattern with per-service thread pools and semaphore-based rejection to isolate failures between dependent services.
import threading
import time
import random
from concurrent.futures import ThreadPoolExecutor
class ServiceBulkhead:
def __init__(self, name, max_threads, max_queue):
self.name = name
self.executor = ThreadPoolExecutor(max_workers=max_threads)
self.semaphore = threading.Semaphore(max_thread…
Cache-Aside Pattern in Python: Per-Service Mock
A Python mock of the cache-aside pattern for a single microservice—lazy-load from a database into an in-memory cache and invalidate on updates.
class ServiceCache:
def __init__(self):
self.database = {"user:1": "Alice", "user:2": "Bob", "user:3": "Charlie"}
self.cache = {}
def get_user(self, user_id):
cache_key = f"user:{user_id}"
if cache_key in self.cache:
print(f"CACHE HIT: {cache_key}")
retu…
Consumer Driven Contract Pact Mock in Python
Define and verify consumer-driven contracts using Pact's Consumer and Provider classes, mocking the provider to assert expected interactions.
from pact import Consumer, Provider
pact = Consumer('OrderService').has_pact_with(Provider('InventoryService'))
@Pact.verify()
class TestInventoryContract:
def test_get_inventory(self):
expected = {"item": "widget", "quantity": 100}
(pact
.given('inventory exists for widget')
.u…
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 = {
…
Distributed tracing with contextvars in Python
Propagate trace and span IDs across function calls using contextvars to mock distributed tracing in a single process.
import contextvars
import uuid
import time
_trace_context = contextvars.ContextVar("trace_context", default=None)
class TraceContext:
def __init__(self, trace_id, parent_span_id):
self.trace_id = trace_id
self.parent_span_id = parent_span_id
self.span_id = uuid.uuid4().hex[:16]
s…
Event Sourcing Store in Python: Append-Only Log Mock
Mock an append-only event store in Python — record events, list them, and fetch by ID using a simple list-backed class.
class EventStore:
def __init__(self):
self._events = []
def append(self, event):
event_id = len(self._events) + 1
stored_event = {"id": event_id, "data": event}
self._events.append(stored_event)
return stored_event
def get_events(self):
return list(self._ev…
Fallback cached response mock in Python
Wraps a mock function with a fallback to a real service and caches results to mask transient failures.
import time
from functools import wraps
class CachedMock:
def __init__(self, cache_ttl=5):
self.cache = {}
self.cache_ttl = cache_ttl
def get(self, key):
cached = self.cache.get(key)
if cached and time.time() - cached["timestamp"] < self.cache_ttl:
return cached["v…
How to Build an In-Memory Service Registry Mock in Python
A simple in-memory ServiceRegistry class to register, retrieve, list, and unregister microservice endpoints or configs using a dict, with KeyError guards.
class ServiceRegistry:
def __init__(self):
self._services = {}
def register(self, name, service):
self._services[name] = service
def unregister(self, name):
if name not in self._services:
raise KeyError(f"Service '{name}' not found")
del self._services[name]
…
How to Build an OAuth Client Credentials Mock Server in Python
A minimal HTTP mock server implementing the OAuth 2.0 client credentials grant for local testing and microservice development.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
TOKENS = {"valid_token": "demo_access_token", "client_id": "my_service"}
class OAuthHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path == "/oauth/token":
length = int(self.headers.get("Content-Length", 0))
…
How to Check an External Gateway vs Use an Internal Mock in Python
This code checks whether an external network gateway is reachable using ping, then falls back to a deterministic internal mock for testing environments.
import subprocess
import sys
def check_external_gateway():
"""True if we can reach an external network target."""
try:
subprocess.run(
["ping", "-c", "1", "-W", "2", "8.8.8.8"],
capture_output=True,
timeout=3,
check=True,
)
return True
…
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 Implement a Two-Phase Commit Mock in Python
Simulate a distributed two-phase commit with prepare, commit, and abort phases, including deterministic failure injection for testing.
import random
from dataclasses import dataclass
from typing import Dict, List, Optional
@dataclass
class Transaction:
tx_id: int
data: Dict[str, str]
class TwoPhaseCommitMock:
"""Simple two-phase commit mock with prepare and commit phases."""
def __init__(self) -> None:
self.prepared: List…
How to Implement an Outbox Pattern Mock in Python
This code demonstrates a simple in-memory outbox pattern mock for publishing domain events and tracking pending events until they are marked as published.
from dataclasses import dataclass, field
from datetime import datetime
from uuid import uuid4
@dataclass
class DomainEvent:
event_id: str = field(default_factory=lambda: str(uuid4()))
occurred_at: datetime = field(default_factory=datetime.utcnow)
class Outbox:
def __init__(self):
self._events =…
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 Call Timeouts in Python
Simulate service calls with configurable timeouts using Mock to patch sleep and randomness, covering success and timeout cases.
import time
from unittest.mock import Mock, patch
# Simulate a service call with configurable timeout
def call_service(service_name, timeout=5):
"""Mock a service call that may time out."""
start = time.time()
print(f"Calling {service_name}...")
# Simulate service latency (randomized for realism)…
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 Choreography Saga in Python
Simulate a choreography-based saga with event envelopes, status tracking, and compensating actions to model distributed transactions.
import json
from dataclasses import dataclass, asdict
from typing import List, Optional
from enum import Enum
class SagaStatus(Enum):
PENDING = "PENDING"
COMPLETING = "COMPLETING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
@dataclass
class EventEnvelope:
event_type: str
order_id: str
sta…
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…
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.