SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • What is System Design?
  • High-Level Design (HLD)
  • Low-Level Design (LLD)
  • Functional vs Non-Functional Requirements
  • Back-of-the-Envelope Estimation
  • Numbers Every Engineer Should Know
  • SLA, SLO and SLI
  • Basic OS: Process, Thread, Memory
  • 30 Must-Know Concepts
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Introduction

Low-Level Design (LLD)

The inside of one part: classes, responsibilities, interfaces and the patterns that keep code easy to change.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Low-level design (LLD) is the design inside one part of a system: which classes exist, what each one is responsible for, how they connect, and which interfaces keep the code easy to change.

  • High-level design answers "which boxes, and how do they talk?". LLD answers "what is inside one box, and how do I write it so it stays clean?".
  • The tools: entities and responsibilities, interfaces, SOLID, composition, and a few well-known patterns (Strategy, Factory, Observer and others).
  • The goal: code where new behaviour arrives as new classes, not as edits to old, working ones.

02Concept: What is it?

Once the big picture is drawn (see High-Level Design (HLD)), someone still has to write the code inside each service. LLD is the plan for that code. It is about objects and their relationships: what data each one holds, what it can do, and who it depends on.

A good LLD is not about drawing nice diagrams. It is about making change cheap. Requirements will change next month: a new payment type, a new vehicle, a new notification channel. A design that handles this by adding a class is healthy. A design that handles it by editing five existing classes is a warning sign.

Where LLD sits
🧱HLDservices, databases, queues
→↓zoom into one service
🔬LLDclasses, interfaces, patterns
→↓then write
💻Code and teststhe real thing
Zoom in on one box from the high-level design and design what is inside it.

What an LLD usually contains

🧩Entities
The nouns of the problem: Vehicle, Ticket, Spot. Each gets a clear job.
🔗Relationships
Is-a (inheritance), has-a (composition) and uses (dependency).
🔌Interfaces
The contracts between parts, so one part can be swapped without touching the rest.
🗃️Data model
Fields and tables for what must be stored, at the level of columns and types.
🔄State and flow
Which states an object can be in, and which actions move it between them.
🛡️Errors and threads
What happens on bad input, and what happens when two threads touch the same object.
🧠Not the same as coding
LLD is the thinking before and during coding: who owns what. A clean LLD can be written in any language. The classes in this page use TypeScript-style code, but the ideas are the same in Java, C# or Python.

03Real-Life Example

🍵Designing the Inside of a Restaurant Kitchen
The restaurant owner has already decided on the big picture: a dining room, a kitchen, a storeroom and a delivery door (that is the HLD). Now the head chef plans the kitchen itself. Who works at which station? What does each station do, and what does it hand to the next? If a new dish needs grilling, does the chef rebuild the kitchen, or just add a cook at the grill station? A good kitchen layout lets you add a dish without rearranging everything. That is LLD.
Kitchen
Low-level design
A station (grill, salad, dessert)
A class with one clear responsibility
The order ticket passed between stations
An interface or message between classes
Any cook can run the grill station
Many classes implement one interface
Adding a new dish
Adding a new class, not editing old ones
A cook who does everything
A god class (a warning sign)
Two cooks reaching for one pan
Two threads sharing one object

A first look in code

A tiny, well-shaped design
interface PricingStrategy {
  price(minutes: number): number;
}

class HourlyPricing implements PricingStrategy {
  price(minutes: number) { return Math.ceil(minutes / 60) * 2; }
}

class Ticket {
  constructor(private pricing: PricingStrategy) {}
  fee(minutes: number) { return this.pricing.price(minutes); }
}

Ticket does not know how pricing works. To add a monthly-pass rule you write a new class that implements PricingStrategy. Ticket never changes.

04Why Do We Need It?

🔧Cheap changes
New features arrive as new classes. Old, tested code is left alone.
📖Readable code
Each class has a clear job and a clear name, so a new teammate can find things.
🧪Easy testing
Small classes with interfaces can be tested alone, using simple fakes for their neighbours.
🧑‍🤝‍🧑Team work
Agreed interfaces let two people build two classes at the same time.
🐞Fewer bugs
Low coupling means one change does not break ten other places.
🎤Interview signal
LLD rounds show whether you can turn a vague problem into clean, extendable code.
HLD decides where the boxes go. LLD decides whether the code inside each box will still be pleasant to change in a year.

