Reference library

System design patterns

Sharding, load balancing, CAP tradeoffs, and scaling patterns — interview and production ready.

10 matches
System design patterns easy

Builder pattern for mocking complex objects in Python

Use a fluent Builder to construct realistic mock objects with defaults, enabling readable test data setup.

builder-pattern mock-data testing
Python
class User:
    def __init__(self):
        self.name = "default"
        self.age = 0
        self.email = "unknown@example.com"
        self.address = "unknown"

    def __repr__(self):
        return f"User(name={self.name!r}, age={self.age}, email={self.email!r}, address={self.address!r})"


class UserBuilder:
   …
16 0 Open
System design patterns easy

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.

defaultdict api-gateway aggregation
Python
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 = …
13 0 Open
System design patterns easy

How to Build a Health Check System with Instance Up and Down Status in Python

Track instance health by marking them up or down and simulating health checks with a mock class in Python.

health-check monitoring system-design
Python
from datetime import datetime
import random

class HealthChecker:
    def __init__(self):
        self.status = {}
    
    def mark_up(self, instance_id):
        self.status[instance_id] = {
            "state": "up",
            "last_check": datetime.now().isoformat(),
            "healthy": True
        }
    
  …
14 0 Open
System design patterns easy

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.

python how build
Python
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.…
13 0 Open
System design patterns easy

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.

dataclasses mvp design-patterns
Python
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
      …
13 0 Open
System design patterns easy

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.

hexagonal-architecture unittest-mock dependency-injection
Python
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
   …
15 0 Open
System design patterns easy

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.

decorators unittest.mock metrics
Python
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…
15 0 Open
System design patterns easy

How to Mock the Ambassador Pattern Retry Client in Python

This code demonstrates the ambassador pattern for API clients by simulating a flaky request and retrying with exponential backoff, useful for testing resilience in system design.

retry ambassador-pattern mock
Python
import time
import random


class RetryingClient:
    """Retry wrapper simulating a flaky ambassador-style API client."""

    def __init__(self, max_attempts=3, base_delay=0.1):
        self.max_attempts = max_attempts
        self.base_delay = base_delay
        self.attempts = 0

    def _flaky_request(self):
     …
15 0 Open
System design patterns easy

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.

onion-architecture repository-pattern dependency-injection
Python
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]:
     …
11 0 Open
System design patterns easy

Observer Pattern with Mock Metrics in Python

Implement the Observer pattern with a mock metrics collector to track state changes and verify notifications.

observer mock design pattern
Python
import unittest
from unittest.mock import Mock


class Subject:
    def __init__(self):
        self._state = 0
        self._observers = []

    def attach(self, observer):
        self._observers.append(observer)

    def set_state(self, value):
        if value != self._state:
            self._state = value
      …
12 0 Open

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.