Low-Level Design
OOP and SOLID, all 23 design patterns, 23 classic problems with entities and APIs, 3 full worked designs, concurrency and the machine-coding round.
00LLD atlas: topics and routes
The whole sheet on one screen. Select an area or topic to jump to it; hover the boxes in any diagram below for explanations.
LLD topic atlas#
How to use this sheet#
- Learning: OOP foundations, then the pattern catalogue; learn when each pattern applies, not just what it is.
- Practising: take a problem from the playbook, set a 90-minute timer, and build a runnable solution with a demo driver.
- Before a machine-coding round: re-read the time plan, package layout and rubric, then one worked design.
- Interview tomorrow: pattern trigger phrases, the problem playbook table, concurrency hazards, then the last-minute checklist.
What interviewers score#
| Signal | Where it's covered |
|---|---|
| Clear entities and ownership | Responsibility guide · GRASP |
| Extensible without edits | SOLID · Pattern triggers |
| Working code early | Time plan · Package layout |
| Thread-safety stated | Hazards · Primitives |
| Edge cases and tests | Errors · Testing |
Check yourself 2 questions
Which principle signals 'extensible without edits'?
Show answer
Open/closed, usually via Strategy or Factory.
Why produce working code early?
Show answer
Interviewers score a running core over a perfect but unfinished design.
Takeaway Clear entities and ownership, extensibility without edits, working code early, and handling of concurrency and errors.
01LLD: model behavior, state, and boundaries
60-minute interview route#
| Time | Focus |
|---|---|
| 0–6 | Use cases, constraints, edge cases |
| 6–12 | Entities, value objects, invariants |
| 12–18 | Public method signatures and ownership |
| 18–24 | Relationships and state transitions |
| 24–44 | Implement core path; extend only as needed |
| 44–50 | Concurrency and atomicity |
| 50–60 | Errors, races, tests, extension points |
What interviewers score
- Entities with one job each, and invariants enforced inside them rather than by callers.
- Patterns used for a real variation point, and named only after the code needs them.
- A working core path early, then extensions.
- Thread safety reasoned out loud: what is shared, and what guards it.
- Testability: injected clock and ID generator, small interfaces, edge cases named.
- Readable names, small methods, and no dead abstractions.
Check yourself 2 questions
What comes right after use cases?
Show answer
Entities, value objects and invariants.
When do you write method signatures?
Show answer
Before relationships and code, around minutes 12–18.
Takeaway Use cases, entities and invariants, method signatures, relationships and states, code the core, then concurrency and extensions.
Object design flow#
flowchart TD U[Use cases + edge cases] --> I[Invariants and state ownership] I --> M[Entities + immutable values] M --> A[Small public interfaces] A --> S[Services orchestrate behavior] S --> P[Pattern for real variation] P --> C[Concurrency / transaction boundaries] C --> T[Test transitions, races, failures]
Check yourself 2 questions
Where should invariant-preserving operations live?
Show answer
Near the state they protect, on the entity.
What do services do?
Show answer
Orchestrate behaviour across entities.
Takeaway Use cases → invariants and state ownership → entities and values → small interfaces → orchestrating services.
Responsibility guide#
| Building block | Owns | Design cue |
|---|---|---|
| Entity | Identity and lifecycle state | Keep invariant-preserving operations near state. |
| Value object | Immutable values such as Money or Address | Validate once; compare by value. |
| Service | Use-case orchestration | Coordinate collaborators; avoid god classes. |
| Repository / gateway | Persistence or external boundary | Depend on an interface for testability. |
| Strategy / state | Replaceable rule or legal transitions | Use when the variation is visible. |
Check yourself 2 questions
Give an example of a value object.
Show answer
Money or Address.
What does a repository hide?
Show answer
Storage details behind a collection-like interface.
Takeaway Entities own identity and lifecycle, value objects are immutable, services orchestrate, repositories hide storage.
02Object-oriented foundations
The vocabulary interviewers expect you to use while modeling. Name the principle when you apply it.
Four pillars of OOP#
| Pillar | What it means | Interview cue |
|---|---|---|
| Encapsulation | State is private; change it only through methods that keep invariants | No public setters on balance; expose deposit() / withdraw() |
| Abstraction | Callers depend on what an object does, not how | PaymentGateway interface hides Stripe/Razorpay details |
| Inheritance | "is-a" reuse of type and behaviour | Use for true subtypes only; prefer composition for reuse |
| Polymorphism | One call, many implementations (runtime dispatch / overloading) | Replace if type == … chains with subclasses or strategies |
Check yourself 2 questions
Encapsulation interview cue?
Show answer
No public setter on balance; expose deposit() and withdraw().
What does polymorphism let you do?
Show answer
Call the same interface with different behaviours.
Takeaway Encapsulation, abstraction, inheritance and polymorphism; protect invariants with methods, not public setters.
UML class relationships#
| Relation | Notation | Lifetime | Code shape |
|---|---|---|---|
| Dependency | dashed arrow | temporary use | parameter or local variable |
| Association | solid line | independent | field holding a reference |
| Aggregation | hollow diamond | part outlives whole | Team has Players passed in |
| Composition | filled diamond | part dies with whole | Order creates its OrderLines |
| Inheritance | hollow triangle, solid | — | class Car extends Vehicle |
| Realization | hollow triangle, dashed | — | class Card implements Payment |
Check yourself 2 questions
Composition versus aggregation?
Show answer
In composition the part's lifetime is owned by the whole; in aggregation it's independent.
Code shape of a dependency?
Show answer
A parameter or local variable.
Takeaway Dependency, association, aggregation, composition, inheritance and realisation differ in lifetime and code shape.
SOLID with the smell and the fix#
| Principle | Rule | Smell you'll see | Fix | LLD example |
|---|---|---|---|---|
| S · Single responsibility | One reason to change | Invoice computes, prints and saves itself | Split into calculator, printer, repository | ParkingLot doesn't compute fees; FeeCalculator does |
| O · Open/closed | Extend without editing | Growing switch(paymentType) | Interface + new class per variant | Add UpiPayment without touching checkout |
| L · Liskov substitution | Subtypes honour the parent's contract | Square extends Rectangle breaks setWidth; Penguin.fly() throws | Re-model the hierarchy; split capabilities | Flyable as a separate interface |
| I · Interface segregation | Small, client-specific interfaces | Classes implementing methods with throw UnsupportedOperation | Split fat interface into roles | Printer, Scanner, Fax instead of Machine |
| D · Dependency inversion | Depend on abstractions; inject them | new MySqlRepo() inside a service | Constructor injection of an interface | Swap in-memory repo for tests |
Check yourself 2 questions
SRP smell?
Show answer
One class that computes, prints and saves (several reasons to change).
DIP fix?
Show answer
Depend on abstractions; inject implementations.
Takeaway Each SOLID principle has a recognisable smell and a standard fix.
Design principles beyond SOLID#
- Composition over inheritance: assemble behaviour from parts; avoids fragile base classes.
- Tell, don't ask:
account.withdraw(x)rather than reading balance and deciding outside. - Law of Demeter: talk to direct collaborators only; avoid
a.getB().getC().do(). - DRY · KISS · YAGNI: no duplicated knowledge, simplest design that works, no speculative features.
- High cohesion, low coupling: related behaviour together; few, narrow dependencies.
- Program to interfaces; keep the domain free of framework and I/O code.
- Immutability for value objects and anything shared across threads.
- Fail fast: validate at construction; make illegal states unrepresentable (enums, types).
Check yourself 2 questions
Tell, don't ask example?
Show answer
account.withdraw(x) rather than reading the balance and deciding outside.
Why prefer composition?
Show answer
It avoids fragile base classes and allows swapping parts.
Takeaway Composition over inheritance, tell don't ask, Law of Demeter, DRY, KISS and YAGNI.
GRASP: who should own this responsibility?#
| Principle | Assign the responsibility to… |
|---|---|
| Information expert | the class that has the data needed |
| Creator | the class that contains or aggregates the created object |
| Controller | a use-case/facade object, not the UI |
| Polymorphism | the types that vary, not a conditional |
| Pure fabrication | a made-up service class when no domain object fits (repository, notifier) |
| Indirection | an intermediary that decouples two classes |
| Protected variations | an interface wrapped around whatever is likely to change |
Check yourself 2 questions
Information expert rule?
Show answer
Give the responsibility to the class with the needed data.
Creator rule?
Show answer
The class that contains or aggregates an object creates it.
Takeaway Information expert, creator, controller, low coupling, high cohesion and more decide ownership.
Language essentials for LLD: Java and Python#
| Topic | Java | Python | Interview cue |
|---|---|---|---|
| Interface vs abstract class | Interface: a contract, multiple inheritance, default methods. Abstract class: shared state and code, single inheritance | abc.ABC with @abstractmethod; typing.Protocol for structural typing | Interface for a capability or strategy; abstract class when subclasses share real state |
| Immutability | final fields, no setters, defensive copies; record for value objects | @dataclass(frozen=True), tuples | Value objects (Money, Address) and anything shared across threads |
| Equality and hashing | Override equals and hashCode together; equal objects must have equal hashes | __eq__ and __hash__; frozen dataclasses generate both | Mutating a field used in the hash after inserting into a HashMap/set loses the entry |
| Enums | Enums can hold fields and per-constant behaviour | enum.Enum; add methods on the class | Model statuses and types as enums, not strings |
| Generics | Bounded types; PECS rule: producer extends, consumer super | TypeVar, Generic[T] (hints only) | Repository<T, ID>, Cache<K, V> |
| Exceptions | Checked (recoverable, declared) vs unchecked (programming errors); custom domain exceptions | All unchecked; subclass Exception per domain error | SeatUnavailableException beats returning null or -1 |
| Visibility and encapsulation | private by default; package-private for tests | Leading underscore by convention; @property for computed or read-only attributes | No public mutable fields on entities |
| Composition helpers | Constructor injection; Optional for absent values | Pass collaborators to __init__; None checks or Optional[T] | Makes swapping and testing collaborators trivial |
Check yourself 2 questions
Interface versus abstract class in Java?
Show answer
Interfaces are contracts with multiple inheritance; abstract classes share state and code with single inheritance.
Python's equivalent of an abstract class?
Show answer
abc.ABC with @abstractmethod.
Takeaway Interfaces versus abstract classes, generics, enums, records and dataclasses, and equality and hashing.
03Design patterns catalogue
All 23 Gang of Four patterns plus the modern ones that show up in machine-coding rounds. In an interview, use one or two that the requirements actually call for, and say why.
Creational (5)#
| Pattern | Intent | Use when |
|---|---|---|
| Singleton | One shared instance | Config, registry, ID generator; make it thread-safe and injectable |
| Factory Method | Subclass decides which product to create | Create Vehicle by type; hide new |
| Abstract Factory | Families of related products | UI themes, DB driver families (connection + command) |
| Builder | Step-by-step construction | Many optional params; immutable result (Pizza, HTTP request) |
| Prototype | Clone an existing object | Expensive setup; templates (documents, game units) |
Check yourself 2 questions
When use Builder?
Show answer
For objects with many optional parameters.
What should a Singleton be, in modern practice?
Show answer
Thread-safe and injectable.
Takeaway Singleton, Factory Method, Abstract Factory, Builder and Prototype manage object creation.
Structural (7)#
| Pattern | Intent | Use when |
|---|---|---|
| Adapter | Convert one interface to another | Wrap a third-party payment SDK |
| Bridge | Split abstraction from implementation | Shape × renderer, Remote × device |
| Composite | Tree of parts treated uniformly | File system, nested comments, menu |
| Decorator | Add behaviour by wrapping | Pizza toppings, stream compression, logging |
| Facade | Simple front for a subsystem | BookingService over seats, payments, notifications |
| Flyweight | Share intrinsic state | Chess piece types, text glyphs, map tiles |
| Proxy | Stand-in that controls access | Lazy loading, caching, auth, remote stub |
Check yourself 2 questions
Wrap a third-party payment SDK?
Show answer
Adapter.
Tree of items treated uniformly?
Show answer
Composite.
Takeaway Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy shape how objects compose.
Behavioral (11)#
| Pattern | Intent | Use when |
|---|---|---|
| Strategy | Swap algorithms | Pricing, matching, split types, eviction |
| State | Behaviour changes with state | Vending machine, ATM, order lifecycle |
| Observer | Notify subscribers of change | Stock alerts, order status, UI events |
| Command | Request as an object | Undo/redo, job queues, macro recording |
| Chain of Responsibility | Pass along handlers | Log levels, approval flows, middleware, ATM notes |
| Template Method | Fixed skeleton, overridable steps | Game turn, report generation, data import |
| Iterator | Traverse without exposing internals | Custom collections, paginated results |
| Mediator | Central hub for interactions | Chat room, air-traffic control, UI dialogs |
| Memento | Snapshot and restore state | Editor undo, game save points |
| Visitor | New operations over a fixed structure | AST evaluation, tax/export over shapes |
| Interpreter | Grammar evaluation | Rule engines, simple expression parsers |
Check yourself 2 questions
Vending machine behaviour changes with state?
Show answer
State pattern.
Swap pricing algorithms?
Show answer
Strategy.
Takeaway Strategy, State, Observer, Command, Chain of Responsibility, Template Method and others organise behaviour.
Modern and enterprise patterns#
| Pattern | Use when |
|---|---|
| Dependency injection | Always: pass collaborators in; enables tests and swaps |
| Repository | Hide storage behind a collection-like interface |
| Unit of Work | Commit several changes atomically |
| Specification | Composable business rules (eligibility, filters) |
| Null Object | Avoid null checks (NoDiscount) |
| Object Pool | Reuse expensive objects (connections, threads) |
| Producer–Consumer | Decouple work creation from execution |
| Event bus / Pub-Sub | Many-to-many async notifications |
| Circuit breaker | Stop calling a failing dependency |
| Rule engine | Coupons, fraud rules, pricing stored as data |
Check yourself 2 questions
When use dependency injection?
Show answer
Always: pass collaborators in for testability and swaps.
Unit of Work?
Show answer
Commits several changes as one transaction.
Takeaway Dependency injection, repository, unit of work, CQRS, event sourcing and outbox appear in modern systems.
Patterns people confuse#
| Pair | Difference |
|---|---|
| Strategy vs State | Client picks the strategy; a state object switches itself to the next state |
| Decorator vs Proxy | Decorator adds behaviour and stacks; proxy controls access to the same interface |
| Adapter vs Facade | Adapter converts one interface; facade simplifies many |
| Factory Method vs Abstract Factory | One product via inheritance vs a family via composition |
| Builder vs Factory | Builder assembles step by step; factory picks a type in one call |
| Observer vs Pub-Sub | Observer: subject knows observers. Pub-sub: broker in between, often async |
| Template vs Strategy | Inheritance fills steps vs composition swaps the whole algorithm |
| Composite vs Decorator | Both wrap the same interface; composite has many children, decorator one |
| Mediator vs Observer | Mediator coordinates two-way logic; observer only broadcasts |
| Bridge vs Adapter | Bridge is designed up front so abstraction and implementation vary independently; adapter retrofits a mismatch |
| Command vs Strategy | Command is a request object you can queue, log or undo; strategy is an interchangeable algorithm |
| Flyweight vs Singleton | Flyweight shares many immutable instances by key; singleton has exactly one instance |
| Chain of Responsibility vs Decorator | A chain link may stop the request; a decorator always delegates and adds behaviour |
Check yourself 2 questions
Strategy versus State?
Show answer
The client picks a strategy; a state object switches itself to the next state.
Decorator versus Proxy?
Show answer
Decorator adds behaviour and stacks; Proxy controls access.
Takeaway Strategy vs State, Decorator vs Proxy, Adapter vs Facade and Factory vs Builder differ in intent.
Trigger phrase → pattern#
| Requirement says… | Reach for |
|---|---|
| "support multiple … types, add more later" | Strategy + Factory |
| "behaves differently when idle / running / out of stock" | State |
| "notify users when…" | Observer |
| "undo", "replay", "queue requests" | Command (+ Memento) |
| "escalate", "levels", "fall through" | Chain of Responsibility |
| "folders contain files and folders" | Composite |
| "add-ons", "toppings", "wrap with logging" | Decorator |
| "integrate legacy / external API" | Adapter |
| "exactly one …" | Singleton, but prefer DI |
| "object with many optional fields" | Builder |
Check yourself 2 questions
'Support multiple types, add more later'?
Show answer
Strategy + Factory.
'Notify users when…'?
Show answer
Observer.
Takeaway Requirement phrases map to patterns: multiple types → Strategy + Factory, state-dependent behaviour → State, notify → Observer.
Which pattern? A quick picker#
Check yourself 2 questions
Behaviour depends on state?
Show answer
State.
Create objects by type?
Show answer
Factory.
Takeaway Varying algorithm → Strategy; state-dependent → State; reactions → Observer; creation by type → Factory.
Vending machine state diagram#
stateDiagram-v2 direction LR [*] --> Idle Idle --> HasMoney: insertCoin HasMoney --> HasMoney: insertCoin HasMoney --> Dispensing: select, stock and funds ok HasMoney --> Idle: refund Dispensing --> Idle: dispense and return change
Check yourself 2 questions
What moves HasMoney to Dispensing?
Show answer
A selection with stock and enough funds.
How do you return from HasMoney to Idle?
Show answer
Refund.
Takeaway Idle → HasMoney on coins → Dispensing on a valid selection → Idle; refunds return to Idle.
Code smells and the refactoring that fixes them#
| Smell | Looks like | Refactoring |
|---|---|---|
| God class | One class with dozens of methods and fields across concerns | Extract class by responsibility; introduce a facade that delegates |
| Long method | A method that needs comments to explain its sections | Extract method per step; name the steps |
| Switch on type | if type == CAR … elif type == BIKE … repeated in several places | Replace conditional with polymorphism (Strategy or subclasses) |
| Primitive obsession | Money as double, IDs as raw strings, status as int | Introduce value objects and enums |
| Feature envy | A method mostly reads another object's data | Move the method to the class that owns the data |
| Data clumps / long parameter lists | The same 4–5 arguments passed together everywhere | Introduce a parameter object or builder |
| Shotgun surgery | One change requires edits in many classes | Move related behaviour together; one place per decision |
| Anemic domain model | Entities are bags of getters/setters; all logic in services | Move invariant-protecting behaviour into the entity |
| Hidden dependencies | new or singletons called deep inside methods | Constructor injection behind interfaces |
| Speculative generality | Abstract layers and patterns with a single implementation | Inline them until a second variation appears (YAGNI) |
Check yourself 2 questions
Fix for a god class?
Show answer
Extract classes by responsibility, with a facade delegating.
Fix for switch-on-type?
Show answer
Replace conditional with polymorphism (Strategy or State).
Takeaway God classes, long methods, switch-on-type and feature envy each have a standard refactoring.
Strategy + Factory (Java)#
interface PricingStrategy { Money price(Ride r); } class StandardPricing implements PricingStrategy { public Money price(Ride r){ return r.km().times(12); } } class SurgePricing implements PricingStrategy { private final double mult; SurgePricing(double m){ mult = m; } public Money price(Ride r){ return r.km().times(12 * mult); } } final class PricingFactory { static PricingStrategy forDemand(double ratio){ return ratio > 1.5 ? new SurgePricing(ratio) : new StandardPricing(); } } // RideService depends on PricingStrategy only (DIP); new rule = new class (OCP)
Check yourself 2 questions
What does the factory return?
Show answer
The right PricingStrategy implementation for the context.
Adding a new pricing rule needs what?
Show answer
A new class, without editing existing ones.
Takeaway An interface per algorithm, implementations per type, and a factory choosing one.
State machine (vending machine)#
interface State { default void insertCoin(Machine m, int c){ throw new IllegalStateException(); } default void select(Machine m, String code){ throw new IllegalStateException(); } default void dispense(Machine m){ throw new IllegalStateException(); } } class Idle implements State { public void insertCoin(Machine m, int c){ m.addBalance(c); m.setState(new HasMoney()); } } class HasMoney implements State { public void insertCoin(Machine m, int c){ m.addBalance(c); } public void select(Machine m, String code){ if (!m.inventory().available(code)) throw new OutOfStock(code); if (m.balance() < m.price(code)) throw new InsufficientFunds(); m.setSelection(code); m.setState(new Dispensing()); } } class Dispensing implements State { public void dispense(Machine m){ m.release(); m.returnChange(); m.setState(new Idle()); } } // Illegal transitions fail loudly; no if/else on a status enum
Check yourself 2 questions
What do default methods do in the State interface?
Show answer
Throw IllegalStateException for invalid actions.
Who switches the current state?
Show answer
The state objects, via the machine.
Takeaway Each state implements only valid actions; defaults throw for invalid ones.
Observer#
interface Subscriber { void onEvent(OrderEvent e); } class OrderPublisher { private final List<Subscriber> subs = new CopyOnWriteArrayList<>(); void subscribe(Subscriber s){ subs.add(s); } void publish(OrderEvent e){ for (Subscriber s : subs) s.onEvent(e); } } // CopyOnWriteArrayList: safe iteration while others subscribe. // Async delivery? hand events to an ExecutorService or a BlockingQueue.
Check yourself 2 questions
Why CopyOnWriteArrayList for subscribers?
Show answer
Safe iteration while subscribers are added or removed.
What does a subscriber implement?
Show answer
An onEvent method.
Takeaway Publishers hold a thread-safe list of subscribers and notify each on events.
Thread-safe Singleton#
// 1) Holder idiom: lazy, thread-safe, no locks final class IdGenerator { private IdGenerator() {} private static class Holder { static final IdGenerator I = new IdGenerator(); } static IdGenerator get(){ return Holder.I; } } // 2) Enum singleton: also safe against reflection/serialization enum Registry { INSTANCE; } // 3) Double-checked locking needs a volatile field // Python: a module-level instance is already a singleton.
Check yourself 2 questions
Why is the holder idiom thread-safe?
Show answer
Class loading initialises the holder once, safely.
Alternative Java singleton?
Show answer
An enum with one instance.
Takeaway The holder idiom gives lazy, lock-free, thread-safe initialisation; an enum also works.
04LLD problem breakdowns & patterns
SystemDesign/06-lld/06-problems/* (Key takeaways), LLD_Interview_Cheatsheet.md, 03-design-patterns
LLD problems: pattern + the gotcha#
| Problem | Patterns | Gotcha / key insight |
|---|---|---|
| Parking lot | Strategy (spot allocation), Factory, Singleton | ParkingLot → ParkingFloor → ParkingSpot; delegate, don't god-class |
| Rate limiter | Strategy | token bucket w/ lazy refill; ConcurrentHashMap per user |
| Tic-tac-toe | — | O(1) win check with row/col/diag counters |
| Vending machine | State | no if-else state; polymorphic states |
| Splitwise | Strategy (split types) | + minimise cash flow greedy on net balances |
| BookMyShow | Strategy, Observer | Seat vs ShowSeat; lock ShowSeat with TTL |
| Chess | Template, Factory | pieces validate geometry; Board validates path/check |
| Snake & ladder | — | single Jumper(start→end) class |
| Elevator | Strategy, State | SCAN/LOOK sweep with sorted sets, not FIFO |
| Comment system | Composite | materialised path for O(1) thread fetch |
| Hotel management | Strategy (pricing) | date-range overlap in availability |
| ATM | State, Chain (cash dispenser) | external BankService does atomic debit |
| LRU cache | — | HashMap + DLL with dummy head/tail; know the wiring cold |
| Food delivery | Strategy (dispatch), Observer (status) | focus on core models |
| Locker | Strategy | size ordering: S fits S/M/L/XL, L fits L/XL |
| Notification | Strategy, Observer, Factory | add WhatsAppStrategy without touching core |
| Coupon system | Strategy / Rule engine | coupons as DB rows → strategy, never hardcode |
| Logger | Chain of Responsibility, Strategy, Producer-Consumer | BlockingQueue for async |
| Library | — | Book vs BookItem (copies) |
| Order management | Saga / Command | OrderOrchestrator with compensating steps |
| Ride sharing | Strategy (match, price), State (ride) | black-box LocationService |
| Pub-sub | Observer | BlockingQueue per topic + worker |
| Inventory | — | available vs reserved vs purchased quantity |
Check yourself 2 questions
Parking lot gotcha?
Show answer
Delegate through Lot → Floor → Spot; don't build a god class.
Patterns for a parking lot?
Show answer
Strategy for spot allocation, Factory, Singleton.
Takeaway Each classic LLD problem has signature patterns and one gotcha.
Pattern trigger map (use at most 2)#
| Trigger phrase | Pattern |
|---|---|
| multiple algorithms / pricing / payment types | Strategy |
| create objects by type | Factory |
| notify on change / subscribe | Observer |
| single shared instance (config, registry) | Singleton (thread-safe) |
| many optional params | Builder |
| add behaviour dynamically (toppings, filters) | Decorator |
| behaviour depends on state (vending, ATM, order) | State |
| undo / queue requests | Command |
| pass through handlers (log levels, approvals) | Chain of Responsibility |
| tree of parts (folders, comments) | Composite |
Check yourself 2 questions
Why use at most two patterns?
Show answer
Over-patterning adds complexity without value.
Single shared instance trigger?
Show answer
Singleton.
Takeaway Map trigger phrases to patterns, and use at most two per problem.
SOLID + scoring signals#
- SRP one reason to change · OCP extend via new class · LSP subtypes substitutable · ISP small interfaces · DIP depend on abstractions
- Composition over inheritance; facade service as the entry point
- Value objects immutable (Money, Address); enums for statuses
- Thread-safety stated explicitly; no global mutable state
- Recovery line: "Let me simplify — I'll get the core flow working, then extend.
Check yourself 2 questions
ISP in one line?
Show answer
Small, focused interfaces.
What's the typical entry point to the design?
Show answer
A facade service.
Takeaway SOLID, composition over inheritance and a facade service as the entry point score well.
Class sketch: parking lot#
classDiagram
class ParkingLot{+park(v) Ticket +unpark(t) Fee}
class ParkingFloor{+findSpot(type) Spot}
class ParkingSpot{+type +isFree()}
class Ticket{+id +entryTime}
class PricingStrategy{+fee(t)}
ParkingLot "1" --> "*" ParkingFloor
ParkingFloor "1" --> "*" ParkingSpot
ParkingLot --> PricingStrategy
ParkingLot --> TicketCheck yourself 2 questions
Who finds a free spot?
Show answer
ParkingFloor.findSpot(type).
How is the fee computed?
Show answer
By a PricingStrategy.
Takeaway ParkingLot parks and unparks, floors find spots, tickets record entry, a pricing strategy computes fees.
05LLD problems: entities, APIs and the core move
For each classic problem: the classes to draw first, the methods to write first, and the part interviewers probe.
Problem playbook#
| Problem | Core entities | Key methods | Patterns | What they probe |
|---|---|---|---|---|
| Parking lot | ParkingLot, Floor, Spot(type), Vehicle, Ticket, FeeCalculator, Gate | park(vehicle) → Ticket, unpark(ticket) → Receipt | Strategy (allocation, fees), Factory, Singleton | Concurrent spot allocation; per-type free lists |
| Elevator | ElevatorSystem, Elevator, Request, Direction, Dispatcher, Door | request(floor, dir), step() | Strategy (dispatch), State (moving/idle/maintenance) | SCAN/LOOK scheduling, choosing the nearest same-direction car |
| BookMyShow / movie booking | Movie, Theatre, Screen, Show, Seat, ShowSeat, Booking, Payment | holdSeats(show, seats), confirm(bookingId) | Strategy (pricing), Observer | Seat hold with TTL; no double booking |
| Splitwise | User, Group, Expense, Split (Equal/Exact/Percent), BalanceSheet | addExpense(), balances(user), settle() | Strategy, Factory | Validate splits sum; simplify debts with heaps on net balance |
| Vending machine | Machine, State, Inventory, Product, Coin | insertCoin(), select(), dispense(), refund() | State | Illegal transitions; change-making |
| ATM | ATM, Card, Account, Transaction, CashDispenser, BankService | authenticate(), withdraw(amount) | State, Chain (note denominations) | Atomic debit + dispense; reversal on failure |
| Library management | Book, BookItem(copy), Member, Loan, Reservation, Fine | checkout(), return(), reserve() | Observer (availability), Strategy (fines) | Book vs BookItem; limits per member |
| Chess | Game, Board, Cell, Piece(subtypes), Move, Player | makeMove(from, to), isCheckmate() | Template, Factory, Command (undo) | Piece validates shape; board validates path and check |
| Tic-tac-toe (n×n) | Game, Board, Player, Move | move(r, c) → result | — | O(1) win check using row/col/diagonal counters |
| Snake & ladder | Game, Board, Jumper(start→end), Player, Dice | playTurn() | Strategy (dice) | One Jumper class covers snakes and ladders |
| LRU / LFU cache | Cache, Node, DoublyLinkedList, (freq buckets) | get(k), put(k, v) in O(1) | Strategy (eviction) | Map + DLL wiring; LFU min-freq tracking; thread safety |
| Rate limiter | RateLimiter, Bucket, Rule, Clock | allow(clientId) → bool | Strategy (algorithm) | Lazy refill; per-key locking; injectable clock |
| Logger | Logger, Level, Appender(console/file), Formatter | log(level, msg) | Chain, Strategy, Singleton, Producer-Consumer | Async appender with bounded queue; level filtering |
| Pub-sub / message queue | Broker, Topic, Partition, Message, Publisher, Subscriber, Offset | publish(topic, msg), subscribe(topic, s) | Observer | Per-subscriber offsets; ordering; back-pressure |
| Hotel booking | Hotel, Room(type), Booking, Guest, DateRange, Invoice | search(range, type), book(), cancel() | Strategy (pricing) | Date-range overlap check; holds |
| Ride sharing | Rider, Driver, Trip(state), Location, Matcher, Pricing | requestRide(), accept(), complete() | Strategy, State, Observer | Matching nearest available driver atomically |
| Food delivery | Restaurant, Menu, Order(state), Cart, DeliveryAgent, Dispatcher | placeOrder(), assignAgent(), track() | State, Strategy, Observer | Order lifecycle; reassignment on reject |
| File system | Entry (File / Directory), Path, Permissions | mkdir, ls, find(filter) | Composite, Specification | Recursive size; search filters composed with AND/OR |
| Task scheduler | Task, Trigger(once/cron), Scheduler, Worker, DelayQueue | schedule(task, at), cancel(id) | Command, Strategy | Min-heap by next run time; worker pool; retries |
| Shopping cart / inventory | Product, Cart, CartItem, Inventory, Order, Coupon | add(), checkout(), applyCoupon() | Strategy, Specification | Reserve vs purchased stock; coupon stacking rules |
| Notification service | Notification, Channel(Email/SMS/Push), Template, Preference | send(userId, event) | Strategy, Factory, Observer | Add a channel without touching core; retries, dedup |
| Stack Overflow | User, Question, Answer, Comment, Vote, Tag, Reputation | post(), vote(), accept() | Observer, Composite | One vote per user; reputation updates |
| Cricket scoreboard | Match, Innings, Over, Ball, Player, Scorecard | recordBall(event) | Observer, Command | Extras, wickets and strike rotation rules |
Check yourself 2 questions
Parking lot key methods?
Show answer
park(vehicle) → Ticket; unpark(ticket) → Receipt.
What do interviewers probe in a rate limiter?
Show answer
Algorithm choice, concurrency and per-key state.
Takeaway For each problem know the core entities, key methods, patterns and what the interviewer is probing.
LRU cache, O(1) (Python)#
class Node: __slots__ = ("k", "v", "prev", "next") def __init__(self, k=0, v=0): self.k, self.v, self.prev, self.next = k, v, None, None class LRUCache: def __init__(self, cap): self.cap, self.map = cap, {} self.head, self.tail = Node(), Node() # sentinels self.head.next, self.tail.prev = self.tail, self.head def _remove(self, n): n.prev.next, n.next.prev = n.next, n.prev def _add_front(self, n): n.next, n.prev = self.head.next, self.head self.head.next.prev = n; self.head.next = n def get(self, k): if k not in self.map: return -1 n = self.map[k]; self._remove(n); self._add_front(n); return n.v def put(self, k, v): if k in self.map: self._remove(self.map[k]) n = self.map[k] = Node(k, v); self._add_front(n) if len(self.map) > self.cap: lru = self.tail.prev; self._remove(lru); del self.map[lru.k] # Thread-safe: guard get/put with one lock (or striped locks per shard)
Check yourself 2 questions
Data structures for an O(1) LRU?
Show answer
A hash map plus a doubly linked list.
What happens on get?
Show answer
Move the node to the front (most recent).
Takeaway A hash map to nodes plus a doubly linked list with sentinels gives O(1) get and put.
Token-bucket rate limiter (Java, thread-safe)#
final class TokenBucket { private final long capacity; private final double refillPerNano; private double tokens; private long last; private final Clock clock; // injectable for tests TokenBucket(long cap, double perSec, Clock c){ capacity = cap; refillPerNano = perSec / 1e9; tokens = cap; clock = c; last = c.nanos(); } synchronized boolean tryAcquire(){ long now = clock.nanos(); tokens = Math.min(capacity, tokens + (now - last) * refillPerNano); // lazy refill last = now; if (tokens < 1) return false; tokens -= 1; return true; } } class RateLimiter { private final ConcurrentHashMap<String, TokenBucket> buckets = new ConcurrentHashMap<>(); boolean allow(String client){ return buckets.computeIfAbsent(client, k -> new TokenBucket(10, 5, Clock.SYSTEM)).tryAcquire(); } }
Variants and follow-ups
- Leaky bucket smooths output to a fixed rate; fixed window is simple but bursts at window edges.
- Sliding log is exact but stores every timestamp; sliding window counter approximates it with two counters.
- Distributed: keep the bucket in Redis and refill-and-take in one Lua script so it stays atomic.
- Memory: per-client buckets need eviction (expire idle keys).
- Response: return 429 with
Retry-Aftercomputed from the token deficit.
Check yourself 2 questions
How are tokens refilled?
Show answer
By elapsed time × refill rate, capped at capacity.
Why inject a Clock?
Show answer
So tests can control time.
Takeaway Refill tokens by elapsed time, take one per request, synchronise access and inject a clock for tests.
Parking lot class sketch (Java)#
enum SpotType { MOTORBIKE, COMPACT, LARGE } enum VehicleType { BIKE, CAR, TRUCK } record Ticket(String id, String spotId, VehicleType type, Instant in) {} interface SpotAllocator { Optional<Spot> allocate(VehicleType t); void release(Spot s); } interface FeePolicy { Money fee(Ticket t, Instant out); } final class ParkingLot { // facade private final SpotAllocator allocator; private final FeePolicy fees; private final Map<String, Ticket> active = new ConcurrentHashMap<>(); Ticket park(Vehicle v){ Spot s = allocator.allocate(v.type()).orElseThrow(LotFull::new); // atomic inside Ticket t = new Ticket(UUID.randomUUID().toString(), s.id(), v.type(), Instant.now()); active.put(t.id(), t); return t; } Receipt unpark(String ticketId){ Ticket t = Optional.ofNullable(active.remove(ticketId)).orElseThrow(InvalidTicket::new); allocator.release(spotOf(t)); return new Receipt(t, fees.fee(t, Instant.now())); } }
Check yourself 2 questions
Why use a record for Ticket?
Show answer
It's an immutable value.
What returns Optional in the sketch?
Show answer
The SpotAllocator, when no spot is free.
Takeaway Enums for spot and vehicle types, records for tickets, and an injectable SpotAllocator.
Tic-tac-toe with O(1) win check (Java)#
final class TicTacToe { private final int n; private final int[] rows, cols; private int diag, anti; TicTacToe(int n) { this.n = n; rows = new int[n]; cols = new int[n]; } /** player 1 or 2; returns the winner or 0. */ int move(int r, int c, int player) { int d = player == 1 ? 1 : -1; rows[r] += d; cols[c] += d; if (r == c) diag += d; if (r + c == n - 1) anti += d; int target = d * n; return (rows[r] == target || cols[c] == target || diag == target || anti == target) ? player : 0; } } // Validation (occupied cell, wrong turn, game over) lives in a Game class around this.
Check yourself 2 questions
How does the O(1) win check work?
Show answer
Add ±1 to the move's row, column and diagonals; |sum| = n means a win.
Space needed?
Show answer
O(n): row and column arrays plus two diagonals.
Takeaway Track row, column and diagonal sums per player: a sum of ±n means a win, checked in O(1).
Logger with chain of responsibility (Java)#
enum Level { DEBUG, INFO, WARN, ERROR } abstract class Handler { private Handler next; Handler then(Handler n) { this.next = n; return n; } void handle(Level lvl, String msg) { if (accepts(lvl)) write(lvl, msg); if (next != null) next.handle(lvl, msg); } abstract boolean accepts(Level lvl); abstract void write(Level lvl, String msg); } final class ConsoleHandler extends Handler { boolean accepts(Level l) { return l.compareTo(Level.INFO) >= 0; } void write(Level l, String m) { System.out.println(l + " " + m); } } final class AlertHandler extends Handler { boolean accepts(Level l) { return l == Level.ERROR; } void write(Level l, String m) { /* page on-call */ } } // chain: Handler root = new ConsoleHandler(); root.then(new AlertHandler()); // For throughput, put a BlockingQueue + writer thread in front (async appender).
Follow-ups
- Async appender: a bounded queue plus one writer thread; decide whether to block or drop when it is full.
- Configuration: levels per package, changeable at runtime without a restart.
- Formatting is a Strategy; extra sinks (file, network) are more handlers in the chain.
- Thread safety: a single writer thread, or synchronise each sink's write.
Check yourself 2 questions
Which pattern routes log levels?
Show answer
Chain of Responsibility.
How do handlers link?
Show answer
Each holds a next handler.
Takeaway Handlers handle levels they care about and pass messages down the chain.
In-memory pub-sub with per-subscriber offsets (Java)#
final class Topic { private final List<String> log = new CopyOnWriteArrayList<>(); // append-only void publish(String msg) { log.add(msg); } String read(int offset) { return offset < log.size() ? log.get(offset) : null; } } final class Subscriber implements Runnable { private final Topic topic; private final Consumer<String> handler; private final AtomicInteger offset = new AtomicInteger(); // own position private volatile boolean running = true; Subscriber(Topic t, Consumer<String> h) { topic = t; handler = h; } public void run() { while (running) { String m = topic.read(offset.get()); if (m == null) { LockSupport.parkNanos(1_000_000); continue; } // or wait/notify handler.accept(m); offset.incrementAndGet(); // commit after handling } } void resetOffset(int o) { offset.set(o); } // replay void stop() { running = false; } } // Each subscriber has its own offset, so slow ones don't block fast ones and can replay.
Check yourself 2 questions
Why per-subscriber offsets?
Show answer
Each subscriber reads independently and can replay.
What structure holds messages?
Show answer
An append-only list per topic.
Takeaway An append-only log per topic with per-subscriber offsets lets each consumer read at its own pace.
06Worked LLD designs: three walkthroughs and a booking flow
Requirements, class diagram, the code that interviewers actually probe, and the extensions to mention. Java, since most machine-coding rounds expect it.
Elevator system#
The core is a per-car scheduler (LOOK: keep going in one direction while stops remain) and a dispatcher that picks the cheapest car.
classDiagram
class ElevatorSystem {
+requestPickup(floor, dir)
+requestStop(carId, floor)
+tick()
}
class Dispatcher {
<<interface>>
+choose(cars, floor, dir) Elevator
}
class LeastCostDispatcher
class Elevator {
-int floor
-Direction dir
-TreeSet up
-TreeSet down
+addStop(floor)
+step()
+cost(floor, dir) int
}
class Direction {
<<enumeration>>
UP
DOWN
IDLE
}
ElevatorSystem "1" --> "*" Elevator
ElevatorSystem --> Dispatcher
Dispatcher <|.. LeastCostDispatcher
Elevator --> Direction
Requirements to confirm
- N cars, M floors; hall calls (floor + direction) and car calls (destination).
- Minimise wait time; no starvation; doors, capacity and maintenance mode as extensions.
- Single controller process; simulation driven by
tick().
Key decisions
- Two sorted sets per car (stops above, stops below) give O(log n) next-stop lookup.
- Dispatcher is a Strategy: nearest car, least cost, zoning.
- Car state (moving, doors open, maintenance) can become a State pattern.
Edge cases to test
- A call for the current floor while the doors are open.
- An opposite-direction hall call on the car's path: serve it only after the car turns.
- Every car busy or in maintenance: queue the call, never drop it.
- Repeated presses of the same button are idempotent.
- Emergency stop or overweight: hold the car and re-dispatch its hall calls.
Follow-ups to expect
- 100 floors and 8 cars: zone the building or add express cars.
- Testing the scheduler: drive it with a fake clock and
tick()so runs are deterministic. - Destination dispatch: riders enter the floor in the lobby, so you can group them by destination.
Elevator scheduling (LOOK)
enum Direction { UP, DOWN, IDLE } final class Elevator { private int floor = 0; private Direction dir = Direction.IDLE; private final TreeSet<Integer> up = new TreeSet<>(), down = new TreeSet<>(); synchronized void addStop(int f) { if (f > floor) up.add(f); else if (f < floor) down.add(f); if (dir == Direction.IDLE && f != floor) dir = f > floor ? Direction.UP : Direction.DOWN; } synchronized void step() { // one tick = one floor if (dir == Direction.UP) { if (up.isEmpty()) { dir = down.isEmpty() ? Direction.IDLE : Direction.DOWN; return; } floor++; if (up.remove(floor)) openDoors(); } else if (dir == Direction.DOWN) { if (down.isEmpty()) { dir = up.isEmpty() ? Direction.IDLE : Direction.UP; return; } floor--; if (down.remove(floor)) openDoors(); } } synchronized int cost(int f, Direction d) { // lower is better int dist = Math.abs(floor - f); if (dir == Direction.IDLE) return dist; boolean onTheWay = (dir == Direction.UP && d == Direction.UP && f >= floor) || (dir == Direction.DOWN && d == Direction.DOWN && f <= floor); return onTheWay ? dist : dist + 100; // penalise turning around } private void openDoors() { /* notify observers, start door timer */ } }
Dispatcher
interface Dispatcher { Elevator choose(List<Elevator> cars, int floor, Direction d); } final class LeastCostDispatcher implements Dispatcher { public Elevator choose(List<Elevator> cars, int floor, Direction d) { return cars.stream().min(Comparator.comparingInt(c -> c.cost(floor, d))).orElseThrow(); } }
Extensions to mention
- Capacity: skip hall calls when the car is full.
- Peak modes: park idle cars at the lobby in the morning.
- Fairness: age requests so far floors aren't starved.
- Concurrency: requests arrive on many threads; each car's state is guarded by its own lock.
Check yourself 2 questions
What does the LOOK algorithm do?
Show answer
Keeps moving in one direction while stops remain, then reverses.
What does the dispatcher choose?
Show answer
The cheapest car for each pickup request.
Takeaway A per-car LOOK scheduler plus a dispatcher that picks the cheapest car.
Movie ticket booking (BookMyShow)#
Model a seat per show separately from the physical seat, and make "hold these seats" all-or-nothing with an expiry.
classDiagram
class Show {
+String id
+Movie movie
+Screen screen
+Instant start
}
class Seat {
+String id
+SeatType type
}
class ShowSeat {
+Seat seat
+SeatStatus status
+Money price
}
class Booking {
+String id
+String userId
+List seats
+BookingStatus status
}
class BookingService {
+hold(showId, seatIds, userId) Hold
+confirm(holdId, payment) Booking
}
class SeatLockProvider {
<<interface>>
+lock(showId, seatIds, userId) bool
+unlock(showId, seatIds, userId)
}
Show "1" --> "*" ShowSeat
ShowSeat --> Seat
BookingService --> SeatLockProvider
BookingService --> Booking
Booking --> ShowSeat
Requirements to confirm
- Search shows by city/movie; view seat layout; select up to N seats; hold for 10 minutes; pay; confirm or release.
- No double booking under concurrent requests; price by seat type and show.
Key decisions
- Seat vs ShowSeat: the physical seat is shared across shows; status lives on ShowSeat.
- Locking behind an interface: in-memory for the interview, Redis or DB in production.
- Pricing as a Strategy (weekday, premium, surge); notifications via Observer.
- Money as integer minor units, never
double.
All-or-nothing seat lock with expiry
final class InMemorySeatLock implements SeatLockProvider { private record Lock(String user, Instant expiry) {} private final Map<String, Map<String, Lock>> locks = new ConcurrentHashMap<>(); private final Duration ttl; private final Clock clock; InMemorySeatLock(Duration ttl, Clock clock) { this.ttl = ttl; this.clock = clock; } public boolean lock(String show, List<String> seats, String user) { Map<String, Lock> m = locks.computeIfAbsent(show, k -> new HashMap<>()); synchronized (m) { // serialise per show only Instant now = clock.instant(); for (String s : seats) { Lock l = m.get(s); if (l != null && l.expiry().isAfter(now) && !l.user().equals(user)) return false; } for (String s : seats) m.put(s, new Lock(user, now.plus(ttl))); return true; } } public void unlock(String show, List<String> seats, String user) { Map<String, Lock> m = locks.get(show); if (m == null) return; synchronized (m) { seats.forEach(s -> m.computeIfPresent(s, (k, l) -> l.user().equals(user) ? null : l)); } } }
Confirm flow
- Check every seat is still locked by this user (not expired).
- Charge with an idempotency key.
- Mark ShowSeats BOOKED and save the booking in one transaction.
- Unlock; publish a BookingConfirmed event.
- On payment failure or timeout, release the lock and mark the booking FAILED.
Extensions to mention
- Distributed lock: Redis
SET key NX PXper seat, with the DB unique constraint as a safety net. - Waitlist via Observer when seats free up.
- Coupons as a rule engine.
Check yourself 2 questions
Why model ShowSeat separately from Seat?
Show answer
Availability is per show, not per physical seat.
How are holds made safe?
Show answer
All-or-nothing locking with an expiry.
Takeaway Model seat-per-show separately from the physical seat; holds are all-or-nothing with expiry.
Splitwise (expense sharing)#
Different split types are a Strategy with validation, balances are a ledger, and "settle up" is a greedy matching of debtors and creditors.
classDiagram
class ExpenseService {
+addExpense(groupId, paidBy, amount, splitType, details)
+balances(userId) Map
+settlePlan(groupId) List
}
class Expense {
+String id
+String paidBy
+long amountCents
+List splits
}
class Split {
<<abstract>>
+String userId
+long amountCents
}
class SplitStrategy {
<<interface>>
+compute(amount, users, details) List
}
class EqualSplit
class ExactSplit
class PercentSplit
class BalanceSheet {
+apply(Expense)
+net(userId) long
}
ExpenseService --> SplitStrategy
ExpenseService --> BalanceSheet
Expense "1" --> "*" Split
SplitStrategy <|.. EqualSplit
SplitStrategy <|.. ExactSplit
SplitStrategy <|.. PercentSplit
Requirements to confirm
- Users, groups, expenses paid by one user split equally, by exact amounts or by percentages.
- Show who owes whom; simplify debts to few transfers; record settlements.
Key decisions
- Store money as
longcents; give rounding remainders to the first participants deterministically. - Each strategy validates its input (exact amounts sum to the total; percentages sum to 100).
- Balances as net amount per user per group: positive is owed money, negative owes.
- Expenses are immutable; edits are reversal plus a new expense (audit trail).
Equal split with fair rounding
final class EqualSplit implements SplitStrategy { public List<Split> compute(long amount, List<String> users, Map<String, Long> ignored) { long base = amount / users.size(), rem = amount % users.size(); List<Split> out = new ArrayList<>(); for (int i = 0; i < users.size(); i++) out.add(new Split(users.get(i), base + (i < rem ? 1 : 0))); return out; // sums exactly to amount } }
Simplify debts
record Transfer(String from, String to, long cents) {} static List<Transfer> simplify(Map<String, Long> net) { // + owed, − owes PriorityQueue<long[]> cred = new PriorityQueue<>((a, b) -> Long.compare(b[1], a[1])); PriorityQueue<long[]> debt = new PriorityQueue<>((a, b) -> Long.compare(b[1], a[1])); List<String> ids = new ArrayList<>(net.keySet()); for (int i = 0; i < ids.size(); i++) { long v = net.get(ids.get(i)); if (v > 0) cred.add(new long[]{i, v}); else if (v < 0) debt.add(new long[]{i, -v}); } List<Transfer> out = new ArrayList<>(); while (!cred.isEmpty() && !debt.isEmpty()) { long[] c = cred.poll(), d = debt.poll(); long amt = Math.min(c[1], d[1]); out.add(new Transfer(ids.get((int) d[0]), ids.get((int) c[0]), amt)); if (c[1] > amt) cred.add(new long[]{c[0], c[1] - amt}); if (d[1] > amt) debt.add(new long[]{d[0], d[1] - amt}); } return out; // at most n − 1 transfers; the true minimum is NP-hard }
Check yourself 2 questions
Pattern for equal, exact and percent splits?
Show answer
Strategy, each with validation.
How does settle-up minimise transactions?
Show answer
Greedily match largest debtors with largest creditors.
Takeaway Split types are strategies with validation, balances are a ledger, and settle-up greedily matches debtors and creditors.
Booking flow as a sequence diagram#
sequenceDiagram participant U as User participant BS as BookingService participant L as SeatLockProvider participant P as PaymentGateway participant R as BookingRepository U->>BS: hold(showId, seats) BS->>L: lock(showId, seats, userId) L-->>BS: locked until T + 10 min BS-->>U: holdId U->>BS: confirm(holdId, paymentToken) BS->>L: still locked by this user? BS->>P: charge(amount, idempotencyKey) P-->>BS: success BS->>R: save booking and mark seats BOOKED BS->>L: unlock(showId, seats) BS-->>U: booking confirmed
Draw this after the class diagram: it proves the classes can actually carry out the use case and shows where the concurrency risk sits (between lock and confirm).
Check yourself 2 questions
What happens if payment fails?
Show answer
Release the seat locks.
When is the booking saved?
Show answer
After successful payment, via the repository.
Takeaway Hold seats with a lock provider, pay, then confirm and save; release locks on failure.
07Concurrency, atomicity & error paths
Correctness boundary#
| Problem | Mechanism | Invariant |
|---|---|---|
| Concurrent map update | Atomic map op / lock | Check-and-set is one operation. |
| Shared counter | Atomic integer / synchronized allocator | No lost or duplicate increments. |
| Multi-field transition | Lock or database transaction | No partial state visible. |
| Work queue | BlockingQueue / bounded channel | Backpressure and shutdown are defined. |
| Retryable command | Idempotency key + stored result | Retry returns same logical outcome. |
| External side effect | Outbox / saga boundary | Failure can be retried or compensated. |
Check yourself 2 questions
Concurrent map update mechanism?
Show answer
An atomic map operation (e.g. computeIfAbsent) or a lock.
Shared counter mechanism?
Show answer
An atomic integer or a synchronised allocator.
Takeaway Make check-and-set one operation: atomic map ops, atomic counters, locks or transactions.
Review questions#
- Who owns each mutable field?
- Can two requests race on the same object?
- What makes each method atomic?
- Can a retry duplicate an operation?
- Are terminal and invalid states explicit?
- Can dependencies be replaced in a unit test?
Check yourself 2 questions
Name a concurrency review question.
Show answer
Any of: who owns each mutable field, can two requests race, what makes the method atomic.
Why ask whether retries duplicate operations?
Show answer
Retries without idempotency cause double effects.
Takeaway Ask who owns each field, what races, what makes methods atomic, whether retries duplicate, and which states are terminal.
Optimistic vs pessimistic locking in code#
// Pessimistic: hold a lock for the whole read-modify-write synchronized (account) { account.debit(amount); } // Optimistic in memory: compare-and-swap loop AtomicReference<Balance> ref = new AtomicReference<>(start); while (true) { Balance cur = ref.get(); Balance next = cur.minus(amount); // immutable value if (ref.compareAndSet(cur, next)) break; // retry if someone else won } // Optimistic in the database: version column // UPDATE accounts SET balance = ?, version = version + 1 // WHERE id = ? AND version = ? -- 0 rows updated means retry
- Optimistic wins when conflicts are rare; pessimistic when contention is high or retries are expensive.
- Avoid deadlock under pessimistic locking: acquire locks in a global order (for example by account ID) or use
tryLockwith a timeout. - CAS can suffer the ABA problem; use a versioned reference such as
AtomicStampedReference.
Check yourself 2 questions
When prefer optimistic locking?
Show answer
Low contention.
What does the optimistic loop use?
Show answer
Compare-and-swap, retrying on conflict.
Takeaway Pessimistic holds a lock for the whole read-modify-write; optimistic retries a compare-and-swap.
08Concurrency toolkit
Machine-coding rounds increasingly ask "make it thread-safe". Know the primitive, the hazard it prevents, and the classic exercises.
Primitives: Java and Python#
| Need | Java | Python |
|---|---|---|
| Mutual exclusion | synchronized, ReentrantLock (tryLock, fairness) | threading.Lock / RLock |
| Many readers, one writer | ReentrantReadWriteLock, StampedLock | Lock + Condition (no built-in RW lock) |
| Limit concurrent access | Semaphore | threading.Semaphore |
| Wait for a condition | Condition.await/signal, wait/notifyAll | threading.Condition, Event |
| Lock-free counter | AtomicInteger, LongAdder (CAS) | Lock (GIL doesn't make += atomic) |
| Visibility | volatile, happens-before | — |
| Concurrent map | ConcurrentHashMap.compute/merge | dict + Lock |
| Hand-off queue | BlockingQueue (Array/Linked), DelayQueue | queue.Queue, PriorityQueue |
| Wait for N tasks | CountDownLatch, CyclicBarrier, Phaser | Barrier, concurrent.futures.wait |
| Thread pool | ExecutorService, CompletableFuture, virtual threads (21+) | ThreadPoolExecutor, ProcessPoolExecutor, asyncio |
Check yourself 2 questions
Many readers, one writer in Java?
Show answer
ReentrantReadWriteLock or StampedLock.
Mutual exclusion in Python?
Show answer
threading.Lock or RLock.
Takeaway Locks, read-write locks, conditions, semaphores, atomics and concurrent collections in both languages.
Hazards and how to prevent them#
| Hazard | Looks like | Prevention |
|---|---|---|
| Race condition | check-then-act, read-modify-write | Atomic op (CAS, computeIfAbsent) or one lock around both steps |
| Deadlock | Two threads hold locks the other needs | Global lock ordering, tryLock with timeout, fewer locks |
| Livelock | Threads keep yielding to each other | Randomised back-off |
| Starvation | A thread never gets the lock | Fair locks, bounded priorities |
| Visibility bug | Thread never sees a flag change | volatile, locks, atomics |
| Lost update | Two writers overwrite each other | Optimistic version check or row lock |
| ABA | CAS succeeds on a recycled value | Versioned/stamped references |
| Priority inversion | Low-priority holder blocks high priority | Priority inheritance, short critical sections |
Check yourself 2 questions
How do you prevent deadlock?
Show answer
Acquire locks in a global order, or use tryLock with timeouts.
Fix a check-then-act race?
Show answer
An atomic operation or one lock around both steps.
Takeaway Races, deadlocks, livelocks, starvation and visibility bugs each have a prevention.
Classic concurrency exercises#
| Problem | Core idea |
|---|---|
| Producer–consumer / bounded blocking queue | Lock + two conditions (notFull, notEmpty); loop on the predicate |
| Readers–writers | RW lock; decide reader vs writer preference |
| Dining philosophers | Order the forks or limit diners with a semaphore of N−1 |
| Print in order / FooBar / ZeroEvenOdd | Semaphores or condition hand-off between threads |
| Building H₂O | Semaphores (2 H, 1 O) + barrier |
| Multithreaded web crawler | Concurrent visited set + work queue + pool; stop when queue empty and no task in flight |
| Thread-safe LRU cache | One lock, or segment the key space into shards |
| Delayed task scheduler | Priority queue + condition wait until the earliest deadline |
Check yourself 2 questions
Producer–consumer core idea?
Show answer
A lock with two conditions (notFull, notEmpty), looping on the predicate.
Why loop on the predicate, not if?
Show answer
Spurious wakeups.
Takeaway Producer–consumer, readers–writers, dining philosophers and ordered printing are the classics.
Bounded blocking queue (Python)#
import threading from collections import deque class BoundedBlockingQueue: def __init__(self, capacity): self.q, self.cap = deque(), capacity self.lock = threading.Lock() self.not_full = threading.Condition(self.lock) self.not_empty = threading.Condition(self.lock) def enqueue(self, x): with self.not_full: while len(self.q) == self.cap: # while, not if: spurious wake-ups self.not_full.wait() self.q.append(x) self.not_empty.notify() def dequeue(self): with self.not_empty: while not self.q: self.not_empty.wait() x = self.q.popleft() self.not_full.notify() return x
Check yourself 2 questions
When does put() wait?
Show answer
While the queue is full.
What does take() signal after removing?
Show answer
notFull, waking a producer.
Takeaway A deque, a lock and two conditions; producers wait when full, consumers when empty.
Producer–consumer with a bounded queue#
flowchart TD P1["Producer 1"] --> Q[["Bounded blocking queue<br/>capacity N"]] P2["Producer 2"] --> Q Q --> W1["Consumer 1"] Q --> W2["Consumer 2"] Q -.->|"full: producers block"| P1 W1 -.->|"empty: consumers wait"| Q
The bound gives back-pressure; a poison pill or shutdown flag stops consumers cleanly.
Check yourself 2 questions
What happens when the queue is full?
Show answer
Producers block.
Why bound the queue?
Show answer
Backpressure, to cap memory and slow producers.
Takeaway A bounded queue gives backpressure: producers block when full, consumers when empty.
09Machine-coding round: structure, APIs, errors, tests
Machine-coding rounds (90–120 minutes, runnable code) reward a clean package layout, a working demo and easy extension more than clever algorithms.
Time plan (90 min)#
| Min | Do |
|---|---|
| 0–10 | Clarify scope; write the 4–6 must-have commands |
| 10–20 | Models (enums, value objects, entities) and interfaces |
| 20–65 | Services for the happy path; in-memory repositories |
| 65–80 | Driver/demo with the sample input; validation and exceptions |
| 80–90 | Extension point demo, concurrency note, cleanup |
Check yourself 2 questions
What happens in minutes 0–10?
Show answer
Clarify scope and write the 4–6 must-have commands.
Where does most time go?
Show answer
Services for the happy path, about minutes 20–65.
Takeaway Clarify and list commands, models and interfaces, happy-path services, then edge cases, tests and demo.
Package layout#
app/ model/ # entities, value objects, enums repository/ # interfaces + in-memory impls service/ # use cases (facade per aggregate) strategy/ # pluggable rules (pricing, matching) exception/ # domain exceptions Main # driver: parses commands, prints output
- Keep I/O in the driver only; services return values.
- One public method per use case.
Check yourself 2 questions
Where do pluggable rules go?
Show answer
The strategy package.
Where do in-memory implementations live?
Show answer
Under repository.
Takeaway model, repository, service, strategy, exception and a main or demo package.
Evaluation rubric#
- Runs end-to-end on the sample input
- Separation of concerns; no god class
- Extensible: a new type means a new class
- Meaningful names, small methods, no dead code
- Edge cases and errors handled explicitly
- Thread-safety called out where state is shared
- Tests or a demo that proves behaviour
Check yourself 2 questions
What shows extensibility?
Show answer
A new type means a new class, not edits.
First thing on the rubric?
Show answer
It runs end to end on the sample input.
Takeaway Runs end to end, separated concerns, extensible, clean names, edge cases and tests.
API and method design#
- Methods are verbs in domain language:
reserve(),settle(). - Return domain objects or results, never raw maps.
- Validate inputs at the boundary; constructors enforce invariants.
- Prefer immutable inputs and outputs (records, frozen dataclasses).
- Idempotent where retries are possible: pass a request ID.
- Pagination and filtering for list methods.
Check yourself 2 questions
What should methods return?
Show answer
Domain objects or results, never raw maps.
Where should inputs be validated?
Show answer
At the boundary; constructors enforce invariants.
Takeaway Verb methods in domain language, domain return types, validation at boundaries, immutable values.
Errors and edge cases#
- Domain exceptions (
SeatUnavailable,InsufficientFunds) over generic ones. - Decide: exception,
Optional, or result type. Be consistent. - Check: empty input, duplicates, not found, capacity full, invalid transition, concurrent conflict, partial failure.
- Roll back or compensate on partial failure; never leave half-updated state.
Check yourself 2 questions
Domain exception examples?
Show answer
SeatUnavailable, InsufficientFunds.
Name three edge cases to check.
Show answer
Any three of: empty input, duplicates, not found, capacity limits, concurrent access.
Takeaway Domain exceptions, a consistent error style, and checks for empty, duplicate, missing and capacity cases.
Testing the design#
- DIP pays off here: inject fakes for clock, repository, payment gateway.
- Unit-test each strategy and each state transition.
- Table-driven tests for rules (fees, splits, discounts).
- Concurrency test: N threads booking one seat → exactly one succeeds.
- Say which tests you would write even if time runs out.
Check yourself 2 questions
How does DIP help testing?
Show answer
You can inject fakes for clock, repository and payment gateway.
What suits fee or split rules?
Show answer
Table-driven tests.
Takeaway Inject fakes, unit-test strategies and transitions, use table-driven tests, and test concurrency.
10LLD last-minute checklist
LLD last-minute checklist#
- Confirm use cases before drawing classes.
- State invariants and who owns each piece of state.
- Separate entities, immutable values, services, and gateways.
- Define method signatures before implementation details.
- Use composition; choose at most two useful patterns.
- Make state transitions and invalid transitions explicit.
- State thread-safety and transaction boundaries.
- Dry-run normal, duplicate, invalid, concurrent, and failure cases.
Check yourself 2 questions
What comes before drawing classes?
Show answer
Confirming use cases.
What should be stated for each piece of state?
Show answer
Its invariants and owner.
Takeaway Confirm use cases, state invariants and ownership, separate building blocks, define signatures, then code.