Skip to the content.

Awesome Low-Level Design: SOLID, Design Patterns and 10 Classic LLD Problems in Python

A practical guide to low-level design (LLD), also called object-oriented design or machine coding: SOLID principles with before-and-after code, 17 design patterns implemented in idiomatic Python, and 10 classic LLD interview problems (parking lot, LRU cache, elevator, vending machine, expense splitter, tic-tac-toe, library, ticket booking, key-value store with transactions, logging framework), each with class diagrams, design decisions and tested code. It is for engineers preparing for LLD and machine coding interview rounds and for anyone who wants cleaner object-oriented Python.

Last reviewed: December 2026

Table of Contents

What low-level design interviews test

Signal What the interviewer looks for
Requirements You ask clarifying questions and agree on scope before coding
Modelling Sensible classes, responsibilities and relationships; nouns become entities, verbs become methods
Extensibility New vehicle types, payment methods or pricing rules can be added without rewriting existing code
Correctness Edge cases handled: full lot, sold-out item, invalid move, expired hold
Code quality Readable names, small methods, no duplicated logic, errors raised clearly
Patterns Used where they help (strategy for pricing, state for workflows), not forced everywhere
Concurrency Awareness of races for shared resources (seats, spots, counters)
Testing You can show the design works, ideally with a few tests or a driver

Machine coding rounds (60-120 minutes) expect working code; design-only rounds expect class diagrams and key methods.

A step-by-step approach for LLD rounds

  1. Clarify requirements (5 min). List core use cases, then out-of-scope items. Example for a parking lot: multiple floors? vehicle sizes? payment? reservations?
  2. Identify entities (5 min). Underline nouns in the requirements: ParkingLot, Floor, Spot, Vehicle, Ticket.
  3. Define relationships. Composition (a lot has floors), association (a ticket refers to a spot), inheritance only for genuine “is-a” with shared behaviour.
  4. Assign responsibilities. Each class owns its data and the rules about it. Ask “who should know this?”
  5. Find what varies and isolate it. Fee rules, notification channels and matching algorithms usually change: put them behind an interface (strategy).
  6. Draw a class diagram (Mermaid or boxes) and walk through one use case end to end.
  7. Write the code, starting with the core flow; add validation and edge cases next.
  8. Test with a small driver or unit tests; discuss concurrency and extensions.

OOP building blocks in Python

Concept Python tool Example in this repo
Interface abc.ABC + @abstractmethod, or typing.Protocol for structural typing Notifier, FeePolicy
Value object @dataclass(frozen=True) HttpRequest
Entity with identity Regular class or @dataclass with an ID field Spot, Ticket
Enumeration enum.Enum / IntEnum Size, Direction, Level
Encapsulation Leading underscore for internals, properties for computed values LRUCache._unlink
Composition Objects held as attributes OrderFacade holds Inventory, Billing, Shipping
Polymorphism Same method name, different classes File.size() and Folder.size()

Python-specific advice:

SOLID principles with examples

S: Single responsibility principle

A class should have one reason to change.

# Before: one class formats, persists and emails reports
class Report:
    def build(self, rows): ...
    def save_to_disk(self, path): ...
    def email(self, to): ...

# After: each concern can change independently
class ReportBuilder:
    def build(self, rows) -> str: ...

class ReportStore:
    def save(self, report: str, path: str) -> None: ...

class ReportMailer:
    def send(self, report: str, to: str) -> None: ...

O: Open/closed principle

Open for extension, closed for modification. Add new behaviour by adding code, not by editing a growing if/elif chain.

# Before: every new discount type edits this function
def price(kind, base):
    if kind == "regular":
        return base
    elif kind == "sale":
        return base * 0.8
    # ...

# After: new strategies are new classes (see patterns/behavioral.py)
class PricingStrategy:            # abstract
    def price(self, base: float) -> float: ...

class PercentOff(PricingStrategy):
    def __init__(self, percent): self.percent = percent
    def price(self, base): return base * (1 - self.percent / 100)

L: Liskov substitution principle

Subtypes must be usable wherever the base type is expected without surprising the caller.

# Violation: a Square that inherits from Rectangle breaks callers that set width and height independently
class Rectangle:
    def __init__(self, w, h): self.w, self.h = w, h
    def set_width(self, w): self.w = w
    def area(self): return self.w * self.h

