Reference library

System design patterns

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

9 matches
System design patterns medium

Circuit Breaker Pattern in Python: Closed, Open, and Half-Open States

Implement a circuit breaker with closed, open, and half-open states to prevent repeated calls to failing services and allow recovery after a timeout.

circuit-breaker resilience fault-tolerance
Python
class CircuitBreaker:
    def __init__(self, failure_threshold=3, timeout_seconds=5):
        self.failure_threshold = failure_threshold
        self.timeout_seconds = timeout_seconds
        self.state = "closed"
        self.failure_count = 0
        self.last_failure_time = None

    def record_success(self):
     …
14 0 Open
System design patterns medium

Domain Driven Design Aggregate Root Example in Python

Model an Order as an aggregate root with invariants enforced through methods, demonstrating DDD principles in Python.

ddd aggregate-root object-oriented
Python
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional
from uuid import uuid4


class Money:
    def __init__(self, amount: float, currency: str = "USD"):
        self.amount = amount
        self.currency = currency

    def __add__(self, other: Money) -> Money:
       …
12 0 Open
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 medium

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.

pipeline text-processing functional
Python
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"}):…
16 0 Open
System design patterns medium

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.

saga distributed-transactions compensation
Python
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…
14 0 Open
System design patterns medium

How to implement stale-while-revalidate caching in Python

A Python cache wrapper that returns a stale cached value with a fallback flag when the upstream fetch fails, using TTL-based freshness checks.

caching ttl resilience
Python
import time
from functools import lru_cache


class CachedService:
    def __init__(self, fetch_func, ttl=5):
        self.fetch_func = fetch_func
        self.ttl = ttl
        self._cache = {}
        self._timestamp = {}

    def get(self, key):
        now = time.time()
        if key in self._cache and now - self…
12 0 Open
System design patterns medium

Implement Bulkhead Thread Pool Isolation in Python

Create isolated thread pools with a bulkhead pattern to protect different services from cascading failures.

bulkhead threadpool concurrency
Python
import threading
import time
import random
from concurrent.futures import ThreadPoolExecutor


class Bulkhead:
    """Simple bulkhead isolation: separate thread pools for different tasks."""

    def __init__(self, max_workers):
        self.executor = ThreadPoolExecutor(max_workers=max_workers)
        self.active = …
13 0 Open
System design patterns medium

Mock Unit of Work commit and rollback in Python

Verify that a Unit of Work pattern commits on success and rolls back on failure using unittest.mock in Python.

unit-of-work mocking testing
Python
from unittest import mock


class UnitOfWork:
    def __init__(self):
        self.committed = False
        self.rolled_back = False

    def commit(self):
        self.committed = True
        print("Commit executed")

    def rollback(self):
        self.rolled_back = True
        print("Rollback executed")


def b…
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.