System design patterns
Sharding, load balancing, CAP tradeoffs, and scaling patterns — interview and production ready.
Build a BFF (Backend for Frontend) Mock Aggregator in Python
A minimal HTTP server implementing the BFF pattern that aggregates user data and orders from two mock backends into a single JSON response.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
class MockBackendA:
def get_user(self, user_id):
return {"id": user_id, "name": "Alice", "service": "backend-a"}
class MockBackendB:
def get_orders(self, user_id):
return [
{…
Create a Data Helper Class in Python
A reusable DataHelper class that saves and loads JSON and CSV files from a configurable base directory, with automatic header detection for CSV.
import json
import csv
from pathlib import Path
class DataHelper:
def __init__(self, base_path="."):
self.base_path = Path(base_path)
self.base_path.mkdir(exist_ok=True)
def save_json(self, data, filename):
path = self.base_path / filename
with open(path, "w") as f:
…
Facade Pattern in Python with Mock Simplification
This code demonstrates the Facade pattern by hiding complex subsystem interactions behind a simple start/stop interface, and adds a MockFacade for testing failure scenarios.
class SubsystemA:
def operation_a(self):
return "Subsystem A: ready"
class SubsystemB:
def operation_b(self):
return "Subsystem B: ready"
class SubsystemC:
def operation_c(self):
return "Subsystem C: ready"
class Facade:
def __init__(self):
self._a = SubsystemA()
…
How to Aggregate Mock API Routes by Method in Python
Groups mock API routes by path and method, collecting response bodies and counts into a nested dictionary structure.
from collections import defaultdict
def aggregate_mock_routes(routes):
"""Aggregate mock API routes by method and aggregate their response bodies."""
aggregated = defaultdict(lambda: defaultdict(list))
for route in routes:
method = route["method"]
path = route["path"]
response = …
How to Apply the Clean Architecture Dependency Rule in Python
Demonstrates the dependency rule with a Protocol repository, a use case, and a presenter wired together at a composition root.
from dataclasses import dataclass
from typing import List, Protocol
class Repository(Protocol):
def get_items(self) -> List[str]:
...
@dataclass
class InMemoryRepository:
items: List[str]
def get_items(self) -> List[str]:
return self.items
class UseCase:
"""Application layer depends…
How to Build a Pipe and Filter Text Processing Chain in Python
A functional pipe-and-filter chain that transforms text through uppercase, whitespace normalization, number removal, stopword filtering, and file export.
import re
import sys
def pipe_filter_chain(stream):
def uppercase(text):
return text.upper()
def strip_whitespace(text):
return " ".join(text.split())
def remove_numbers(text):
return re.sub(r"\d+", "", text)
def remove_stopwords(text, stopwords={"the", "and", "of", "in"}):…
How to Build a Sidecar Logging Proxy in Python
Wrap any object with a proxy that transparently logs every method call, arguments, return value, and execution time to a file — mimicking a sidecar pattern.
import logging
import time
from datetime import datetime
class LoggingProxy:
"""Sidecar-style proxy that logs all calls to a wrapped object."""
def __init__(self, target, log_file="proxy.log"):
self._target = target
logging.basicConfig(
filename=log_file,
level=loggin…
How to Build a Simple Service Discovery Registry in Python
A lightweight in-memory service registry class using a dict — register, deregister, and discover services with host, port, and version.
class ServiceRegistry:
def __init__(self):
self._services = {}
def register(self, name, host, port, version="1.0"):
self._services[name] = {
"host": host,
"port": port,
"version": version
}
def deregister(self, name):
return self._servic…
How to Build a Weighted Random Load Balancer in Python
A Python load balancer mock that distributes requests across servers based on configurable weights using a cumulative weighted random selection algorithm.
import random
from collections import Counter
SERVERS = {
"server-a": 50,
"server-b": 30,
"server-c": 20,
}
def weighted_random_server(servers: dict[str, int]) -> str:
"""Select a server based on its weight (higher weight = more likely)."""
total_weight = sum(servers.values())
rand = random.…
How to Build an Adapter to Translate External API Responses in Python
Build an adapter class that translates a mock external API's response shape into your internal representation, keeping callers decoupled from the external contract.
import json
from typing import Dict, Any
class ExternalAPI:
"""Mock external service returning a different data shape."""
def get_user(self, user_id: int) -> Dict[str, Any]:
return {
"id": user_id,
"full_name": "Jane Doe",
"email_address": "jane@example.com",
…
How to Build an Anti-Corruption Layer in Python
Wrap a legacy system with a translation layer that converts awkward legacy data into a clean, modern DTO (Data Transfer Object) for use by new code.
class LegacyOrderSystem:
"""Legacy system with awkward, unstructured data."""
def get_order(self):
return {
"order_id": "ORD-123",
"cust": "Acme Corp",
"items": [{"sku": "A1", "qty": 2, "price_each": 10.0}],
"ship_to": "123 Main St, Springfield"
}…
How to Build an MVP Presenter View Mock in Python
A minimal MVP (Model-View-Presenter) mock showing a Presenter controlling a SlideDeck model with slide navigation and typed state via dataclasses.
from dataclasses import dataclass, field
from typing import List
@dataclass
class SlideDeck:
title: str
slides: List[str] = field(default_factory=list)
current_index: int = 0
def next_slide(self) -> str:
if self.current_index < len(self.slides) - 1:
self.current_index += 1
…
How to Implement CQRS with Separate Read and Write Models in Python
Implements Command Query Responsibility Segregation (CQRS) by splitting data into separate write and read models with dedicated repositories, using dataclasses for structure.
from dataclasses import dataclass, field
from typing import List, Dict, Optional
@dataclass
class OrderWriteModel:
order_id: int
customer: str
items: List[str] = field(default_factory=list)
def add_item(self, item: str) -> None:
self.items.append(item)
@dataclass
class OrderReadModel:
…
How to Implement Retry with Exponential Backoff and Jitter in Python
This code demonstrates a retry mechanism with exponential backoff and optional full jitter, using a flaky mock network call for testing.
import random
import time
def retry_with_backoff(func, max_attempts=5, base_delay=0.1, jitter=True):
"""
Retry a function with exponential backoff and optional full jitter.
"""
for attempt in range(max_attempts):
try:
return func()
except Exception as e:
if att…
How to Implement a Simple MVVM Binding Mock in Python
A minimal Python implementation of the MVVM pattern, mocking data binding so views auto-update when the view model changes.
class BindingMock:
def __init__(self, view_model):
self.view_model = view_model
self.subscribers = []
def bind(self, property_name, callback):
self.subscribers.append((property_name, callback))
def set(self, property_name, value):
setattr(self.view_model, property_name, va…
How to Implement the Flyweight Pattern in Python
Implements the Flyweight design pattern to share immutable intrinsic state (character + font) across many document objects, reducing memory usage.
class Character:
"""Flyweight - stores only intrinsic state (shared)."""
def __init__(self, char: str, font: str):
self.char = char
self.font = font
def render(self, size: int) -> str:
return f"{self.char}_{self.font}_{size}"
class CharacterFactory:
"""Flyweight factory - ma…
How to Implement the Repository Pattern in Python with an In-Memory Dict
Stores, retrieves, updates, and deletes user records in memory using a Repository abstraction over a plain dict, isolating data access from business logic.
class UserRepository:
def __init__(self):
self._storage = {}
self._next_id = 1
def create(self, name, email):
user_id = self._next_id
self._next_id += 1
self._storage[user_id] = {"id": user_id, "name": name, "email": email}
return self._storage[user_id]
def…
How to Migrate a Legacy Facade with the Strangler Fig Pattern in Python
Use a facade to wrap a legacy API and incrementally migrate callers to a modern interface, following the strangler fig pattern.
class LegacyAPI:
"""Simulates the legacy system's raw interface."""
def get_user(self, user_id):
return {"id": user_id, "name": "Alice", "legacy": True}
class UserService:
"""Facade that wraps the legacy system with a modern interface."""
def __init__(self, legacy_api=None):
self.lega…
How to Mock Hexagonal Architecture Ports and Adapters in Python
Mock an email adapter in a hexagonal architecture with unittest.mock to test business logic in isolation.
from unittest.mock import Mock
class EmailService:
def send(self, recipient, message):
raise NotImplementedError
class OrderProcessor:
def __init__(self, email_service):
self.email_service = email_service
def process_order(self, order_id, customer_email):
# Business logic
…
How to Mock a Metrics Decorator in Python with unittest.mock
This code demonstrates a timing decorator that wraps a function to measure execution time and prints the duration, with a unit test using unittest.mock to patch the print function and assert it was called.
import time
from functools import wraps
from unittest.mock import patch
def add_metrics(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.6f}s…
How to Structure a Three-Tier Layered Architecture in Python
A mock three-tier architecture with presentation, business, and data layers that process a user request from input to response.
class PresentationLayer:
def __init__(self, business_layer):
self.business = business_layer
def handle_request(self, user_id):
print(f"[Presentation] Received request for user {user_id}")
data = self.business.process_user(user_id)
print(f"[Presentation] Response: {data}")
…
How to Take Periodic Snapshots of Aggregate State in Python
Build a Python class that accumulates values and periodically captures immutable snapshots of total, count, and average for later analysis.
import time
import random
from collections import defaultdict
class SnapshotAggregator:
def __init__(self):
self.total = 0
self.count = 0
self.history = []
def add(self, value):
self.total += value
self.count += 1
def snapshot(self):
avg = self.total / se…
How to implement saga orchestration with compensating steps in Python
Orchestrate a distributed transaction across services, rolling back completed steps with compensations when a later step fails.
class InventoryService:
def reserve(self, order_id):
print(f"[Inventory] Reserving stock for order {order_id}")
return True
def compensate(self, order_id):
print(f"[Inventory] Releasing stock for order {order_id}")
class PaymentService:
def charge(self, order_id):
print(f…
How to mock the domain center in an onion architecture in Python
Define a repository interface and an in-memory mock to test domain services without touching infrastructure.
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, List, Optional
@dataclass
class Order:
id: int
customer: str
items: List[str]
total: float
class OrderRepository(ABC):
@abstractmethod
def find_by_id(self, order_id: int) -> Optional[Order]:
…
Browse by section
Each section groups closely related Python snippets.
System design patterns — Python code examples
What you will find here
This page collects system design 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.