Reference library

Microservices patterns

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

6 matches
Microservices patterns easy

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.

caching microservices cache-aside
Python
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…
12 0 Open
Microservices patterns easy

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.

event-sourcing microservices mock
Python
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…
14 0 Open
Microservices patterns easy

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.

service-registry microservices in-memory
Python
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]

 …
14 0 Open
Microservices patterns easy

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.

outbox domain-events microservices
Python
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 =…
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 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

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.