Skip to content

System Design Cheat Sheet ​


1. OOPs Concepts ​

ConceptAnalogyProblem SolvedReal-World Example
EncapsulationATM β€” you see the screen/buttons, not the internal cash mechanismHides internal state, protects data integrityBankAccount class with private _balance, public deposit()/withdraw()
InheritanceChild inherits traits from parent + has their ownCode reuse, hierarchical relationshipsVehicle β†’ Car, Bike, Truck
PolymorphismSame remote button (power) works on TV, AC, SoundbarOne interface, multiple implementationsShape.draw() β†’ Circle.draw(), Square.draw()
AbstractionDriving a car β€” you know steering + pedals, not engine internalsHide complexity, expose essentialssort() method hiding TimSort/QuickSort logic

Python snippet:

python
# Encapsulation
class BankAccount:
    def __init__(self):
        self._balance = 0

    def deposit(self, amt):
        if amt > 0:
            self._balance += amt

    def withdraw(self, amt):
        if 0 < amt <= self._balance:
            self._balance -= amt

# Polymorphism
from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def draw(self): pass

class Circle(Shape):
    def draw(self): print("πŸ”΅ Circle")
class Square(Shape):
    def draw(self): print("🟦 Square")

2. Design Principles ​

SOLID ​

PrincipleWhat it meansAnalogyViolation Example
S β€” Single ResponsibilityOne class = one jobA chef cooks; a waiter serves; a cashier billsInvoice class that also saveToDB(), sendEmail(), print()
O β€” Open/ClosedOpen for extension, closed for modificationPower outlet β€” add adapter for new device, don't rewire houseAdding a new payment type requires editing PaymentProcessor class
L β€” Liskov SubstitutionSubclass must work wherever parent is usedIf Bird can fly(), Penguin should NOT inherit BirdSquare inheriting Rectangle breaks setWidth()/setHeight()
I β€” Interface SegregationDon't force classes to implement unused methodsRestaurant menu β€” separate drink menu, food menu, dessert menuWorker interface with code(), eat(), sleep() forces Robot to implement eat()
D β€” Dependency InversionDepend on abstractions, not concretionsWall outlet expects a plug (abstract), not a specific deviceEmailService directly instantiating GmailClient() instead of Mailer interface

Python snippets:

python
# S β€” Single Responsibility βœ…
class InvoiceCalculator:
    def calculate(self, invoice): ...
class InvoiceRepository:
    def save(self, invoice): ...
class InvoicePrinter:
    def print(self, invoice): ...

# D β€” Dependency Inversion βœ…
from abc import ABC, abstractmethod
class Mailer(ABC):
    @abstractmethod
    def send(self, msg): pass

class GmailClient(Mailer):
    def send(self, msg): print("Sending via Gmail")

class NotificationService:
    def __init__(self, mailer: Mailer):  # depends on abstraction
        self.mailer = mailer

KISS, DRY, YAGNI, SoC, Composition over Inheritance ​

PrincipleMeaningExample
KISS β€” Keep It Simple, StupidSimplest solution winsif x: return True instead of return True if x else False
DRY β€” Don't Repeat YourselfExtract repeated codeExtract validate_email() once, call everywhere
YAGNI β€” You Ain't Gonna Need ItDon't build for hypothetical futureDon't add caching layer "just in case" traffic grows
SoC β€” Separation of ConcernsEach module handles one concernController (HTTP) β†’ Service (logic) β†’ Repository (DB)
Composition > InheritanceHas-a vs Is-aCar has Engine has Piston (instead of Car inheriting Engine)

3. Design Patterns (LLD) ​

🏭 Creational Patterns ​

PatternAnalogyProblem SolvedReal Example
SingletonOne security guard for entire buildingGlobal access to single instanceDB connection, Logger, Config manager
FactorySandwich shop β€” you order "Veggie", they make itObject creation logic is complex/conditionalParser factory: JSONParser, XMLParser
Abstract FactoryFurniture store β€” get "Victorian" set (chair+table+sofa)Creating families of related objectsUI toolkit: WinFactory, MacFactory
BuilderSubway sandwich β€” choose bread, veggies, sauce step-by-stepObject has many optional partsSQL query builder, HTML builder
PrototypeCloning a sheep (Dolly)Creating object is expensive; clone insteadCaching complex objects, game assets

Python snippets:

python
# Singleton (already shown) βœ…

# Factory
class Pizza:
    @staticmethod
    def order_pizza(pizza_type):
        if pizza_type == "veg":   return VegPizza()
        if pizza_type == "nonveg": return NonVegPizza()
        raise ValueError("Unknown pizza")

# Builder
class Burger:
    def __init__(self):
        self.bun = self.patty = self.sauce = None

