System design patterns
Sharding, load balancing, CAP tradeoffs, and scaling patterns — interview and production ready.
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:
…
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.
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
}
…
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 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.
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…
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 a Data Helper Class in Python
Build a beginner-friendly DataHelper class using dataclasses and key system design patterns like Command, Strategy, and Map.
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…
How to Implement a Factory Method by Type String in Python
A factory method maps a type string to a class, creating and returning the appropriate object instance while handling unknown types gracefully.
class Animal:
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class AnimalFactory:
@staticmethod
def create(animal_type: str) -> Animal:
animal_types = {
…
How to Implement a Simple Event Bus in Python
Create a publish-subscribe event bus using dataclasses and defaultdict to decouple event producers from consumers.
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Set
@dataclass
class EventBus:
_subscribers: Dict[str, List[Callable]] = field(
default_factory=lambda: defaultdict(list)
)
def subscribe(self, event_type: str, handler: Callable…
How to Implement the Prototype Pattern with Deep Copy in Python
Implements the Prototype design pattern using copy.deepcopy to clone complex objects without sharing mutable state.
import copy
from dataclasses import dataclass, field
from typing import List
@dataclass
class Engine:
horsepower: int
@dataclass
class Car:
brand: str
engine: Engine
accessories: List[str] = field(default_factory=list)
def clone_prototype(car: Car) -> Car:
return copy.deepcopy(car)
if __name__ …
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…
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.