Reference library

Microservices patterns

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

49 matches
Microservices patterns easy

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.

eventual-consistency microservices ui
Python
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):
    …
17 0 Open
Microservices patterns medium

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.

microservices testing timeout
Python
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)…
16 0 Open
Microservices patterns easy

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.

http-server versioning mock
Python
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")
    …
11 0 Open
Microservices patterns medium

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.

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

How to Mock a GraphQL Backend in Python

Create an in-memory GraphQL mock backend using dataclasses and resolver methods returning plain dictionaries.

graphql mock dataclasses
Python
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…
15 0 Open
Microservices patterns easy

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.

load-balancer microservices simulation
Python
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…
13 0 Open
Microservices patterns easy

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.

sidecar-proxy service-mesh microservices
Python
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…
14 0 Open
Microservices patterns easy

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.

microservices service-registry dictionary
Python
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…
13 0 Open
Microservices patterns easy

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.

api-gateway mock-server http
Python
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}…
14 0 Open
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 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
Microservices patterns easy

Idempotent Consumer Event Processing in Python

Track processed event IDs to skip duplicates and count event types for a reliable, idempotent consumer.

idempotency events microservices
Python
import json
from collections import defaultdict

class EventProcessor:
    def __init__(self):
        self.processed_ids = set()
        self.counts = defaultdict(int)

    def process_event(self, event):
        event_id = event["id"]
        if event_id in self.processed_ids:
            return {"status": "skipped"…
13 0 Open
Microservices patterns medium

JWT Service-to-Service Authentication Mock in Python

Create and verify HS256 JWTs for service-to-service authentication without external libraries.

jwt authentication hmac
Python
import hashlib
import hmac
import base64
import json
import time


class JWTMock:
    """Minimal JWT service-to-service mock using HS256."""
    
    def __init__(self, secret):
        self.secret = secret.encode()
    
    @staticmethod
    def _b64url_encode(data):
        return base64.urlsafe_b64encode(data).rstr…
14 0 Open
Microservices patterns easy

Mock a Sidecar Logger with Python Metrics

Simulate a sidecar logger that tracks request counts, error rates, and endpoint hits, producing a metrics snapshot.

microservices monitoring metrics
Python
import random
import time
from collections import defaultdict


class SidecarLogger:
    def __init__(self):
        self.metrics = defaultdict(int)
        self.total_requests = 0
        self.error_count = 0

    def log_request(self, endpoint, status_code):
        """Simulate logging a request and updating metrics…
16 0 Open
Microservices patterns medium

Python Saga Compensating Steps Mock

Mock a distributed transaction saga with forward steps and compensating actions that reverse partial progress on failure.

saga microservices compensation
Python
from datetime import datetime


def make_payment(user_id, amount):
    print(f"[{datetime.now():%H:%M:%S}] Payment of ${amount} processed for user {user_id}")
    return {"step": "payment", "status": "ok", "details": f"${amount} charged"}


def deduct_inventory(order_id, items):
    print(f"[{datetime.now():%H:%M:%S}]…
14 0 Open
Microservices patterns medium

Saga pattern orchestration with rollback in Python

Orchestrate a distributed transaction with Saga steps and automated compensation rollback on failure.

saga microservices transaction
Python
import time
import random


class SagaStep:
    def __init__(self, name):
        self.name = name
        self.executed = False

    def execute(self):
        print(f"Executing {self.name}...")
        time.sleep(0.2)
        if random.random() < 0.3:
            raise RuntimeError(f"{self.name} failed")
        sel…
14 0 Open
Microservices patterns easy

Strangler Fig Migration Pattern in Python

Gradually reroute calls from a legacy service to a modern replacement using a runtime switch and feature detection.

migration facade microservices
Python
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…
14 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.