Low-Level Design: How to Approach the Round
System Design · Low-Level Design · Intermediate · 25 min
Turn a short brief like 'design a shopping cart with coupons' into clean, working classes: requirements, entities, relationships, APIs and the few design patterns that matter (Strategy, Factory, Observer, State), and know what the interviewer is grading.
A restaurant kitchen. The head chef (your main class) never cooks every dish; she hands each order to the right station. Want a new dish? Add a station. You never rebuild the kitchen.
The idea in everyday words
Building with LEGO. First you read the box (requirements), then you sort the bricks by kind (entities), then you decide which bricks click onto which (relationships), then you build each part so it has studs on top that other parts can use (APIs). Good LEGO models let you swap the wheels without taking the car apart. That swap-ability is what design patterns give you.
What the LLD round actually is
Low-level design (LLD) = deciding the classes, their data and their methods for one feature, then writing code that works.
Many Indian product companies (Flipkart, Swiggy, PhonePe, Razorpay, Uber and others) run it as a machine-coding round: you get a brief such as "build a parking lot" or "build Splitwise", 60 to 120 minutes, and you must hand in running code with a small demo. Other companies run a whiteboard version: you draw the classes and write the key methods.
| High-level design (HLD) | Low-level design (LLD) | |
|---|---|---|
| Question | "Design WhatsApp for 1 billion users" | "Design the classes for a chat group" |
| You draw | boxes: services, databases, queues, caches | classes, fields, methods, relationships |
| You talk about | scale, replication, latency | responsibilities, extensibility, correctness |
| Output | a diagram and numbers | working code (machine coding) or class diagrams plus key methods |
Usual rules of a machine-coding round:
- No database, no web server. Keep data in memory (dictionaries and lists). A "driver" (a
mainfunction or a list of commands) shows it working. - Any language you know well. Python, Java, C++, Go are all fine.
- Working beats perfect. A clean design that does not run usually scores lower than a simpler one that runs and handles the edge cases.
In this module every challenge has the same shape as many real rounds: a list of text commands goes in, a list of output lines comes out. Inside, you build real classes.
The five-step recipe
Use the same five steps for every LLD question. We will apply them to the challenge of this lesson: a shopping cart with coupons.
1. Requirements (5 minutes). Ask, then write them down as a short list. Split into must have and nice to have.
- Add an item (name, price, quantity). Adding the same item again increases its quantity.
- Remove an item. Show the total.
- Apply one coupon at a time: a flat amount off, a percent off, or "buy 2 get 1 free".
- Ask: can coupons stack? (no) Can the total go below zero? (no) Money as whole numbers? (yes, rupees, round down).
2. Entities (nouns become classes). Read your requirement list and underline the nouns: Cart, LineItem, Coupon. Verbs become methods: add, remove, apply, total.
3. Relationships. Who owns whom?
Cart ◆──────── 1..* LineItem (a cart HAS line items: composition)
Cart ────────── 0..1 Coupon (a cart USES one coupon)
Coupon <|──── FlatOff (FlatOff IS A coupon: inheritance / interface)
<|──── PercentOff
<|──── BuyTwoGetOne
CouponFactory ┄┄> Coupon (creates the right coupon from a code)
4. APIs (method signatures). Write them before any body:
| Class | Method | Returns |
|---|---|---|
| Cart | add(name, price, qty) | "shirt x2" |
| Cart | remove(name) | "removed shirt" or an error |
| Cart | apply(code) | "coupon PCT15" or an error |
| Cart | total() | "total 1105" |
| Coupon | discount(items, subtotal) | a whole number of rupees |
| make_coupon | (code) | a Coupon, or nothing if the code is bad |
5. Patterns, only where they earn their place. Three kinds of coupon that compute a discount differently is the textbook case for Strategy. Turning the text "PCT15" into the right object is a Factory. That is all this problem needs. Do not add patterns for show.
SOLID in plain words
SOLID is five rules of thumb for classes that are easy to change. Interviewers rarely ask you to recite them, but they notice when your code follows them.
| Letter | Rule | In plain words | In our cart |
|---|---|---|---|
| S | Single responsibility | One class, one job. | Cart keeps items; each Coupon only computes its discount. |
| O | Open / closed | Add new behaviour by adding code, not editing old code. | A new "festival 20% up to 300" coupon is a new class. Cart does not change. |
| L | Liskov substitution | A child class must work anywhere its parent works. | Every coupon returns a discount between 0 and the subtotal; none throws or returns a string. |
| I | Interface segregation | Small interfaces beat one giant one. | Coupon has one method, discount. It does not also have print_receipt. |
| D | Dependency inversion | Depend on an interface, not on a concrete class. | Cart holds "a Coupon", never "a PercentOff". |
The test for good design: when the interviewer says "now add X", how many existing classes do you have to edit? Zero or one is great. Five means the design is too tangled.
The patterns you will actually use
You do not need all 23 classic patterns. These five cover almost every LLD round:
| Pattern | Use it when | Example |
|---|---|---|
| Strategy | Several interchangeable ways to do one thing | pricing rules, coupon types, elevator scheduling, rate-limit algorithms, split types |
| Factory | Code must create one of several classes from some input | "car" → CarSpot, "PCT15" → PercentOff |
| Observer | Many parts must react when something happens, and the sender should not know them | order shipped → email, SMS, analytics |
| State | An object behaves differently depending on its current mode | elevator idle / moving / doors open, vending machine, order status |
| Singleton | Exactly one instance must exist | the parking lot, a config object |
About Singleton: use it rarely. A singleton is a global variable in a nice coat. It hides dependencies (any code can reach it), makes tests leak into each other (state from test 1 is still there in test 2), and is a headache with threads. Prefer creating one object in your driver and passing it in (this is called dependency injection). If the interviewer asks for a singleton, write it, then say why you would rather inject it.
Here is Strategy in its smallest form. Notice that the loop never asks "which kind of coupon is this?":
class Flat:
def __init__(self, n): self.n = n
def discount(self, total): return min(self.n, total)
class Percent:
def __init__(self, p): self.p = p
def discount(self, total): return total * self.p // 100
for coupon in [Flat(100), Percent(15), Flat(5000)]:
print(type(coupon).__name__, 1300 - coupon.discount(1300))
Rule of thumb: if you are about to write a long if kind == "a" ... elif kind == "b" chain in more than one place, replace it with Strategy, and keep the single remaining if chain inside a Factory.
How you are graded
Interviewers usually score these, roughly in this order of weight:
| What | What they look for |
|---|---|
| Working code | It runs, the demo passes, edge cases (empty cart, bad coupon) do not crash. |
| Modelling | Sensible classes with clear names. No "God class" that does everything. |
| Extensibility | "Add a new coupon type" or "add a new vehicle" touches one place. |
| Code quality | Small methods, no copy-paste, meaningful names, no magic numbers. |
| Edge cases and errors | Invalid input returns a clear error, not a stack trace. |
| Communication | You explained your plan before typing and your trade-offs after. |
| Concurrency (senior roles) | You can say where two threads could collide and how you would lock. |
A time plan for a 90-minute machine-coding round:
- 0-10 min: requirements and questions, written as comments at the top of the file.
- 10-20 min: classes and method signatures, no bodies yet.
- 20-70 min: implement the must haves end to end, run them often.
- 70-85 min: edge cases, one extension, tidy names.
- 85-90 min: demo and a short walkthrough of what you would add next.
Commit to a working skeleton early. A half-built perfect design at minute 90 scores worse than a complete simple one.
Go deeper: what senior candidates add
- Composition over inheritance. Inherit only for a true "is a" with shared behaviour. For "has a" or "can do", hold an object (a Cart has a pricing strategy). Deep inheritance trees are hard to change.
- Interfaces at the seams. Put an interface wherever something is likely to change or be replaced: payment gateway, notification channel, storage. In-memory storage behind a
Repositoryinterface lets you swap in a database later without touching business logic. - Value objects. Money, a seat id, a time range: small immutable classes with validation inside. They stop bugs like adding paise to rupees.
- Errors as part of the API. Decide early: return error results, or raise domain exceptions (
CouponInvalid). Be consistent. - Testability. Pass the clock in (
now) instead of calling the system time inside, so tests can control time. Every challenge in this module does exactly that. - Thread safety. Name the shared mutable state (the cart, the seat map) and say which methods must be atomic. Then pick: one lock per object, finer locks per item, or a single-threaded actor with a queue.
Step by step
- Add items:
add shirt 500 2 creates a LineItem (shirt, 500, qty 2): output 'shirt x2'. add socks 100 3: 'socks x3'. The cart now holds two lines, subtotal 500×2 + 100×3 = 1300.
- Factory builds B2G1:
coupon B2G1: make_coupon reads the code and returns a BuyTwoGetOne object. The cart stores it as 'a Coupon' and does not care which kind it is.
- Total with B2G1:
total: subtotal 1300. B2G1 gives qty // 3 free per line: shirts 2 // 3 = 0 free, socks 3 // 3 = 1 free (100). Output 'total 1200'.
- Swap the strategy:
coupon PCT15 replaces the old coupon (one at a time). total: 1300 × 15 // 100 = 195 off, output 'total 1105'. Cart's code did not change at all: only the strategy object did.
- Bad code is rejected:
coupon SAVE50 matches no rule, so the factory returns nothing and the cart answers 'error: bad coupon SAVE50'. PCT15 stays active: the next total is still 1105.
Code example
class EventBus: # Observer: senders do not know who listens
def __init__(self):
self.listeners = {}
def subscribe(self, event, fn):
self.listeners.setdefault(event, []).append(fn)
def publish(self, event, data):
for fn in self.listeners.get(event, []):
fn(data)
class EmailNotifier:
def on_shipped(self, order):
print(f"email: order {order['id']} is on its way to {order['city']}")
class SmsNotifier:
def on_shipped(self, order):
print(f"sms: {order['id']} shipped")
class Analytics:
def __init__(self):
self.shipped = 0
def on_shipped(self, order):
self.shipped += 1
bus, stats = EventBus(), Analytics()
bus.subscribe("shipped", EmailNotifier().on_shipped)
bus.subscribe("shipped", SmsNotifier().on_shipped)
bus.subscribe("shipped", stats.on_shipped)
bus.publish("shipped", {"id": "A-17", "city": "Pune"})
bus.publish("shipped", {"id": "A-18", "city": "Indore"})
bus.publish("cancelled", {"id": "A-19", "city": "Goa"}) # nobody listens: nothing happens
print("orders shipped:", stats.shipped)Complexity
- Time: O(1) per add / remove / apply; O(k) per total for k distinct items
- Space: O(k): one LineItem per distinct item, plus one coupon object
Interview tips
Spend the first minutes on requirements and write them as comments. Ask about the edge cases that change the code: stacking, rounding, limits, what happens on bad input.
Say your entities and relationships out loud, or sketch a tiny class diagram, before typing. It shows structure and lets the interviewer correct you early.
When you add an interface, say why: 'coupons will grow, so Cart depends on a Coupon interface and new types are new classes'.
Expect follow-ups like 'add a coupon that is 20% off up to 300' or 'allow two coupons'. Show that your design absorbs it with one new class or one small change.
If asked about Singleton, write it and then explain the testing and hidden-dependency problems, and offer dependency injection instead.
Challenge: Shopping Cart with Coupon Strategies
Build a small shopping cart, the way you would in a machine-coding round. Write run_cart(ops): ops is a list of text commands, and you return a list with one output line per command.
| Command | Meaning | Output |
|---|---|---|
add <name> <price> <qty> |
Add an item. If the item is already in the cart, add to its quantity (keep the first price). | <name> x<new qty> |
remove <name> |
Remove the whole line. | removed <name>, or error: no <name> |
coupon <CODE> |
Make this the only active coupon (it replaces any earlier one). | coupon <CODE>, or error: bad coupon <CODE> (the old coupon stays) |
total |
Subtotal minus the discount of the active coupon, worked out now. | total <n> |
Coupon codes (all amounts are whole rupees):
FLAT<n>(digits after FLAT): n off, but never more than the subtotal (the total cannot go below 0).PCT<n>with 1 ≤ n ≤ 90:subtotal * n // 100off (rounded down).B2G1: for each line, every 3rd unit is free:(qty // 3) * price.- Anything else is a bad coupon.
Build it with classes: a Cart, a LineItem, a Coupon interface with one class per coupon type, and a factory that turns a code into a coupon.
Example:
run_cart(["add shirt 500 2", "add socks 100 3", "coupon B2G1", "total", "coupon PCT15", "total"])
-> ["shirt x2", "socks x3", "coupon B2G1", "total 1200", "coupon PCT15", "total 1105"]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Strategy pattern, explained with diagrams (Refactoring.Guru) (Easy)
- Factory Method pattern (Refactoring.Guru) (Easy)
- Design Browser History (a small class-design problem) (Medium)
More in Low-Level Design
- LLD: Design a Parking Lot
- LLD: Design an Elevator System
- LLD: Design a Rate Limiter (Classes and Strategies)
- LLD: Design Splitwise (Expense Sharing)
- LLD: Design Movie Ticket Booking (BookMyShow)
Previous: Interview Walkthrough: Video Streaming (YouTube/Netflix) on AWS · Next: LLD: Design a Parking Lot