class BurgerBuilder:
    def __init__(self):
        self.burger = Burger()
    def add_bun(self, bun):     self.burger.bun = bun;   return self
    def add_patty(self, patty):  self.burger.patty = patty; return self
    def add_sauce(self, sauce):  self.burger.sauce = sauce; return self
    def build(self):             return self.burger

burger = BurgerBuilder().add_bun("sesame").add_patty("chicken").add_sauce("BBQ").build()

🧱 Structural Patterns ​

PatternAnalogyProblem SolvedReal Example
AdapterTravel plug adapter β€” converts US plug to EU socketIncompatible interfacesLegacy system wrapper, API version adapter
DecoratorPizza toppings β€” base pizza + cheese + olives + pepperoniAdd responsibilities dynamically without subclassingMiddleware (logging, auth, compression)
FacadeHotel receptionist β€” one person handles booking, cleaning, foodSimplify complex subsystemOrderService hiding Inventory, Payment, Shipping
ProxyCredit card (proxy for bank account)Control access, lazy init, loggingLazy loading, auth proxy, cache proxy
CompositeFolder containing files + sub-folders (same interface)Treat single & group objects uniformlyUI tree: Label, Panel, Button all have render()
BridgeRemote (Sony Γ— Basic, Samsung Γ— Advanced)Decouple abstraction from implementationDevice(R/LED) Γ— Remote(Basic/Advanced)

Python snippets:

python
# Adapter
class EuropeanSocket:
    def voltage(self): return 230
class USPlug:
    def connect(self): return 110

class Adapter(USPlug):
    def __init__(self, socket: EuropeanSocket):
        self.socket = socket
    def connect(self):
        return self.socket.voltage()  # adapts 230 β†’ 110

# Decorator
def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_decorator
def process(data): ...

# Facade
class OrderFacade:
    def place_order(self, items, user):
        Inventory().check(items)
        Payment().charge(user, items)
        Shipping().schedule(items, user.address)

πŸ”„ Behavioral Patterns ​

PatternAnalogyProblem SolvedReal Example
ObserverYouTube subscriber β€” bell πŸ”” β†’ all subs get notifiedOne-to-many dependency, state change notificationEvent listeners, pub/sub systems, React state
StrategyGPS navigation β€” car vs bike vs walking routesFamily of algorithms, interchangeable at runtimePayment strategies (UPI, Card, NetBanking), sort algorithms
CommandRestaurant order β€” waiter takes slip β†’ chef cooks β†’ cashier billsEncapsulate request as objectUndo/redo, task queue, macro recording
StateTraffic light — Red→Green→Yellow→RedObject changes behavior when state changesOrder status (New→Paid→Shipped→Delivered), vending machine
TemplateTea/Coffee recipe β€” boil water + add stuff (boil is same, stuff varies)Define skeleton, defer steps to subclassesData migration framework, CI pipeline steps
IteratorTV remote channel surf β€” next(), prev(), current()Sequential access without exposing internal structurefor item in collection
Chain of Resp.ATM dispenser — 2000₹ → 500₹ → 200₹ → 100₹ notesPass request along chain until handledLogging levels (DEBUG→INFO→ERROR), middleware pipeline

Python snippets:

python
# Observer
class Subject:
    def __init__(self):
        self._observers = []
    def attach(self, obs):  self._observers.append(obs)
    def notify(self, msg):
        for obs in self._observers:
            obs.update(msg)

class EmailSubscriber:
    def update(self, msg): print(f"Email: {msg}")

# Strategy
from abc import ABC, abstractmethod
class PaymentStrategy(ABC):
    @abstractmethod
    def pay(self, amt): pass

class CreditCard(PaymentStrategy):
    def pay(self, amt): print(f"Paid {amt} via Card")

class UPI(PaymentStrategy):
    def pay(self, amt): print(f"Paid {amt} via UPI")

class Checkout:
    def __init__(self, strategy: PaymentStrategy):
        self.strategy = strategy
    def execute(self, amt):
        self.strategy.pay(amt)

Checkout(UPI()).execute(100)  # Paid 100 via UPI

# Chain of Responsibility
class Handler:
    def __init__(self):
        self._next = None
    def set_next(self, handler):
        self._next = handler; return handler
    def handle(self, request):
        if self._next: self._next.handle(request)

class AuthHandler(Handler):
    def handle(self, request):
        if request.get("auth"): print("Auth OK")
        else: print("Auth FAIL"); return
        super().handle(request)

class LoggingHandler(Handler):
    def handle(self, request):
        print(f"Log: {request}")
        super().handle(request)

βœ… Pattern Selection Guide ​