class Square(Rectangle):
    def set_width(self, w): self.w = self.h = w   # surprise: height changed too

# Fix: model both as separate implementations of a Shape interface with area(), no shared setters.

Other common violations: a subclass that raises NotImplementedError for a base method, or one that strengthens preconditions (accepts fewer inputs than the base).

I: Interface segregation principle

Clients should not depend on methods they do not use.

# Before: every device must implement everything
class Machine:
    def print(self, doc): ...
    def scan(self, doc): ...
    def fax(self, doc): ...

# After: small, focused interfaces
class Printer:
    def print(self, doc): ...

class Scanner:
    def scan(self, doc): ...

class OfficeMachine(Printer, Scanner): ...
class SimplePrinter(Printer): ...

D: Dependency inversion principle

High-level code depends on abstractions, and concrete details are injected.

# Before: the service creates its own concrete dependency
class OrderService:
    def __init__(self):
        self.payments = StripeLikeClient()     # hard to test, hard to swap

# After: depend on an interface and inject the implementation
class OrderService:
    def __init__(self, payments: "PaymentProcessor"):
        self.payments = payments               # tests can pass a fake

Other principles worth naming

Principle Meaning Typical interview use
DRY (don’t repeat yourself) One source of truth for each piece of knowledge Shared validation or fee logic
KISS Prefer the simplest design that works Resisting unnecessary patterns
YAGNI Do not build features before they are needed Pushing back on speculative abstractions
Composition over inheritance Combine small objects rather than build deep hierarchies Decorators, strategies
Law of Demeter Talk only to immediate collaborators (a.b().c().d() is a smell) Keeping coupling low
Tell, don’t ask Ask objects to do work rather than pulling their data out order.pay() instead of inspecting order.status
Fail fast Validate inputs at the boundary and raise early Constructors and public methods

Design patterns catalogue

All patterns below are implemented in patterns/ and exercised in tests/test_patterns.py.

Creational

Pattern Intent Python example Use when
Singleton One shared instance Config (thread-safe double-checked creation) A truly global resource; in Python a module-level object is usually simpler and easier to test
Factory method Delegate which class to instantiate create_notifier with a registry The concrete type depends on input or configuration
Abstract factory Create families of related objects DarkTheme / LightTheme Products must match each other (UI themes, cloud provider SDKs)
Builder Construct complex objects step by step HttpRequestBuilder Many optional parameters with validation at the end
Prototype Clone a configured object Document.clone Copying is cheaper or simpler than rebuilding

Structural

Pattern Intent Python example Use when
Adapter Convert one interface to another LegacyGatewayAdapter Integrating a third-party or legacy API
Decorator Add behaviour by wrapping UppercaseDecorator, @retry Optional, stackable features (logging, retries, caching)
Facade Simple front for a complex subsystem OrderFacade Hiding orchestration of several services
Proxy Same interface, controlled access CachingWeatherProxy Caching, lazy loading, access control, remote calls
Composite Treat parts and wholes uniformly File / Folder Trees: file systems, menus, org charts

Behavioral

Pattern Intent Python example Use when
Strategy Interchangeable algorithms PricingStrategy Pricing, sorting, routing rules that vary
Observer Notify subscribers of events EventBus Decoupled reactions to changes
Command Encapsulate a request as an object AppendText + CommandHistory Undo/redo, job queues, audit logs
State Behaviour depends on state; one class per state Order states Workflows with clear transitions (orders, vending, tickets)
Iterator Traverse without exposing internals Playlist (generators) Custom collections
Template method Fixed algorithm skeleton with overridable steps Report / CsvReport Shared workflow with varying steps
Chain of responsibility Pass a request along handlers TeamLead → Manager → Director Approvals, middleware, filters

Choosing a pattern

flowchart TB
    Q{What is changing?}
    Q -->|which algorithm runs| S[Strategy]
    Q -->|which class gets created| F[Factory method or abstract factory]
    Q -->|behaviour as status changes| ST[State]
    Q -->|who reacts to an event| O[Observer]
    Q -->|extra behaviour around an object| D[Decorator or proxy]
    Q -->|an incompatible interface| A[Adapter]
    Q -->|many optional constructor arguments| B[Builder]
    Q -->|who handles a request| C[Chain of responsibility]

