Reference library

Microservices patterns

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

5 matches
Microservices patterns easy

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.

bff aggregation microservices
Python
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…
13 0 Open
Microservices patterns medium

Distributed tracing with contextvars in Python

Propagate trace and span IDs across function calls using contextvars to mock distributed tracing in a single process.

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

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.

network-check mock microservices
Python
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
  …
14 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

Scatter Gather Aggregate Pattern in Python

Simulates a scatter/gather/aggregate pattern by distributing work across items, gathering results, and aggregating them.

scatter-gather aggregation pattern
Python
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 …
13 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.