The HLD said one component, the scan processor, owns the status rule. The low-level design says how: which classes exist, what each one is responsible for, which interfaces they talk through, what order the calls happen in, and what happens when two of them run at the same time. This is where most production bugs are born, not in the boxes but in the lines between them. This lesson follows one scan message through the processor's code, call by call, and shows the LLD decision at each step. By the end you can design a component as classes with single responsibilities, draw its sequence diagram, and make it correct under retries and concurrency before anyone writes the first test.
Difficulty: Intermediate · Know this first: Lesson 165, Lesson 48, Lesson 10
This bar splits one message's time inside the processor. It is a worked example, not a measurement. In the good design the save dominates and stays short; in the bad one, a lock held during a network call turns a small cost into the whole bar, and multiplies it for every worker waiting behind.
A row that many workers update behaves like a single-server queue. Move the sliders: the wait grows sharply as the lock's utilisation approaches 100 percent. The save hop above follows your numbers.
utilisation = updates/s × hold time · average wait ≈ hold × u ÷ (1 − u) (a single-server queue) · above 100 percent the queue grows without limit.
Comfortable: the lock is free most of the time
Three questions. No score is saved anywhere — this is just you against the material.
Low-level design grows in four levels: first classes with one responsibility each, then the principles that keep them changeable and testable, then correctness under concurrency, retries, and failure, and finally designing components that other teams extend and depend on for years.
At the basic level you split a component into classes that each have one responsibility, and you write down the calls between them. The scan processor becomes a consumer adapter, a Scan value object, a processor, a repository, and a status machine. A sequence diagram shows, in order, who calls whom for one message.
Types:
Uses: any component bigger than one function. The test of a good split: you can name each class's job in one sentence without the word "and".
Where it breaks: one large class that receives, validates, decides, saves, and publishes. Every change touches it, and every test needs everything.
Try it: Basic
Which class should know which message queue the scans come from?
Now do it: Draw the sequence diagram for one request through a component you own. Count the lifelines and name each one's job in one sentence.
At the intermediate level you apply the principles that keep a design changeable. Single responsibility: one reason to change per class. Open-closed: add a new scan source by adding an adapter, not editing the processor. Liskov: every SeenScans implementation honours the same contract. Interface segregation: the processor needs contains and add, not a forty-method database client. Dependency inversion: the processor depends on interfaces, and the composition root wires real implementations.
Types:
Uses: any code that will live longer than a quarter or be changed by more than one person.
Scale and failure: the cost of SOLID is indirection; applied to a 50-line script it is ceremony. The failure at this level is interfaces with one implementation and no test that needs a second; add an interface where a seam exists, at I/O, at a vendor, or at a rule that varies.
Try it: Intermediate
You want to add scans arriving from a partner's webhook as well as the queue. Which design follows open-closed?
Now do it: Find one class in your code that imports a vendor client directly. Sketch the interface it actually needs.
At the advanced level the design is correct when things happen at the same time, twice, or not at all. Concurrent updates use optimistic versions or carefully scoped locks. Behaviour that depends on state is a state machine with an explicit transition table. Every method states its failure contract: which errors are retryable, which are permanent, and what partial state a failure can leave.
Types:
Uses: consumers, payment and order flows, anything with retries or more than one worker.
Scale and failure: a row updated 20 times a second with an 8 ms hold is at 16 percent lock utilisation; hold it 50 ms across a network call and it is at 100 percent and the queue never drains. The design lever is hold time, which is why nothing slow goes inside a lock. The trade is complexity: retry loops and outboxes are more code than a plain update, and they are the difference between a race that happens once a week and one that cannot happen.
Try it: Advanced
A conditional UPDATE with the version check updates zero rows. What should the processor do?
Now do it: Use the lock simulator above: find the hold time at which 20 updates a second reach 50 percent utilisation.
At the master level the LLD is a product: other teams extend it, call it, and depend on its behaviour for years. You design extension points on purpose, version internal interfaces like public ones, keep the core small and the plug-ins many, and review an LLD by reading its sequence diagrams and failure contracts before its classes.
Types:
Uses: platform libraries, shared SDKs, internal frameworks, and the core domain of a product.
Trade-off: every extension point is a promise to keep. Add them where at least two real variants exist today, not where one might exist someday; premature flexibility is the most expensive kind of complexity because it is permanent.
Try it: Master
Three teams want the processor to do something extra after a status change: one sends SMS, one updates billing, one feeds analytics. What does a master-level LLD do?
Now do it: For one shared component you own, list who depends on its behaviour and which interface each of them uses. Anything undocumented is a promise you did not know you made.
An LLD review is fastest with three artefacts: the class list with one-sentence responsibilities, the sequence diagram for the main path and the main failure, and the interfaces. Code comes after the reviewer agrees with those three.
ScanConsumer reads a message, builds Scan, calls handle, acks after return
Scan (value) valid scan: ScanId, ParcelId, Status, scanned_at
ScanProcessor orchestrates: dedupe, load, transition, save; no I/O of its own
StatusMachine allowed transitions; created -> in_transit -> out_for_delivery -> delivered
SeenScans (port) contains(id), add(id) impl: unique key / in-memory set
ParcelRepository get(id) -> Parcel+version; save(parcel, expected_version) -> ok | conflict
Outbox (port) add(event) inside the same transaction; relay publishes after commit
sequence: Consumer -> Processor.handle(scan)
Processor -> SeenScans.contains(scan.id) -> false
Processor -> Repository.get(parcel_id) -> Parcel v7
Processor -> Parcel.apply(scan) -> StatusMachine.next(cur, new)
Processor -> Repository.save(parcel, expected=7) -> ok (v8) | conflict -> reload, retry x3
Processor -> Outbox.add(ParcelStatusChanged) (same transaction)
Consumer -> queue.ack(message)Seven classes, one sentence each, and a sequence short enough to read aloud. The retry on conflict is part of the design, not an afterthought.
Real races are timing-dependent, which makes them hard to see. This script plays the exact interleaving that loses an update in production, in a fixed order, so it fails the same way every run: both workers load version 7, worker A saves first, then worker B saves.
# python3 lost_update.py
ORDER = ["created", "in_transit", "out_for_delivery", "delivered"]
furthest = lambda a, b: max(a, b, key=ORDER.index)
def run(check_version):
row = {"status": "in_transit", "version": 7}
def save(seen, new_status):
if check_version and row["version"] != seen["version"]:
return False # conflict: someone saved first
row.update(status=new_status, version=seen["version"] + 1)
return True
a, b = dict(row), dict(row) # both workers load version 7
save(a, furthest(a["status"], "delivered")) # A commits "delivered"
if not save(b, furthest(b["status"], "out_for_delivery")):
b = dict(row) # B reloads and re-applies
save(b, furthest(b["status"], "out_for_delivery"))
return row
print("no check: ", run(False))
print("with check:", run(True))
Expected: without the check, {'status': 'out_for_delivery', 'version': 8}: worker B overwrote A's "delivered", one update lost. With the check, B's first save is refused, it reloads version 8, keeps the furthest status, and the row ends {'status': 'delivered', 'version': 9}. In a real database the check is WHERE version = $expected in the UPDATE, and the database makes the compare-and-write atomic.
A scan processor I inherited held a row lock on the parcel while it called the notification service synchronously to say "your parcel is out for delivery". For months the notification service answered in 20 ms. Then it moved to a new provider and its p99 went to 900 ms.
The proper fix was the outbox: the status change and a "notify" event commit together, and the notification service consumes the event in its own time. The LLD checklist gained two lines: no network call inside a transaction, and every lock has a written maximum hold time.
Design the low-level structure of a "refund request" handler: a customer asks for a refund, the handler checks eligibility, records the refund, calls the payment provider, and notifies the customer. Requests can be retried by the client.
What makes a refund eligible, and does that rule change often? Can two refund requests for the same order arrive at once? What does the payment provider return on a timeout: success, failure, or unknown? Must the customer notification be in the same flow, or can it lag?
Low volume, perhaps 20 refunds a minute, but each is money. The design priority is correctness under retries and partial failure, not throughput.
RefundRequest value object; EligibilityPolicy as a strategy interface (rules vary by product); Refund entity with a state machine (requested, approved, sent_to_provider, confirmed, failed); RefundRepository with optimistic versions; PaymentGateway port with an adapter; outbox for RefundConfirmed. Idempotency key from the client on the request. Sequence diagram for the happy path and for "provider timed out".
Calling the provider inside the request gives the customer an immediate answer and holds a connection during a slow call; recording "requested" and processing asynchronously is safer and gives a "pending" answer. An "unknown" provider result must be reconciled, never retried blindly, because a blind retry can refund twice.