Patterns are a vocabulary, not a goal. Naming the pattern you used (“pricing is a strategy so we can add holiday rates”) shows design intent; forcing patterns into simple code is a common way to lose points.

LLD problems

Each problem lists the requirements we chose, the core classes, key design decisions, and extensions an interviewer might ask for. Code lives in problems/ and is tested in tests/test_problems.py.

1. Parking lot

Requirements: multiple floors; spot sizes for motorcycles, cars and trucks; a vehicle may use a larger spot if needed; issue a ticket on entry; compute the fee on exit; report free spots.

classDiagram
    class ParkingLot {
        +floors: list
        +policy: FeePolicy
        +park(plate, size, now) Ticket
        +leave(ticket_id, now) float
        +free_spots() int
    }
    class Spot {
        +spot_id: str
        +size: Size
        +vehicle: str
        +fits(size) bool
    }
    class Ticket {
        +ticket_id: int
        +plate: str
        +spot_id: str
        +entry_time: float
    }
    class FeePolicy {
        <<interface>>
        +fee(size, hours) float
    }
    class HourlyFee
    ParkingLot "1" *-- "many" Spot
    ParkingLot --> Ticket
    ParkingLot --> FeePolicy
    FeePolicy <|.. HourlyFee

Decisions. The smallest fitting spot is chosen so large spots stay free. Fees are a strategy (FeePolicy), so weekend or flat-rate pricing is a new class, not an edit. Time is passed in (now) so tests are deterministic.

Extensions. Display boards per floor (observer on spot changes), reservations, EV charging spots (a spot attribute plus a filter), multiple entry gates (concurrency: lock spot assignment or use atomic updates in a database).

Code: problems/parking_lot.py

2. LRU cache

Requirements: fixed capacity; get and put in O(1); evict the least recently used entry when full.

classDiagram
    class LRUCache {
        +capacity: int
        -map: dict
        -head: Node
        -tail: Node
        +get(key) value
        +put(key, value)
    }
    class Node {
        +key
        +value
        +prev: Node
        +next: Node
    }
    LRUCache *-- Node

Decisions. A dictionary gives O(1) lookup of the node; a doubly linked list with sentinel head and tail gives O(1) move-to-front and evict-from-back without edge cases. Python’s collections.OrderedDict offers the same behaviour in a few lines, which is a good thing to mention, but interviewers usually want the manual version.

Extensions. TTL per entry, LFU eviction (frequency buckets), thread safety (a lock around get and put), and metrics (hit rate).

Code: problems/lru_cache.py

3. Elevator system

Requirements: several cars; hall calls (floor + direction) and car calls (destination); each car serves requests efficiently; a controller assigns hall calls.

stateDiagram-v2
    [*] --> Idle
    Idle --> MovingUp: stop above
    Idle --> MovingDown: stop below
    MovingUp --> MovingUp: more stops above
    MovingUp --> MovingDown: no stops above, stops below
    MovingDown --> MovingDown: more stops below
    MovingDown --> MovingUp: no stops below, stops above
    MovingUp --> Idle: no stops left
    MovingDown --> Idle: no stops left

Decisions. Each car uses the SCAN (“elevator”) algorithm: keep moving in one direction while stops remain ahead, then reverse. The controller assigns each hall call to the car with the lowest estimated cost (distance, plus a penalty if the car must finish its current sweep first). The cost function is the natural place for a strategy pattern.

Extensions. Capacity and weight limits, express cars for certain floors, peak-hour modes (park idle cars in the lobby in the morning), door and emergency states, and a simulation clock.

Code: problems/elevator.py

4. Vending machine

Requirements: accept coins and notes; select a product; dispense it with change; handle sold-out items, insufficient money and cancellation.

stateDiagram-v2
    [*] --> Idle
    Idle --> HasMoney: insert money
    HasMoney --> HasMoney: insert more
    HasMoney --> Dispensing: select product with enough balance
    Dispensing --> Idle: product and change returned
    HasMoney --> Idle: cancel and refund

Decisions. An explicit state field blocks invalid actions (selecting before paying). Change is computed greedily, which is correct for canonical coin systems like 25/10/5 but not for arbitrary denominations (use dynamic programming or coin inventory checks there). Errors are specific: sold out, unknown product, insufficient balance.

