Reference library

System design patterns

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

11 matches
System design patterns medium

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.

facade-pattern design-patterns abstraction
Python
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()
   …
15 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 medium

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.

anti-corruption-layer ddd dto
Python
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"
        }…
15 0 Open
System design patterns easy

How to Build an Append-Only Event Store in Python

Implement a simple append-only event store class that stores events in a list and supports retrieval by index range.

event-sourcing append-only event-store
Python
class EventStore:
    def __init__(self):
        self._events = []

    def append(self, event):
        """Append an event to the store."""
        self._events.append(event)

    def get_events(self, start=0, end=None):
        """Return events from start index to end (exclusive)."""
        return self._events[sta…
14 0 Open
System design patterns easy

How to Implement a Data Helper Class in Python

Build a beginner-friendly DataHelper class using dataclasses and key system design patterns like Command, Strategy, and Map.

dataclass data-helper design-patterns
Python
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


@dataclass
class DataHelper:
    """A beginner-friendly data utility with common system design patterns."""
    data: List[Dict[str, Any]] = field(default_factory=list)

    def add_record(self, r…
13 0 Open
System design patterns medium

How to Implement the Abstract Factory Pattern in Python

Implements the Abstract Factory pattern to create families of related GUI objects (buttons, checkboxes) without specifying their concrete classes.

abstract-factory design-patterns system-design
Python
from abc import ABC, abstractmethod


class Button(ABC):
    @abstractmethod
    def render(self):
        pass


class Checkbox(ABC):
    @abstractmethod
    def render(self):
        pass


class WindowsButton(Button):
    def render(self):
        return "Rendering Windows-style button"


class WindowsCheckbox(Chec…
13 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 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.

aggregation snapshots state-management
Python
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…
13 0 Open
System design patterns medium

Implement a Consistent Hash Ring in Python

Build a minimal consistent hash ring with virtual nodes to map keys to servers stably as nodes are added or removed.

consistent-hashing hashing distributed-systems
Python
import hashlib
import bisect


class ConsistentHashRing:
    def __init__(self, nodes=None, replicas=3):
        self.replicas = replicas
        self.ring = {}
        self.sorted_keys = []
        if nodes:
            for node in nodes:
                self.add_node(node)

    def _hash(self, key):
        return i…
15 0 Open
System design patterns easy

Round Robin Load Balancer in Python

This code simulates round robin load balancing by distributing a list of requests evenly across a list of servers.

load-balancing round-robin system-design
Python
def round_robin_servers(requests: list[str], servers: list[str]) -> dict[str, list[str]]:
    assignments = {server: [] for server in servers}
    for idx, request in enumerate(requests):
        server = servers[idx % len(servers)]
        assignments[server].append(request)
    return assignments


if __name__ == "_…
13 0 Open
System design patterns medium

Simulate a Leaky Bucket Rate Limiter in Python

This code implements a leaky bucket rate limiter that drains at a fixed rate and accepts or rejects incoming requests based on capacity.

rate limiting leaky bucket simulation
Python
import time
from collections import deque


class LeakyBucket:
    """Simulates a leaky bucket rate limiter with a fixed drain rate."""
    def __init__(self, capacity, drain_rate_per_sec):
        self.capacity = capacity
        self.drain_rate = drain_rate_per_sec
        self.water = 0.0
        self.last_refill =…
13 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.