Until now, this tutorial has worked at the level of boxes and arrows: load balancers, caches, databases, queues. That is High-Level Design (HLD). But somebody eventually has to write the code inside each box, and if the classes are tangled, every new feature becomes painful. Deciding which classes exist, what each one is responsible for, and how they talk to each other is Low-Level Design (LLD). Product companies in India (Flipkart, Swiggy, Razorpay, Uber and many others) often have a separate LLD or "machine coding" round, so this skill matters for placements as much as HLD does.
Low-Level Design is the detailed design of a single component: its classes and interfaces, their attributes and methods, the relationships between them, and the design principles and patterns that keep the code correct, readable and easy to extend.
HLD vs LLD
Aspect | High-Level Design | Low-Level Design |
|---|---|---|
Question answered | Which services, databases and infrastructure, and how does data flow between them? | Which classes and interfaces, and how do they collaborate inside one service? |
Building blocks | Load balancer, cache, queue, DB, CDN | Classes, interfaces, enums, methods, design patterns |
Main concerns | Scale, availability, latency, consistency | Correctness, readability, extensibility, testability, thread safety |
Artifacts | Architecture diagram, API list, data model, estimates | Class diagram, sequence diagram, working code |
Interview example | Design a URL shortener for 100M users | Design the classes for a parking lot, and code them |
The two are connected: the HLD says "there is a Booking service"; the LLD designs the Booking, Seat, PaymentProcessor and PricingStrategy classes inside it.
What a Good Low-Level Design Achieves
Correctness: it does what the requirements say, including edge cases (a full parking lot, an invalid ticket, two users booking the last seat at once).
Extensibility: a new requirement ("add electric-vehicle spots", "add WhatsApp notifications") means adding a class, not rewriting ten.
Readability: a new teammate can find where something happens from the class names alone.
Testability: each class can be tested on its own, with dependencies replaced by fakes.
Low coupling, high cohesion: each class does one focused job (cohesion) and knows as little as possible about other classes (coupling).
OOP Foundations (Quick Recap)
LLD rests on the four pillars of object-oriented programming. If any of these feel shaky, revise them in the OOP Concepts tutorial first.
Pillar | Meaning | Role in LLD |
|---|---|---|
Encapsulation | Keep data private, expose behaviour through methods | A |
Abstraction | Show what an object does, hide how | Code talks to |
Inheritance | A class reuses and specialises another | Use sparingly; only for true "is-a" relationships |
Polymorphism | One interface, many implementations, chosen at runtime | The key to adding features without editing existing code |
SOLID Principles
SOLID is a set of five principles popularised by Robert C. Martin. They are guidelines, not laws, but almost every LLD interview checks them.
S: Single Responsibility Principle
A class should have only one reason to change.
An Invoice class that calculates totals, formats a PDF and emails it has three reasons to change (tax rules, PDF layout, email provider). Split it into Invoice, InvoicePdfRenderer and InvoiceMailer.
O: Open/Closed Principle
Software entities should be open for extension but closed for modification.
Long if (type == "UPI") ... else if (type == "CARD") ... chains violate it: every new payment type edits the same method. Instead, define a PaymentMethod interface and add a new class per method.
L: Liskov Substitution Principle
Objects of a subclass must be usable wherever the parent type is expected, without breaking the program's correctness.
The classic violation: Square extends Rectangle. Code that sets width 5 and height 4 on a Rectangle expects area 20, but a Square forces both sides equal and breaks it. If a subclass has to throw "not supported" for a parent method (a Penguin that cannot fly()), the hierarchy is wrong.
I: Interface Segregation Principle
Clients should not be forced to depend on methods they do not use.
A huge Machine interface with print(), scan() and fax() forces a simple printer to implement fax. Prefer small interfaces: Printer, Scanner, Fax.
D: Dependency Inversion Principle
High-level modules should not depend on low-level modules; both should depend on abstractions.
An OrderService should depend on a PaymentGateway interface, and receive the concrete RazorpayGateway through its constructor (dependency injection). Then switching providers, or using a fake gateway in tests, needs no change to OrderService.
Other Useful Principles
Composition over inheritance: build behaviour by holding objects ("has-a") rather than extending classes ("is-a"). Deep inheritance trees are rigid; composed objects can be swapped at runtime.
DRY (Don't Repeat Yourself), KISS (Keep It Simple) and YAGNI (You Aren't Gonna Need It): do not build a plug-in framework for a requirement nobody asked for.
UML Class Diagrams in Text
In an interview you sketch classes quickly. The standard notation is the UML class diagram: a box with the class name, attributes and methods, where - means private, + public and # protected.
+---------------------------+
| ParkingSpot |
+---------------------------+
| - id: String |
| - type: SpotType |
| - vehicle: Vehicle |
+---------------------------+
| + isFree(): boolean |
| + park(v: Vehicle): void |
| + release(): void |
+---------------------------+
Relationships
Relationship | Meaning | UML symbol | Example |
|---|---|---|---|
Inheritance (generalisation) | "is-a" | Solid line, hollow triangle at parent |
|
Realisation | Class implements interface | Dashed line, hollow triangle |
|
Association | Objects know each other | Solid line (optional arrow) |
|
Aggregation | Weak "has-a": part can live without the whole | Hollow diamond at the whole |
|
Composition | Strong "has-a": part dies with the whole | Filled diamond at the whole |
|
Dependency | Temporarily uses another class (parameter, local variable) | Dashed arrow |
|
Multiplicity is written at line ends: 1, 0..1, * (many), 1..*. For example, one ParkingLot 1 ◆—— 1..* Floor.
Design Patterns You Will Use Most
Design patterns are proven, named solutions to recurring design problems, catalogued in the 1994 "Gang of Four" book. You do not need all 23 for interviews; these appear again and again.
Pattern | Type | Problem it solves | Typical LLD use |
|---|---|---|---|
Singleton | Creational | Exactly one shared instance | Configuration, a single |
Factory | Creational | Hide which concrete class is created |
|
Builder | Creational | Construct objects with many optional fields readably |
|
Strategy | Behavioural | Swap an algorithm at runtime | Pricing (hourly vs flat), spot allocation, payment methods |
Observer | Behavioural | Notify many listeners when something changes | Display boards updating when a spot frees up; stock price alerts |
State | Behavioural | Behaviour depends on current state | Vending machine, elevator, order lifecycle |
Command | Behavioural | Wrap a request as an object (undo, queue) | Text editor undo/redo |
Chain of Responsibility | Behavioural | Pass a request along handlers | ATM cash dispenser (₹500, ₹200, ₹100 notes), logging levels |
Decorator | Structural | Add responsibilities without subclass explosion | Coffee + milk + sugar pricing |
Adapter | Structural | Make an incompatible interface fit | Wrapping a third-party SMS SDK behind your own interface |
A warning: patterns are tools, not goals. Interviewers are not impressed by forcing five patterns into a small problem. Use one when it clearly removes a problem, and say why.
Worked Example: A Notification Module
Requirement: when an order ships, notify the user on their chosen channels (email, SMS, push). New channels will be added later. SMS messages must be short.
Step 1, find the nouns and verbs. Nouns: user, order, notification, channel, message. Verbs: notify, send, format.
Step 2, assign responsibilities.
NotificationChannel(interface): knows how to send on one channel. Each channel class handles its own quirks (SMS trimming).MessageTemplate: knows how to format text. (SRP)ChannelFactory: knows how to create a channel from a name. (Factory)NotificationService: coordinates; depends only on the interface, injected via the constructor. (DIP)
<<interface>>
NotificationChannel NotificationService
+ send(user, message) <------------------ - channels: List<NotificationChannel>
^ - template: MessageTemplate
.........:.......... + notifyShipped(user, orderId)
: : :
EmailChannel SmsChannel PushChannel ChannelFactory ---creates---> channels
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
// A plain data holder (Java 16+ record)
record User(String name, String email, String phone, String deviceId) {}
// Abstraction: every channel can send a message (Open/Closed + Dependency Inversion)
interface NotificationChannel {
String name();
void send(User user, String message);
}
class EmailChannel implements NotificationChannel {
public String name() { return "EMAIL"; }
public void send(User user, String message) {
System.out.println("[EMAIL to " + user.email() + "] " + message);
}
}
class SmsChannel implements NotificationChannel {
public String name() { return "SMS"; }
public void send(User user, String message) {
// SMS has a length limit, so this class alone knows how to trim
String text = message.length() > 40 ? message.substring(0, 37) + "..." : message;
System.out.println("[SMS to " + user.phone() + "] " + text);
}
}
class PushChannel implements NotificationChannel { // added later: no channel or service class changed
public String name() { return "PUSH"; }
public void send(User user, String message) {
System.out.println("[PUSH to " + user.deviceId() + "] " + message);
}
}
// Factory: creation logic lives in one place
final class ChannelFactory {
private static final Map<String, NotificationChannel> CHANNELS = Map.of(
"EMAIL", new EmailChannel(),
"SMS", new SmsChannel(),
"PUSH", new PushChannel());
private ChannelFactory() {}
static NotificationChannel of(String type) {
NotificationChannel c = CHANNELS.get(type);
if (c == null) throw new IllegalArgumentException("Unknown channel: " + type);
return c;
}
}
// Single responsibility: this class only formats messages
class MessageTemplate {
String orderShipped(User user, String orderId) {
return "Hi " + user.name() + ", your order " + orderId + " has been shipped and arrives in 2 days.";
}
}
// High-level service depends on the abstraction, injected through the constructor
class NotificationService {
private final List<NotificationChannel> channels;
private final MessageTemplate template;
NotificationService(List<NotificationChannel> channels, MessageTemplate template) {
this.channels = channels;
this.template = template;
}
void notifyShipped(User user, String orderId) {
String msg = template.orderShipped(user, orderId);
for (NotificationChannel c : channels) {
c.send(user, msg);
}
}
}
public class NotificationDemo {
public static void main(String[] args) {
List<NotificationChannel> prefs = new ArrayList<>();
for (String type : List.of("EMAIL", "SMS", "PUSH")) {
prefs.add(ChannelFactory.of(type));
}
NotificationService service = new NotificationService(prefs, new MessageTemplate());
User asha = new User("Asha", "asha@example.com", "+91-98xxxxxx01", "android-7f3a");
service.notifyShipped(asha, "OD-1029");
try {
ChannelFactory.of("FAX");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
[EMAIL to asha@example.com] Hi Asha, your order OD-1029 has been shipped and arrives in 2 days.
[SMS to +91-98xxxxxx01] Hi Asha, your order OD-1029 has been ...
[PUSH to android-7f3a] Hi Asha, your order OD-1029 has been shipped and arrives in 2 days.
Error: Unknown channel: FAX
Why this design is good:
Adding WhatsApp means one new class plus one line in the factory.
NotificationService,MessageTemplateand the other channels are untouched (Open/Closed).In a unit test, you can pass a fake channel that records messages instead of sending them (Dependency Inversion makes the class testable).
The SMS length rule lives only in
SmsChannel, so it cannot leak into or break email (high cohesion).The factory throws a clear error for an unknown channel instead of failing silently.
Compare with the "beginner" version: a single NotificationService.send(String type, ...) containing an if/else per channel, the formatting code, and the SMS trimming. It works for the demo but every change edits the same fragile method.
How to Approach an LLD Interview
Clarify requirements (3 to 5 minutes). List the use cases you will support and the ones you will not. "Do we need payments? Multiple floors? Reservations?"
Identify entities. Underline nouns in the requirements; they become candidate classes and enums.
Identify behaviours. Verbs become methods. Decide which class owns each behaviour (the one that has the data it needs).
Define relationships. Inheritance only for true "is-a"; otherwise composition. Draw a quick class diagram.
Spot variation points. Wherever the interviewer might say "what if we add X?", put an interface (Strategy, Factory, State).
Write the core code. Clean names, small methods, enums for fixed sets, exceptions for invalid input. Machine-coding rounds expect code that compiles and runs with a small demo in
main.Handle concurrency. If two threads can grab the same seat or spot, say how you prevent it (synchronized methods, locks, atomic operations, or database constraints).
Walk through a scenario and discuss extensions.
The next chapter, LLD: Design a Parking Lot, applies exactly these steps to the most famous LLD question.
Common Mistakes
Jumping into code before agreeing on requirements and entities.
God classes: one
Managerclass that does everything.Inheritance for code reuse where there is no real "is-a" (a
Stack extends ArrayListwould exposeadd(index, x)andremove(index), which break stack behaviour; Java's own legacyjava.util.Stack extends Vectorhas exactly this flaw, which is whyArrayDequeis recommended instead).Public mutable fields instead of methods that protect invariants.
Pattern stuffing: adding patterns that solve no stated problem.
Using strings for fixed categories (
"CAR","BIKE") everywhere instead of enums; typos become runtime bugs.Ignoring concurrency in booking-style problems.
Interview Questions
1. What is the difference between HLD and LLD?
HLD decides the system's components (services, databases, caches, queues) and how data flows between them, focusing on scale and availability. LLD designs the inside of one component: classes, interfaces, relationships and patterns, focusing on correctness, extensibility and code quality.
2. Explain the Open/Closed Principle with an example.
Code should be open to extension and closed to modification. A discount calculator with an if/else per festival must be edited for every new sale. With a DiscountStrategy interface and one class per discount type, a new sale is a new class; the calculator never changes.
3. What is the difference between aggregation and composition?
Both are "has-a". In aggregation the part can exist independently (a team and its players). In composition the part's lifetime is bound to the whole (an order and its order lines; delete the order and the lines go too). UML uses a hollow diamond for aggregation and a filled diamond for composition.
4. Why is "composition over inheritance" recommended?
Inheritance fixes behaviour at compile time and couples the subclass to the parent's internals, so changes ripple down the hierarchy. Composition lets you assemble behaviour from small objects and swap them at runtime (for example, inject a different pricing strategy), which is more flexible and easier to test.
5. When would you use the Strategy pattern versus the State pattern?
Both put behaviour behind an interface. Strategy is chosen by the client, usually once, to select an algorithm (pricing, sorting). State changes by itself as the object moves through a lifecycle (a vending machine going from Idle to HasMoney to Dispensing), and each state decides the next state.
6. Why can a Singleton be considered an anti-pattern?
It is global mutable state: any code can reach it, which hides dependencies, makes unit testing hard (you cannot easily substitute a fake) and needs care for thread-safe creation. Prefer creating one instance at startup and injecting it where needed.
Summary
LLD designs classes, interfaces and their relationships inside one component; HLD designs the components themselves.
Goals: correctness, extensibility, readability, testability, low coupling and high cohesion.
SOLID: single responsibility, open/closed, Liskov substitution, interface segregation, dependency inversion.
Prefer composition over inheritance; use enums for fixed categories.
UML class diagrams show classes plus inheritance, realisation, association, aggregation, composition and dependency.
Most-used patterns: Factory, Builder, Singleton, Strategy, Observer, State, Decorator, Adapter. Use them only to solve a real problem.
Interview flow: requirements → entities → behaviours → relationships → variation points → code → concurrency → extensions.
Good low-level design means the next requirement is a new class, not a risky edit to an old one.