05Where Do We Use It?

🧰Inside one service
Every microservice has its own model, services and adapters to design.
🎤LLD interview rounds
Parking lot, elevator, vending machine, library system, tic-tac-toe.
📝Design reviews
A short class diagram and a few interfaces, reviewed before a big feature is built.
♻️Refactoring
Spotting a god class or a long if/else chain and replacing it with interfaces.
📚Libraries and SDKs
Public interfaces must be stable. Their inside can change freely.
🎮Apps and games
Game entities, UI components and state machines are all LLD problems.

06Types / Parts / How It Works

How HLD and LLD differ

High-Level Design (HLD)Low-Level Design (LLD)
ScopeThe whole systemOne service, module or feature
PiecesServices, databases, caches, queuesClasses, interfaces, methods
Typical artifactsArchitecture diagram, data flow, API listClass diagram, sequence diagram, schema, code skeleton
AudienceArchitects, product, other teamsThe developers who write and review the code
Questions answeredWhere is data stored? How does it scale?Who owns this rule? How do I add a new type?
Done whenBoxes and flows meet the requirementsResponsibilities and interfaces are clear enough to code
If skippedThe system cannot scale or survive failuresThe code becomes tangled and hard to change

The five SOLID ideas

IdeaIn plain wordsA sign you broke it
Single responsibilityA class has one reason to changeA class that prints, saves and calculates
Open / closedOpen for extension, closed for editingAdding a type means editing an if/else chain
Liskov substitutionA subclass can stand in for its parent without surprisesA subclass that throws “not supported”
Interface segregationSmall, focused interfacesClasses forced to implement methods they never use
Dependency inversionDepend on interfaces, not on concrete classesnew MySqlDatabase() deep inside business logic

Relationships between classes

Three ways classes connect
Is-a (inheritance)
🚗Carextends Vehicle
Strong tie, hard to undo
Has-a (composition)
🎟️Ticketholds a PricingStrategy
Swap the part at any time
Uses (dependency)
🧾Receipt printertakes a Ticket as input
Short-lived, light
Prefer has-a (composition) over is-a (inheritance) when you can.

Patterns you will meet most

PatternOne lineUse it when
StrategySwap one rule for another behind an interfacePricing, sorting, routing, validation
FactoryOne place that decides which class to createThe type depends on input or config
ObserverMany listeners are told when something changesEvents, notifications, UI updates
StateAn object changes behaviour as its state changesVending machine, order status, elevator
BuilderBuild a complex object step by stepMany optional fields
DecoratorWrap an object to add behaviourLogging, caching, compression layers
AdapterMake one interface look like anotherWrapping a third-party library
CommandTurn an action into an objectUndo, queues, job scheduling
SingletonExactly one instance, sharedRarely. It hides dependencies and makes tests hard
Strong coupling Loose coupling Light dependency
VisualizerAdd a requirement and see how much code has to changePick a new requirement (electric vehicles, monthly pass, second entrance), then switch between the one-big-class design and the interface-plus-strategy design. Watch how many existing classes must be edited.
Design style
New requirements (pick any)
🧱ParkingLotedited
🧱Vehicleedited
🧱Ticketuntouched
existing code editednew classuntouched
Existing classes edited
2
risk of breaking old rules
Wiring files edited
0
where parts are plugged in
New classes
0
added beside, not inside
Open for extension
40/100
rough score, rules below
In the one-big-class design every new rule becomes another if/else branch inside ParkingLot (1 new branch now). 2 existing files were edited: ParkingLot, Vehicle. Each edit can break rules that already worked, and the class keeps growing.

A teaching model with fixed rules, not a measurement of real code. Score = 100 minus 30 for each existing class you must edit, minus 8 if only the wiring file changes. Real projects vary, but the direction is the same: new behaviour should arrive as new code, not as edits to old code.

07How to Use It / Steps / Implementation

