What is low-level design?
What low-level design is, how it differs from system design, the two kinds of LLD interview (OOD discussion and machine coding), and how this course is laid out.
On this page
- The problem: code that works on day one and fights you on day ninety
- The idea: zoom into one box and design the classes inside
- The same checkout, designed
- LLD and system design: two zoom levels
- The kinds of LLD interview
- A method you can repeat in every round
- How this course is organised
- Where this breaks
- When a little design is enough
- In the interview
- Quiz
The problem: code that works on day one and fights you on day ninety
A small online shop writes its checkout in one class. OrderManager adds up the cart, charges the card, emails a receipt and updates stock. It is 200 lines, it works, and it ships.
Then the change requests arrive. "Add PayPal." "Also send an SMS." "Students get 10% off." "The tax rate changed." Each one is a few lines, and each one goes into the same class, because that is where everything lives:
void checkout(String paymentType) {
double total = calcTotal();
if (isStudent) total = total * 0.9; // added in March
if (paymentType.equals("card")) {
// 40 lines of card code
} else if (paymentType.equals("paypal")) { // added in April
// 40 lines of PayPal code
}
sendEmail(customer);
if (wantsSms) sendSms(customer); // added in May
updateStock(items);
}
Three months later the class is 400 lines. Every change means reading most of it to find the right spot, every change risks breaking a feature that has nothing to do with it, and two developers working on two features edit the same file and collide.
One giant class: every change edits it
- Any design works on day one. The real test is change. Your boss says: “add PayPal”. If one giant class does everything, you must open it, read hundreds of lines, edit them, and hope nothing else breaks.
Nothing here is a bug. The code does what it should. The problem is shape: how the code is split up decides how expensive every future change is. Deciding that shape on purpose is low-level design.
The idea: zoom into one box and design the classes inside
In system design you draw boxes: phones, load balancers, an order service, a database. Low-level design (LLD) zooms into one of those boxes and asks how the code inside it should be organised.
Low-level design zooms into one box
- In system design you drew big boxes: phones, servers, databases. Low-level design zooms into one of those boxes and asks a different question: how should the code inside be organised?
Inside, object-oriented code is made of classes. A class bundles some data (its fields) with the things it can do (its methods). At run time the program creates objects from those classes, and the objects work by calling each other's methods. An interface is a promise of which methods a class has, without saying how they work.
Classes hold data and behaviour, and call each other
- Inside, the code is split into classes. A class is a small machine with its own data, called fields, and things it can do, called methods.
- Classes work together by calling each other’s methods. You can picture each call as a little message: Order asks Payment to take 42 dollars, then asks Email to send a receipt.
So an LLD answer is a set of decisions:
- Which classes exist, and what each one is responsible for.
- What each class knows (its fields) and what it can do (its public methods).
- How they relate: who holds a reference to whom, who creates whom, what is shared.
- Where the seams are: which parts are likely to change, and the interfaces that let them change without disturbing the rest.
What "good" means
Any design works on the day it is written. A good one keeps working as requirements change. Four properties to aim for:
| Property | The question to ask | Sign it is missing |
|---|---|---|
| Easy to change | Does a new requirement touch one or two small places? | Every feature edits the same big class |
| Easy to test | Can I test the price maths without a real card or email server? | Tests need a database and a network to run |
| Easy to understand | Can a newcomer guess where a feature lives from the class names? | Names like Manager, Helper, Utils that hold everything |
| Correct under concurrency | What happens if two requests touch the same object at once? | Two cars are given the last parking spot |
Two words you will hear in every LLD discussion describe the first three:
- Cohesion: how closely the contents of one class belong together. High cohesion means a class has one clear job.
PriceCalculatoris cohesive;OrderManagerabove is not. - Coupling: how much one class depends on the details of another. Low coupling means you can change one class without editing its neighbours.
The target is always high cohesion, low coupling. Most of this course (encapsulation, interfaces, SOLID, the design patterns) is a collection of techniques for getting there.
The same checkout, designed
Here is the shop again, split into small classes. Each thing that is likely to vary (how we take payment, how we notify, which discounts apply) sits behind a small interface. CheckoutService coordinates the steps but knows none of the details.
The good design: PayPal is one new class
- In a good design the same change touches one small place, often just one brand-new class. Nothing that already works gets edited, so nothing that already works can break.
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
// What varies sits behind small interfaces
interface PaymentMethod { void pay(BigDecimal amount); }
interface Notifier { void send(String to, String text); }
interface DiscountRule { BigDecimal apply(BigDecimal subtotal); }
record Item(String name, BigDecimal price, int qty) {
BigDecimal lineTotal() { return price.multiply(BigDecimal.valueOf(qty)); }
}
class Order {
private final String customerEmail;
private final List<Item> items = new ArrayList<>();
Order(String customerEmail) { this.customerEmail = customerEmail; }
void addItem(Item item) { items.add(item); }
List<Item> items() { return List.copyOf(items); }
String customerEmail() { return customerEmail; }
}
// One job: work out what the customer owes
class PriceCalculator {
private final BigDecimal taxRate;
private final List<DiscountRule> rules;
PriceCalculator(BigDecimal taxRate, List<DiscountRule> rules) {
this.taxRate = taxRate;
this.rules = List.copyOf(rules);
}
BigDecimal total(List<Item> items) {
BigDecimal sum = BigDecimal.ZERO;
for (Item i : items) sum = sum.add(i.lineTotal());
for (DiscountRule r : rules) sum = r.apply(sum);
return sum.multiply(BigDecimal.ONE.add(taxRate)).setScale(2, RoundingMode.HALF_UP);
}
}
class CardPayment implements PaymentMethod {
private final String cardToken;
CardPayment(String cardToken) { this.cardToken = cardToken; }
public void pay(BigDecimal amount) { System.out.println("Card " + cardToken + " charged " + amount); }
}
class EmailNotifier implements Notifier {
public void send(String to, String text) { System.out.println("Email to " + to + ": " + text); }
}
// Coordinates the steps; knows none of the details
class CheckoutService {
private final PriceCalculator prices;
private final PaymentMethod payment;
private final Notifier notifier;
CheckoutService(PriceCalculator prices, PaymentMethod payment, Notifier notifier) {
this.prices = prices;
this.payment = payment;
this.notifier = notifier;
}
BigDecimal checkout(Order order) {
BigDecimal total = prices.total(order.items());
payment.pay(total);
notifier.send(order.customerEmail(), "Thanks! You paid " + total);
return total;
}
}
// Change requests arrive as new classes
class PayPalPayment implements PaymentMethod {
private final String account;
PayPalPayment(String account) { this.account = account; }
public void pay(BigDecimal amount) { System.out.println("PayPal " + account + " charged " + amount); }
}
class StudentDiscount implements DiscountRule {
public BigDecimal apply(BigDecimal subtotal) { return subtotal.multiply(new BigDecimal("0.90")); }
}
public class Main {
public static void main(String[] args) {
Order order = new Order("asha@example.com");
order.addItem(new Item("Notebook", new BigDecimal("4.50"), 2));
order.addItem(new Item("Pen", new BigDecimal("1.25"), 4));
PriceCalculator prices = new PriceCalculator(new BigDecimal("0.18"), List.of());
new CheckoutService(prices, new CardPayment("tok_42"), new EmailNotifier()).checkout(order);
// Card tok_42 charged 16.52
// "Add PayPal" and "10% student discount": two new classes, plus this wiring
PriceCalculator studentPrices = new PriceCalculator(new BigDecimal("0.18"), List.of(new StudentDiscount()));
new CheckoutService(studentPrices, new PayPalPayment("asha@pp"), new EmailNotifier()).checkout(order);
// PayPal asha@pp charged 14.87
}
}from abc import ABC, abstractmethod
from dataclasses import dataclass
from decimal import Decimal, ROUND_HALF_UP
# What varies sits behind small interfaces
class PaymentMethod(ABC):
@abstractmethod
def pay(self, amount: Decimal) -> None: ...
class Notifier(ABC):
@abstractmethod
def send(self, to: str, text: str) -> None: ...
class DiscountRule(ABC):
@abstractmethod
def apply(self, subtotal: Decimal) -> Decimal: ...
@dataclass(frozen=True)
class Item:
name: str
price: Decimal
qty: int
def line_total(self) -> Decimal:
return self.price * self.qty
class Order:
def __init__(self, customer_email: str):
self.customer_email = customer_email
self._items: list[Item] = []
def add_item(self, item: Item) -> None:
self._items.append(item)
def items(self) -> list[Item]:
return list(self._items)
class PriceCalculator: # one job: what the customer owes
def __init__(self, tax_rate: Decimal, rules: list[DiscountRule]):
self._tax_rate = tax_rate
self._rules = list(rules)
def total(self, items: list[Item]) -> Decimal:
amount = sum((i.line_total() for i in items), Decimal("0"))
for rule in self._rules:
amount = rule.apply(amount)
return (amount * (1 + self._tax_rate)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
class CardPayment(PaymentMethod):
def __init__(self, card_token: str):
self._card_token = card_token
def pay(self, amount: Decimal) -> None:
print(f"Card {self._card_token} charged {amount}")
class EmailNotifier(Notifier):
def send(self, to: str, text: str) -> None:
print(f"Email to {to}: {text}")
class CheckoutService: # coordinates; knows none of the details
def __init__(self, prices: PriceCalculator, payment: PaymentMethod, notifier: Notifier):
self._prices = prices
self._payment = payment
self._notifier = notifier
def checkout(self, order: Order) -> Decimal:
total = self._prices.total(order.items())
self._payment.pay(total)
self._notifier.send(order.customer_email, f"Thanks! You paid {total}")
return total
# Change requests arrive as new classes
class PayPalPayment(PaymentMethod):
def __init__(self, account: str):
self._account = account
def pay(self, amount: Decimal) -> None:
print(f"PayPal {self._account} charged {amount}")
class StudentDiscount(DiscountRule):
def apply(self, subtotal: Decimal) -> Decimal:
return subtotal * Decimal("0.90")
if __name__ == "__main__":
order = Order("asha@example.com")
order.add_item(Item("Notebook", Decimal("4.50"), 2))
order.add_item(Item("Pen", Decimal("1.25"), 4))
prices = PriceCalculator(Decimal("0.18"), [])
CheckoutService(prices, CardPayment("tok_42"), EmailNotifier()).checkout(order)
# Card tok_42 charged 16.52
# "Add PayPal" and "10% student discount": two new classes, plus this wiring
student_prices = PriceCalculator(Decimal("0.18"), [StudentDiscount()])
CheckoutService(student_prices, PayPalPayment("asha@pp"), EmailNotifier()).checkout(order)
# PayPal asha@pp charged 14.87Counting the cost of the four change requests
The worked example: ship the same four requests against each design and count what you touch.
| Change request | One giant class | Small classes |
|---|---|---|
| Add PayPal | Edit OrderManager (new branch) | New PayPalPayment; one wiring line |
| Also send an SMS | Edit OrderManager | New SmsNotifier; one wiring line |
| 10% student discount | Edit OrderManager | New StudentDiscount; one wiring line |
| Change the tax rate | Edit OrderManager | Change one configuration value |
| Old classes edited | 4 edits to the same 400-line class | 0 (only the setup code that builds the objects) |
| Re-test | Everything in checkout, four times | The new class, plus one end-to-end test |
Notice the honest detail in the right-hand column: something still changes, namely the place where objects are created and plugged together (often called the composition root: main, a factory, or a dependency-injection container). Good design does not make change free. It moves change to small, predictable places.
LLD and system design: two zoom levels
Both are "design", but they answer different questions with different tools. Interviewers expect you to stay at the right level.
| System design (HLD) | Low-level design (LLD) | |
|---|---|---|
| The question | Which machines and services, and how does data flow between them? | Which classes inside one program, and how do they collaborate? |
| Building blocks | Services, databases, caches, queues, load balancers | Classes, interfaces, enums, methods, design patterns |
| Drawn as | Boxes and arrows between servers | Class diagrams, sequence diagrams, state diagrams |
| Worries about | Scale, latency, availability, consistency across machines | Responsibilities, coupling, extensibility, thread safety inside one process |
| Numbers | Requests per second, terabytes, milliseconds | Rarely; occasionally time complexity of a key method |
| Typical prompt | "Design WhatsApp" | "Design a parking lot", "Implement an LRU cache" |
| Output | A diagram and a spoken justification | A class design, and often working code |
The boundary is not sharp. A parking lot LLD still asks "what if two gates assign the same spot?", which is a concurrency question; a WhatsApp HLD still has an API, which is an interface. A useful rule: if the answer involves a network hop, it is HLD; if it lives inside one process, it is LLD.
The kinds of LLD interview
"LLD round" means different things at different companies. Ask the recruiter which one you are getting, because they reward different things.
| Format | Length | What you produce | What they grade |
|---|---|---|---|
| Object-oriented design (OOD) discussion | 45–60 min | Requirements, a class diagram on a whiteboard, the key method signatures, maybe one method in code | Clear entities and responsibilities, sensible relationships, how the design absorbs a new requirement |
| Machine coding | 60–120 min (90 is common) | A working program in an IDE, usually in-memory, with a small driver or tests that you run and demo | Code that runs; clean separation; extensibility when they add a requirement midway; naming; error handling |
| Component implementation | 30–60 min | One self-contained class with real logic: an LRU cache, a rate limiter, a thread-safe counter | Correctness, complexity, edge cases, thread safety |
| Refactoring / code review | 30–60 min | Improvements to a messy piece of code you are given | Spotting smells, naming the principle each one breaks, changing it safely |
Machine coding rounds are especially common at Indian product companies (Flipkart, Swiggy, Razorpay and many others run them), and are also used elsewhere under names like "pair programming" or "practical coding". Typical problems: parking lot, Splitwise, snake and ladder, elevator, vending machine, a library system, a rate limiter, a ride-sharing matcher.
A method you can repeat in every round
The same five steps work for an OOD discussion and for machine coding; only the time spent on each changes.
| Step | What you do | OOD discussion (45 min) | Machine coding (90 min) |
|---|---|---|---|
| 1. Clarify | Ask about scope, actors, rules and what is out of scope; write the agreed list | 5 min | 5–10 min |
| 2. Entities | Nouns in the requirements become candidate classes; verbs become methods | 5 min | 5 min |
| 3. Relationships | Who has whom, who creates whom; sketch a class diagram | 10 min | 5–10 min |
| 4. Seams | For each thing that will vary, an interface (often a known pattern) | 10 min | 5 min |
| 5. Build and stress | Code the core flow end to end, then concurrency and extensions | 15 min (walk through, code one method) | 60 min (code, run, demo, extend) |
Step 2 in practice: nouns and verbs
Take one requirement: "A parking lot has several floors. Each floor has spots for motorbikes, cars and trucks. A vehicle enters, gets a ticket and parks in a free spot of its size. On exit the driver pays by the hour."
- Nouns: parking lot, floor, spot, vehicle, ticket, driver, payment, hour.
- Verbs: enter, issue ticket, park, find free spot, exit, pay, calculate fee.
Then filter. "Hour" is a value, not a class. "Driver" carries no behaviour we need, so drop it. Spot sizes and vehicle types are a fixed set, so they become an enum (a type with a fixed list of named values, like SpotSize.SMALL). "Pay by the hour" is a rule that will obviously change (weekend rates, flat fees), so it goes behind an interface such as PricingStrategy (the Strategy pattern). The result is a first cut: ParkingLot, Floor, Spot, Vehicle, Ticket, SpotSize (enum), PricingStrategy. The full answer is in Design a parking lot.
How this course is organised
The course builds from single objects up to complete designs. Each chapter has this reading page plus an interactive version you can play with.
The road map: objects, SOLID, patterns, full designs
- That is what this course is about: code that is easy to change, test and understand. We’ll learn objects, the five SOLID rules, fourteen classic design patterns, and then design real things like a parking lot and an elevator, favourite interview questions.
| Part | Lessons | You will be able to |
|---|---|---|
| Object-oriented basics | Classes and objects, Encapsulation, Inheritance vs composition, Interfaces and polymorphism, Class diagrams, SOLID principles | Model a problem as classes, protect their rules, and explain your choices with a diagram |
| Patterns for creating objects | Singleton, Factory, Builder | Control how and where objects are made |
| Patterns for structure | Adapter, Decorator, Facade, Proxy, Composite | Fit classes together and wrap them without rewriting |
| Patterns for behaviour | Strategy, Observer, Command, State, Template method, Chain of responsibility | Swap, notify, queue and sequence behaviour |
| Design it yourself | Parking lot, vending machine, elevator, movie ticket booking, and more | Run a full machine coding or OOD round |
Code is in Java and Python throughout. Java is the most common language in LLD rounds and its types make designs explicit; Python shows the same ideas with less ceremony. Use whichever you will interview in.
Where this breaks
When a little design is enough
LLD effort should match the life expectancy of the code:
- Scripts and one-off jobs: a 50-line data migration that runs once needs clear names, not interfaces.
- Prototypes: when you are still discovering what the product is, rewriting is cheaper than designing.
- Framework-shaped CRUD: a typical create-read-update-delete endpoint in Spring or Django already has a structure (controller, service, repository). Follow it rather than inventing your own.
Design pays off when code will be changed by several people over months, which describes most production code and every interview problem.
In the interview
Requirement: "A library lends books to members. A book can have several copies. A member may borrow at most five copies at once, for 14 days. Late returns are fined 10 cents per day. Librarians can add books and see overdue loans." Write the nouns and verbs, filter them, and list your classes with one responsibility each. Which rule is most likely to change?
Compare with our answer
- Nouns: library, book, copy, member, loan, day, fine, librarian.
- Verbs: lend (borrow), return, add book, list overdue, calculate fine.
- Filter: "day" is a value; "fine" is an amount computed from a loan, not a stored thing (or a small value). Book and copy are different: a
Bookis the title (ISBN, author), aBookCopyis the physical item that is lent. - Classes:
Book(title data),BookCopy(one physical copy, available or not),Member(identity, current loans),Loan(which copy, which member, due date, returned date),LibraryorLendingService(borrow and return, enforcing the five-loan limit),FinePolicy(an interface: 10 cents a day today). - Most likely to change: the fine and the loan limits, so put them in a policy object rather than hard-coding them in
Loan.
A strong answer mentions: Book vs BookCopy as separate classes · Loan as its own class linking member and copy · the five-loan rule enforced in one place · fine calculation behind an interface or policy · "day" and "fine" as values, not classes · librarian as a role or permission rather than a separate class hierarchy.
A team's NotificationManager has sendEmail(), sendSms() and sendPush(), and a notify(user, type) method with a three-way if/else. Product now wants WhatsApp messages, and users should be able to choose more than one channel. What is wrong with the current shape, and what would you change?
Compare with our answer
- Every new channel edits
NotificationManagerand itsif/else, so the class has many reasons to change (low cohesion) and the chain grows forever. - Extract a
Channelinterface withsend(user, message); one class per channel (EmailChannel,SmsChannel,PushChannel,WhatsAppChannel). - The notifier holds a list of channels per user (from their preferences) and loops over it, so "more than one channel" needs no new branches.
- Channel choice is built in one place (a map from name to channel), not scattered through the code.
- Failure handling: one channel failing (SMS gateway down) should not stop the others; catch per channel and log or retry.
A strong answer mentions: one interface for channels · one class per channel · a list of channels instead of a type switch · choice kept in one place · independent failure per channel.
- LLD = the classes inside one program: responsibilities, relationships, interfaces. HLD = the services and machines between programs.
- Goal: easy to change, test and understand, and correct under concurrency. High cohesion, low coupling.
- Interview formats: OOD discussion (diagram + key methods), machine coding (running code in 60–120 min), component implementation (LRU, rate limiter), refactoring.
- Method: clarify → nouns and verbs → relationships → interfaces for what varies → build the core flow → concurrency and extensions.
- Nouns become classes only if they have behaviour or identity; values become fields or enums.
- Change should land as a new class plus wiring in the composition root, not as edits to working classes.
- Don't over-engineer: abstract what is named as variable; get one flow running first.
- Always ready: "what if two requests hit this at once?" and "how would you test it?"
1. In a design review, which of these questions belongs to low-level design rather than system design?
LLD is about the classes inside one program: responsibilities and seams. Server counts, replication and load balancing are system design questions about machines and the network.
2. You have 90 minutes in a machine coding round to build a Splitwise-style expense sharer. What should you aim to have by the end?
Machine coding is graded first on whether the code runs and demonstrates the flows, then on separation and extensibility. Diagram-only or scaffolding-only answers score poorly; persistence is usually out of scope unless asked.
3. Changing the wording of the receipt email forces a team to re-test card payments, because both live in one class. What does this point to?
Cohesion measures whether a class's contents belong together. Email wording and card charging change for different reasons, so a class holding both has low cohesion; splitting them lets each be changed and tested alone.
4. A well-designed checkout needs to accept PayPal. What should the change look like?
The change lands as a new class plus one line in the place that builds the objects. Branches in the service or methods added to the interface spread the change into working code.
5. From "members borrow copies of books, at most five at a time", which first cut of classes is strongest?
Copies and titles are different things, a loan links a member to a copy with dates, and a rule enforced in one place cannot be forgotten by a caller. A counter on Book cannot tell copies apart or record due dates.
6. A candidate spends 70 minutes of a 90-minute round building interfaces, factories and builders, and has no running code. What was the core mistake?
Over-engineering trades working code for flexibility that may never be needed. Get one flow running, then add seams where the requirements or the interviewer point to change.
7. During an OOD discussion of a parking lot the interviewer asks: "Two gates call findFreeSpot() at the same moment. What happens?" What are they checking?
Checking "free" and then occupying are two steps; two threads can both see the spot as free. The fix is an atomic take (a lock, compare-and-set or database constraint) owned by a clear object.
Score 60% or more and the lesson is marked complete.