Need exactly one instance?       β†’ Singleton
Creation logic is complex?       β†’ Factory / Builder
Need to add features dynamically?β†’ Decorator
Hide complex subsystem?          β†’ Facade
Object changes behavior?         β†’ State
Multiple algorithms?             β†’ Strategy
Notify many on change?           β†’ Observer
Incompatible interfaces?         β†’ Adapter
Undo/redo / task queue?          β†’ Command
Whole-part hierarchy?            β†’ Composite

4. Concurrency & Multithreading ​

Core Concepts ​

ConceptAnalogyExplanation
ProcessA restaurant (has own kitchen, staff, space)Independent execution unit, isolated memory
ThreadOne chef in the kitchenLightweight, shares memory within process
MutexOne spatula β€” only one chef uses it at a timeLock β€” prevents race condition
Semaphore3 ovens available β€” take one, use, returnLimits concurrent access to N resources
DeadlockChef A has knife, Chef B has cutting board; both waitCircular wait β€” threads stuck forever
Race ConditionTwo chefs updating same order totalUnpredictable result due to unsynchronized access
Context SwitchChef switches from chopping to stirringCPU switches between threads
GIL (Python)One chef in kitchen, others wait (only one works at a time)Python's Global Interpreter Lock limits true parallelism

Python Multithreading ​

python
import threading
import time

lock = threading.Lock()
counter = 0

def worker(name):
    global counter
    for _ in range(1000):
        with lock:          # acquire mutex
            counter += 1    # critical section

threads = [threading.Thread(target=worker, args=(f"T{i}",)) for i in range(5)]
for t in threads: t.start()
for t in threads: t.join()
print(f"Counter: {counter}")  # Always 5000 βœ…

Deadlock Example ​

python
fork_a, fork_b = threading.Lock(), threading.Lock()

def philosopher(left, right):
    with left:
        print("Got left fork")
        with right:      # ⚠️ Can deadlock if both pick left first
            print("Eating")

# Fix: acquire locks in consistent order (always fork_a then fork_b)

Thread Pool (Concurrent.futures) ​

python
from concurrent.futures import ThreadPoolExecutor

def fetch_url(url):
    return f"Data from {url}"

with ThreadPoolExecutor(max_workers=4) as pool:
    results = list(pool.map(fetch_url, ["url1", "url2", "url3"]))

Async/Await (asyncio) ​

python
import asyncio

async def fetch_data(url):
    await asyncio.sleep(1)  # simulate I/O
    return f"Data from {url}"

async def main():
    results = await asyncio.gather(
        fetch_data("url1"), fetch_data("url2"), fetch_data("url3")
    )
    print(results)

asyncio.run(main())

Common Concurrency Problems & Solutions ​

ProblemCauseSolution
Race ConditionUnsync'd shared stateMutex, Lock, Semaphore
DeadlockCircular lock waitConsistent lock ordering, timeout
StarvationLow-priority thread never runsFair locks, aging
LivelockThreads keep yielding to each otherRandom backoff
False SharingCPUs invalidate each other's cache linesPadding / alignment

When to use what ​

CPU-bound work (math, video)     β†’ Multiprocessing (parallel)
I/O-bound work (HTTP, DB, files) β†’ Multithreading / asyncio
Thousands of connections         β†’ asyncio (event loop)
Data parallelism                 β†’ multiprocessing.Pool
Task management                  β†’ ThreadPoolExecutor

Quick Reference ​

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                  System Design                     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  OOPs:  Encapsulation | Inheritance | Poly | Abs  β”‚
β”‚  SOLID: S O L I D                                 β”‚
β”‚  Other: KISS DRY YAGNI SoC Comp>Inherit           β”‚
β”‚                                                    β”‚
β”‚  Patterns:                                         β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  Creational   β”‚  Structural   β”‚  Behavioral    β”‚  β”‚
β”‚  │──────────────│──────────────│────────────────│  β”‚
β”‚  β”‚ Singleton    β”‚ Adapter      β”‚ Observer       β”‚  β”‚
β”‚  β”‚ Factory      β”‚ Decorator    β”‚ Strategy       β”‚  β”‚
β”‚  β”‚ Builder      β”‚ Facade       β”‚ Command        β”‚  β”‚
β”‚  β”‚ Prototype    β”‚ Proxy        β”‚ State          β”‚  β”‚
β”‚  β”‚ Abstract Fac.β”‚ Composite    β”‚ Chain of Resp. β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                                                    β”‚
β”‚  Concurrency: Mutex | Semaphore | Deadlock | GIL   β”‚
β”‚  Parallel:  Multiprocessing (CPU)                  β”‚
β”‚  Concurrent: Threading / asyncio (I/O)             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

<<>> with β™₯️ by S@Nchit