Microservices patterns
Service boundaries, discovery, inter-service calls, and decomposition patterns.
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 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 an API Gateway Router in Python
Create a lightweight HTTP server that routes requests to mock microservice responses, simulating an API gateway for local development and testing.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class SimpleGateway(BaseHTTPRequestHandler):
def do_GET(self):
routes = {
"/users": {"service": "user-service", "status": "ok", "count": 42},
"/orders": {"service": "order-service", "status": "ok", "count": 17}…
How to Mock an Ambassador Edge Proxy in Python
Build a lightweight mock Ambassador edge proxy with Python's http.server that responds to health and user endpoint requests for local development and testing.
import http.server
import json
import urllib.parse
import threading
class AmbassadorProxyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
if parsed.path == "/health":
self.send_response(200)
self.send_header("Content-T…
How to implement read-your-writes sticky routing in Python
A mock StickyRouter class that routes all requests for the same key to the same node, ensuring read-after-write consistency.
import random
class StickyRouter:
def __init__(self, nodes):
self.nodes = nodes
self.routes = {}
def route(self, key):
if key not in self.routes:
self.routes[key] = random.choice(self.nodes)
return self.routes[key]
def read(self, key):
node = self.rout…
How to implement round-robin load balancing in Python
Implement a client-side round-robin load balancer that distributes requests sequentially across a list of mock servers using itertools.cycle.
import itertools
import random
class MockServer:
def __init__(self, name):
self.name = name
def handle_request(self, request_id):
return f"Server {self.name} handled request #{request_id}"
class RoundRobinLoadBalancer:
def __init__(self, servers):
self.servers = servers
…
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…
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.