Extensions. Coin inventory (cannot give change if the machine is out of dimes), card payments (strategy), admin restocking, and the class-per-state pattern from patterns/behavioral.py when states gain more behaviour.

Code: problems/vending_machine.py

5. Expense splitter

Requirements: record expenses split equally, by exact amounts or by percentages; show who owes whom; suggest few settlement transfers.

classDiagram
    class ExpenseSplitter {
        +balance: dict
        +add_equal(payer, amount, members)
        +add_exact(payer, amount, shares)
        +add_percent(payer, amount, percents)
        +settlements() list
    }

Decisions. Money is stored as integer cents to avoid floating-point errors, and rounding remainders are assigned deterministically so balances always sum to zero. Settlements use a greedy largest-debtor-pays-largest-creditor approach that needs at most n - 1 transfers. (Finding the absolute minimum number of transfers is NP-hard in general, which is worth mentioning.)

Extensions. Groups, currencies with exchange rates, expense history and edits (store expenses and recompute balances), and notifications.

Code: problems/expense_splitter.py

6. Tic-tac-toe

Requirements: an N x N board, two players taking turns, detect a win or draw, reject invalid moves.

Decisions. Instead of scanning the board after every move (O(N^2)), keep counters per row, column and both diagonals: +1 for player one, -1 for player two. A counter reaching ±N means a win, so each move is O(1).

Extensions. Undo (command pattern), computer player (minimax for 3 x 3), K-in-a-row on larger boards (counters no longer suffice; check lines through the last move).

Code: problems/tic_tac_toe.py

7. Library management

Requirements: catalogue of titles and copies; members borrow and return copies; loan limits; due dates and late fees; holds queue when no copy is free.

classDiagram
    class Library {
        +titles: dict
        +copies: dict
        +members: dict
        +holds: dict
        +checkout(member, isbn, today) str
        +return_copy(copy_id, today) int
        +place_hold(member, isbn) int
        +search(text) list
    }
    class Copy {
        +copy_id
        +isbn
        +borrower
        +due
    }
    class Member {
        +member_id
        +loans
        +fees_cents
    }
    Library *-- Copy
    Library *-- Member

Decisions. A title (ISBN) is separate from its physical copies. Holds are a FIFO queue per title; the first member in the queue gets priority. Business rules (loan limit, unpaid fees) are checked in one place before a loan is created.

Extensions. Renewals, notifications when a hold is ready (observer), different member types with different limits (strategy or configuration), and search by author or subject.

Code: problems/library.py

8. Movie ticket booking

Requirements: show seat maps; hold several seats while the user pays; confirm the booking; release holds after a timeout; never double-book a seat.

sequenceDiagram
    participant U as User
    participant S as Show
    U->>S: hold(A1, A2)
    S->>S: lock, expire old holds, check all seats available
    S-->>U: held for 10 minutes
    U->>S: confirm(A1, A2) after payment
    S->>S: lock, verify holder and expiry
    S-->>U: booked

Decisions. Holds are all-or-nothing so a group never gets split seats. A lock per show makes check-and-hold atomic; in a real system this becomes a conditional database update (UPDATE ... WHERE status = 'available'). Expiry is checked lazily on every operation, so no background thread is needed for correctness.

Extensions. Seat types and pricing tiers, payment integration with idempotency keys, a waiting room for high-demand shows, and seat-selection suggestions (best adjacent seats).

Code: problems/ticket_booking.py

9. Key-value store with transactions

Requirements: set, get, delete, optional TTL; begin, commit and rollback with nesting.

Decisions. Each open transaction keeps an undo log of the previous value of every key it touches (only the first change per key). Rollback replays the log; commit merges the log into the parent transaction (keeping the parent’s older values) so an outer rollback still undoes everything. TTL is checked lazily on read.

Extensions. Snapshot reads, a write-ahead log for durability, background expiry, and concurrency control (per-key locks or optimistic versioning).

Code: problems/kv_store.py

10. Logging framework

Requirements: log levels; a logger name per component; multiple outputs (sinks) with their own minimum levels; pluggable formatting.

