Reference library

Microservices patterns

Service boundaries, discovery, inter-service calls, and decomposition patterns.

34 matches
Microservices patterns easy

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.

ambassador mock http-server
Python
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…
13 0 Open
Microservices patterns medium

How to Mock mTLS Between Services in Python

Simulate mutual TLS authentication between two services using Python's ssl module with self-signed certificates.

mtls ssl security
Python
import ssl
import socket
import threading
import tempfile
from pathlib import Path
import subprocess

def create_test_cert(cert_path: Path, key_path: Path, common_name: str = "localhost"):
    """Generate a self-signed certificate using openssl."""
    subprocess.run([
        "openssl", "req", "-x509", "-newkey", "rs…
15 0 Open
Microservices patterns easy

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.

partition events sorting
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.
       …
11 0 Open
Microservices patterns easy

How to Use the Adapter Pattern to Mock a Legacy System in Python

This code demonstrates the Adapter pattern, allowing a modern interface to interact with a legacy system by wrapping its outdated method.

adapter-pattern design-patterns legacy
Python
class LegacySystem:
    def legacy_method(self, data):
        return f"Legacy processed: {data}"

class ModernInterface:
    def process(self, data):
        raise NotImplementedError

class Adapter(ModernInterface):
    def __init__(self, legacy):
        self.legacy = legacy

    def process(self, data):
        re…
13 0 Open
Microservices patterns medium

How to implement a circuit breaker in Python

A Python CircuitBreaker class that tracks failures, opens after a threshold, and retries after a timeout.

circuit-breaker resilience microservices
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3, timeout=5):
        self.failure_threshold = failure_threshold
        self.timeout = timeout
        self.failure_count = 0
        self.last_failure_time = None
        self.state = "CLOSED"

    def call(self, mock_downstream):
        if self.state …
13 0 Open
Microservices patterns easy

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.

sticky-routing microservices routing
Python
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…
13 0 Open
Microservices patterns easy

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.

load balancing round robin microservices
Python
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
       …
14 0 Open
Microservices patterns medium

How to implement the Database per service pattern in Python

Simulate separate databases per microservice in Python using dataclasses and in-memory dictionaries, showing how services own their data independently.

microservices database-per-service dataclasses
Python
import json
from dataclasses import dataclass, asdict
from typing import Dict, List


@dataclass
class User:
    id: int
    name: str
    email: str


@dataclass
class Order:
    id: int
    user_id: int
    product: str
    amount: float


class UserServiceDB:
    """Simulates a separate database for the User servic…
12 0 Open
Microservices patterns easy

How to mock a SPIFFE workload identity in Python

Generate a mock SPIFFE ID and token for a workload using a trust domain, namespace, and service account.

spiffe identity microservices
Python
import hashlib
import json
from dataclasses import dataclass, asdict


@dataclass
class SPIFFEIdentity:
    trust_domain: str
    namespace: str
    service_account: str

    @property
    def id(self) -> str:
        return f"spiffe://{self.trust_domain}/ns/{self.namespace}/sa/{self.service_account}"


def mock_workl…
13 0 Open
Microservices patterns easy

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.

microservices testing mocking
Python
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…
11 0 Open

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.