An LLD routine you can repeat

  1. 1
    Clarify the requirements
    Ask what the feature must do, what is out of scope, and what is likely to change. Write 4 to 6 use cases.
  2. 2
    Find the entities
    Underline the nouns in the problem: Vehicle, Spot, Ticket, Payment. Most become classes.
  3. 3
    Find the behaviours
    Underline the verbs: park, leave, pay, calculate fee. Give each to the class that owns the data it needs.
  4. 4
    Define the relationships and interfaces
    Decide has-a, is-a and uses. Put an interface wherever you expect variation (pricing, payment, notification).
  5. 5
    Apply a pattern only where it earns its place
    Strategy for swappable rules, Factory for choosing types, State for lifecycles. Not everywhere.
  6. 6
    Walk through each use case
    Trace “a car enters, parks, leaves, pays” through your classes. Fix gaps in who calls whom.
  7. 7
    Test extension and concurrency
    Ask: how do I add one more vehicle type? What if two cars arrive at once and race for the same spot?

Worked example: a parking lot

The core classes
🏢ParkingLothas many Levels
→↓has
🅿️Levelhas many Spots
→↓has
🔲Spotsize, free or taken
→↓holds
🚗Vehicletype, plate
🎟️Ticketvehicle, spot, entry time
→↓priced by
🔌PricingStrategyinterface
→↓implemented by
⏱️HourlyPricingand later MonthlyPassPricing
→↓then
💳Paymentpays the fee
Pricing is an interface, so new rules are new classes.
Adding a new vehicle type touches very little
// 1. A new entry in the vehicle type list
enum VehicleType { Car, Bike, Truck, Electric }

// 2. Spots say which types they accept (data, not if/else)
class Spot {
  constructor(readonly accepts: Set<VehicleType>) {}
  canFit(v: Vehicle) { return this.accepts.has(v.type); }
}

// 3. If pricing differs, add one new class and register it
class EvChargingPricing implements PricingStrategy {
  price(minutes: number) { return Math.ceil(minutes / 60) * 3; }
}

ParkingLot, Level and Ticket are untouched. That is the open / closed idea in action.

⚠️Do not forget threads
Two entrances can try to give the same spot to two cars at once. Keep spot allocation in one place and protect it with a lock (or an atomic update). See Concurrency vs Parallelism.

08Key Terms to Know

TermMeaning in easy words
LLDLow-level design: the design of classes and interfaces inside one part of a system
EntityA thing in the problem that gets its own class, such as Ticket
ResponsibilityThe one job a class is trusted to do
InterfaceA contract listing what a class can do, without saying how
Inheritance (is-a)A class that extends another and takes on its behaviour
Composition (has-a)A class that holds other objects and uses them
CouplingHow much one class depends on another. Lower is better
CohesionHow well the parts inside one class belong together. Higher is better
SOLIDFive guidelines: single responsibility, open/closed, Liskov, interface segregation, dependency inversion
Dependency injectionPassing a class its helpers from outside instead of creating them inside
Design patternA named, reusable solution to a common design problem
God classOne huge class that knows and does too much
Class diagramA UML picture of classes, their fields, methods and relationships
Sequence diagramA UML picture of who calls whom, in order, for one use case

09Pros, Cons and Trade-offs

✅ Pros
  • Changes arrive as new classes, not edits
  • Easier to read, test and review
  • Lets several people work in parallel
  • Fewer ripple bugs from small changes
  • Shows clear thinking in interviews
⚠️ Cons
  • More classes and files to navigate
  • Over-design wastes time on changes that never come
  • Patterns add indirection that new readers must learn
  • A wrong abstraction is harder to undo than no abstraction
  • Needs discipline to keep interfaces small

Trade-offs

ChoiceWe gainWe lose
Interface + several classesEasy to extend and testMore files, a bit more setup
One simple classFast to write and readHard to extend once rules multiply
CompositionSwap parts at run timeMore wiring code
InheritanceShares code quicklyDeep trees are rigid and fragile
Dependency injectionEasy tests with fakesNeeds a place to wire things together
Design up frontFewer rewrites for stable problemsWasted effort if requirements shift
💡A good rule
Start simple. Add an interface when you see the second variation, not before. Wait until the shape of the change is clear.