classDiagram
    class Logger {
        +name
        +level
        +log(level, message)
    }
    class Sink {
        <<abstract>>
        +min_level
        +accept(level, line)
        +write(line)
    }
    class MemorySink
    class Formatter {
        +format(logger, level, message) str
    }
    Logger --> Sink
    Logger --> Formatter
    Sink <|-- MemorySink

Decisions. Filtering happens twice (logger level, then sink level), like a chain of responsibility. Sinks are observers of log events; formatters are strategies. Adding a file or network sink is a new subclass.

Extensions. Asynchronous sinks with a queue, structured (JSON) logs, logger hierarchies inheriting levels, and rate limiting noisy messages. Python’s standard logging module implements these ideas and is worth comparing.

Code: problems/logger.py

More problems to practise

Try these on your own using the same approach. Suggested patterns are hints, not requirements.

Problem Core challenge Patterns that often fit
Snake and ladder Game loop, board configuration Strategy (dice), builder (board)
Chess Move validation per piece, check detection Polymorphism per piece, command (undo)
ATM Card, PIN and transaction states, cash dispensing State, chain of responsibility (note dispensing)
Hotel reservation Room inventory over date ranges Strategy (pricing), repository
Food delivery Orders, restaurants, delivery assignment Observer (status updates), strategy (assignment)
Ride sharing (LLD) Matching riders and drivers, trip states State, strategy
Rate limiter (LLD) Token bucket per client, pluggable algorithms Strategy
Pub/sub message broker Topics, subscribers, delivery Observer
Task scheduler Delayed and recurring jobs, priorities Command, priority queue
Online shopping cart Cart, discounts, checkout Strategy (discounts), decorator
File system Directories, files, paths, sizes Composite
Splitwise with groups Extension of the expense splitter Repository, observer

Concurrency checklist

LLD interviews often end with “what if two users do this at the same time?”

Risk Example Fix
Check-then-act race Two users see a seat as free and both hold it Lock around check and update, or an atomic conditional update
Lost update Two threads increment a counter Lock, atomic operations, or a single-writer queue
Deadlock Two locks taken in different orders Always acquire locks in a fixed order; keep critical sections small
Stale reads Cached state differs from the source of truth Short TTLs, invalidation, or read-through from the source
Double processing Retried payment confirmation Idempotency keys

In Python, the global interpreter lock does not make compound operations atomic: x += 1 on shared state still needs a lock. For I/O-bound concurrency, asyncio with careful design avoids many locks.

Code review checklist for LLD answers

Running the code

Requirements: Python 3.10 or newer, no third-party packages.

git clone https://github.com/Ralpberry-Labs/awesome-low-level-design.git
cd awesome-low-level-design
python3 -m unittest discover -s tests -t .

Layout:

patterns/
  creational.py    Singleton, factory method, abstract factory, builder, prototype
  structural.py    Adapter, decorator, facade, proxy, composite
  behavioral.py    Strategy, observer, command, state, iterator, template method, chain of responsibility
problems/
  parking_lot.py, lru_cache.py, elevator.py, vending_machine.py, expense_splitter.py,
  tic_tac_toe.py, library.py, ticket_booking.py, kv_store.py, logger.py
tests/
  test_patterns.py, test_problems.py

FAQ

What is the difference between low-level design and high-level design? High-level (system) design is about services, databases, caches and scaling across machines. Low-level design is about classes, interfaces, data structures and code inside one service. Many interview loops include both.

Which language should I use for LLD interviews? Any object-oriented language you know well. Java and C++ are common, but Python is accepted widely and keeps the code short, leaving more time for design discussion.

Do I need to know all 23 classic design patterns? No. Strategy, observer, factory, builder, state, decorator, adapter, singleton and command cover most interview problems. Understand when each helps and when it is overkill.

How much code should I write in a 45-minute LLD round? Enough to show the core flow working: the main classes, the key methods with real logic, and validation for the important edge cases. Stub peripheral parts and say what they would do.

Should I draw UML? A simple class diagram (classes, key fields and methods, relationships) helps the interviewer follow your design. Full UML notation is rarely expected.

How is “machine coding” different? Machine coding rounds expect complete, runnable code in 60-120 minutes, often with a command-line driver and some tests. Practise by implementing problems from the table above under a timer.

Where to go next

Contributing

PRs are welcome. Keep entries accurate:

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.