10Common Problems and Mistakes

Common mistakes

  1. The god class. One class holds the data, the rules, the printing and the saving. Every change touches it.
  2. Deep inheritance. Vehicle → MotorVehicle → Car → ElectricCar → ... Small changes at the top break everything below.
  3. Patterns for their own sake. A Factory that creates one class, or a Strategy with one strategy, is noise.
  4. Ignoring concurrency. Two threads booking the same spot, seat or item is the classic LLD bug.
  5. No interface at the boundaries. Business code that calls a payment SDK or a database driver directly cannot be tested or swapped.
  6. Leaking internals. Public fields and methods that return internal lists let outsiders break your rules.
  7. Skipping edge cases. Full lot, lost ticket, invalid input, payment failure. Name them and say what happens.
  8. Jumping to code. Writing classes before agreeing the use cases, so the design fits the first idea, not the real need.

Things to watch

🧮Primitive obsession
Passing raw strings and numbers everywhere. A small Money or PlateNumber class can enforce its own rules.
🪢Circular dependencies
A needs B and B needs A. Introduce an interface or move shared logic to a third class.
🔒Singletons
Global state makes tests depend on each other. Prefer passing the object in.
🔁Copy-paste branches
The same if/else on a type in five places means a missing interface.

11Real-World Examples

🅿️Parking lot
The classic prompt: spots, tickets, pricing rules and gates. Tests extension and concurrency.
🛗Elevator
A state machine plus a scheduling strategy (which lift takes which request).
🥤Vending machine
A textbook State pattern: idle, has money, dispensing, out of stock.
📚Library system
Books, members, loans and fines. Shows relationships and business rules.
⭕Tic-tac-toe
A small board, a rule checker and players. Easy to extend to a bigger board or an AI player.
🚦Rate limiter and LRU cache
Small classes with a sharp interface, hidden data structures and thread-safety questions.

How an LLD interview is judged

Interviewers look forWhat it looks like
A clean modelSensible classes with clear names and one job each
ExtensibilityA new type or rule is a new class, not edits everywhere
Readable codeSmall methods, clear names, no clever tricks
Edge casesFull, empty, invalid, duplicate and failure paths handled
Not over-engineeredPatterns used where they help, and explained
Concurrency awarenessYou mention shared state and say how you would guard it
Mini case: why the interviewer asks 'what if we add a new vehicle?'
❓New vehicle typethe follow-up
→↓big if/else design
✏️Edit 5 classesrisky, many tests
→↓strategy design
➕Add 1 classold code untouched
They are testing whether your design is open for extension.

12Related Topics to Read Next

What is System Design?→

The big picture, and where HLD and LLD fit in it.

High-Level Design (HLD)→

The sibling topic: the boxes and flows around the code you design here.

Hexagonal Architecture→

Ports and adapters: interfaces at the edges of one service.

Layered (N-Tier) Architecture→

A common way to arrange classes inside a service.

Clean Architecture and Modular Monolith→

Keeping business rules independent of frameworks.

Domain-Driven Design (DDD)→

Finding the right entities and names for a business.

LRU Cache Design→

A popular LLD prompt with a data structure and a thread-safety angle.

Concurrency vs Parallelism→

What happens when two threads touch one object.

Rate Limiting→

Another common LLD prompt: a small class with swappable algorithms.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔LLD: the design inside one part: classes, interfaces, patterns.
  • ✔Steps: requirements, entities, behaviours, relationships, patterns, walk-through, extension and threads.
  • ✔SOLID: one job, extend don't edit, safe substitution, small interfaces, depend on interfaces.
  • ✔Prefer: composition over inheritance, interfaces at the edges.
  • ✔Patterns: Strategy, Factory, Observer, State, Builder, Decorator, Adapter, Command. Singleton with care.
  • ✔Smells: god class, long if/else on type, deep inheritance, public internals.
  • ✔Always ask: how do I add one more type? What if two threads arrive together?
  • ✔One line: “HLD picks the boxes; LLD makes sure what is inside each box can grow by adding, not editing.”
← Previous
High-Level Design (HLD)
Next →
Functional vs Non-Functional Requirements