Learnings

System design, part 10 of 12

Low-Level Design

Low-level design (LLD) is the class-level design of one component: its objects, their responsibilities, the interfaces between them and the code that proves it works. This page gives a repeatable method, the UML you need to read and draw, the modelling decisions that separate senior answers, the patterns and concurrency questions that actually come up, and a playbook for machine-coding rounds. All code is Python 3.9, standard library only. SOLID is covered in Design Principles and the 23 patterns in Design Patterns, so they are linked here, not repeated.

What an LLD round is

Part 1 of 7 · scope, formats, scoring

An LLD round asks you to turn a paragraph of requirements into classes with clear responsibilities, and often into working code. It is judged on modelling and code quality, not on scale.

HLD vs LLD

What an LLD round is

High-level design decides which boxes exist and how they talk over the network. Low-level design opens one box and decides its classes.

AspectHLDLLD
ScopeWhole system: services, stores, queues, regionsOne service or library: classes, interfaces, methods
Unit of designProcess or data storeClass, function, in-memory data structure
ArtefactsArchitecture diagram, API list, data model, capacity numbersClass diagram, sequence or state diagram, interfaces, code
Main forcesScale, availability, consistency, costChange: which requirement is likely to vary next
Concurrency meansReplicas, partitions, distributed transactionsThreads, locks, atomic check-then-act inside one process
What is evaluatedTrade-offs, bottlenecks, failure handlingModelling, extensibility, readability, correctness
Typical prompt"Design a ticket booking platform""Design the classes for seat booking and make double booking impossible"

Senior signal: say which level you are at. If the prompt is "design a parking lot", ask whether the interviewer wants classes and code, or a multi-site system with sensors and payments; the answer changes everything you draw.

The two formats

What an LLD round is

Design discussionMachine coding
Length45 to 60 minutes60 to 90 minutes of coding, often plus a 20 to 30 minute review
OutputClass diagram, key method signatures, one walked use caseCode that runs: a demo or test proving each requirement
MediumWhiteboard or shared documentYour own editor, or a shared pad with a run button
DepthBroad: every entity named, a few methods written outNarrow: the core flows fully working, the rest stubbed behind interfaces
Storage and I/ODiscussedIn memory; input from a driver function or a command loop
Common failureA diagram of nouns with no behaviourHalf of everything, nothing runnable at the bell

Interview tip: in machine coding, a small design that runs beats a large design that does not. Get one end-to-end flow printing output in the first 25 minutes, then widen.

How it is scored

What an LLD round is

Rubrics differ by company, but the same dimensions recur. Order below is roughly by weight in machine coding.

DimensionEarns the markLoses it
CorrectnessEvery stated requirement demonstrably worksCrashes on the demo input; requirements silently skipped
ModellingEntities match the domain; each class has one job; state lives where the rules areOne god class; dictionaries of dictionaries; data classes with all logic in a manager
ExtensibilityA new pricing rule or vehicle type is a new class, not an edit to five if chainsif kind == "car" spread across the code
ReadabilityIntention-revealing names, short methods, type hintsmgr, data2, 80-line methods
Patterns, with restraintA pattern only where a variation point exists, and you can name what variesFactory, Singleton and Observer added to a 100-line program
Edge cases and errorsInvalid input and rule violations raise named domain errorsReturning None or -1; bare except
ConcurrencyShared state identified; check-then-act made atomic; you can explain why"Python has a GIL, so it is fine"
TestsA few fast tests of the core rule and one failure pathNone, or only a happy-path print

The method

Part 2 of 7 · ten steps, one worked example

A fixed sequence stops you from coding too early and from diagramming too long. Each step below produces a visible artefact, worked on one small problem: a library lending desk.

The ten steps and the time budget

The method

Three phases. Patterns come at step 8, after the model exists, never at step 1.
StepArtefact45 min discussion90 min machine coding
1. Clarify requirements and scopeIn-scope and out-of-scope lists55
2. Use cases and actorsNumbered use-case list33
3. Entities (nouns) and behaviours (verbs)Entity table54
4. RelationshipsHas-a, is-a, uses, with multiplicity32
5. Class diagramDiagram with key members only83 (a sketch)
6. Key interfaces and APIsPublic method signatures53
7. Walk one use caseSequence diagram, or running code650 (the code)
8. Patterns at variation pointsNamed variation point and interface45
9. Concurrency, errors, edge casesLock placement, domain exceptions410 (with tests)
10. Extensions"To add X, I add class Y"25

Interview tip: minutes are approximate. The fixed rule is the order: no class before a use case needs it, no pattern before something varies.

Steps 1 and 2: requirements and use cases

The method

The prompt: "Design a library lending desk." Ask until the scope fits the time, then write it down so the interviewer can correct it.

Question to askAnswer assumed here
Several copies of one title?Yes; a loan is for a physical copy
Limit on loans per member?Yes, per member, default 2
Loan period and fines?14 days; flat fine per late day
Reservations, search, payments, multiple branches?Out of scope; keep the design open to reservations
Concurrent desks?Possibly two counters: lending one copy must be atomic

Senior signal: state what you are cutting and why. "I will leave reservations out, but lending goes through one method so a reservation check can be added there" shows scope control without closing the design.

Steps 3 and 4: entities, behaviours, relationships

The method

Underline the nouns in the use cases to find candidate classes and the verbs to find methods. Then give every verb exactly one owner: the class that holds the data the rule needs.

NounKindKnowsDoes (verbs it owns)
BookValue objectISBN, titleNothing; it is a description
CopyEntityCopy id, its book, statuscheck_out, check_in
MemberEntityMember id, name, loan limitNothing yet
LoanEntityCopy, member, due date, return datefine
CopyStatusEnumAvailable, on loan
LendingDeskServiceCopies, open loanslend, give_back: rules that span several entities
LibrarianActor onlyNot a class: nothing in scope depends on who is at the desk
  • Relationships: a desk has many copies; a copy describes one book, a book has many copies; a loan links one copy and one member; a member has zero to max_loans open loans.
  • Not every noun is a class. "Fine" is a number computed by Loan; "due date" is a field.
  • Not every class is a noun in the prompt. The service that coordinates a use case (LendingDesk) usually is not.

Steps 5 and 6: class diagram and key interfaces

The method

Key members only. The desk owns loans (composition) but only holds copies (aggregation); a loan points at its copy and member.

The public interface is three methods. Write the signatures and the errors before any body:

Interview tip: today is a parameter, not date.today() inside the method. Passing time in makes the fine rule testable and the demo deterministic.

Step 7: walk one use case

The method

Trace the most important use case through the diagram. Every message must be a method you listed; a message with no owner is a missing class or method.

UC2 and UC3 in one diagram. The copy guards its own status; the desk owns the rule that spans member and loans.

The runnable skeleton

The method

The diagram translated one to one. In a machine-coding round this is the 25-minute checkpoint: the main flow and one refusal both run.

Steps 8 to 10: patterns, edges, extensions

The method

With a working model, look for what will vary, what can go wrong and what the interviewer will add next.

StepQuestionLending desk answer
8. PatternsWhat varies independently of the rest?Fine rules per member type: a FinePolicy interface (Strategy). "Notify when a copy returns": Observer, only if asked
9. ConcurrencyWhich state is shared, which steps must be atomic?lend reads the loan count, then changes the copy: one lock around the whole method (see Making a class thread-safe)
9. Errors and edgesWhat input breaks an invariant?Unknown copy id, returning a copy that is not on loan, same member borrowing twice: each a named LendingError
10. ExtensionsWhat is the next requirement, and what changes?Reservations: a new RESERVED status and a queue per book, checked inside lend. Persistence: put _copies and _open_loans behind repositories (see Service, repository, strategy)

Senior signal: answer an extension with the size of the change: "one new class and one line in lend". If the honest answer is "edits in six places", say which abstraction you would introduce first.

Reading and drawing UML

Part 3 of 7 · just enough notation

You need three diagram types: class (structure), sequence (one flow over time) and state (one object's lifecycle). Interviewers care that the arrows mean something, not that the notation is perfect.

The class box

Reading and drawing UML

Three compartments: name, attributes, operations. Show only the members that explain the design.

Left: visibility markers, a generic type, a static factory (underlined). Right: an abstract class with an abstract operation (italic).
MarkerMeaningPython convention
+Publicname
#Protected: the class and its subclasses_name (by agreement only)
-Private_name; __name mangles the name, it does not enforce privacy
UnderlinedStatic or class-level member@staticmethod, @classmethod, class attribute
Italic, <<abstract>>Abstract class or operationABC with @abstractmethod
<<interface>>Operations only, no stateProtocol, or an ABC with only abstract methods
<<enumeration>>Fixed set of valuesEnum

Relationships

Reading and drawing UML

Six arrows, from weakest coupling to strongest. When unsure between two, draw the weaker one.

RelationshipDrawn asMeansIn PythonExample
DependencyDashed line, open arrowUses it briefly: a parameter, a local, a return typeArgument or local variableLendingDesk.lend takes a Member
AssociationSolid line, open arrowHolds a lasting reference; neither owns the otherAttribute pointing at another objectLoan to Member
AggregationHollow diamond at the wholeWhole and parts, but parts outlive the whole and may be sharedAttribute holding objects created elsewhereTeam and Player
CompositionFilled diamond at the wholeParts are created by, owned by and die with the wholeAttribute holding objects the whole createsOrder and OrderLine
InheritanceSolid line, hollow triangle at the parentIs-a: the child reuses and specialises the parentclass Car(Vehicle)Vehicle and Car
RealisationDashed line, hollow triangle at the interfaceImplements a contract; no code inheritedSubclass of an ABC, or matches a ProtocolPricingStrategy and HourlyPricing
Diamond at the whole. Delete the team and the players remain; delete the order and its lines go with it.
Triangle at the general type. Solid line inherits code; dashed line only promises the interface.
Open arrows show who knows whom. Solid: stored in a field. Dashed: only used in passing.
MultiplicityReads asField type in Python
1Exactly oneMember
0..1OptionalOptional[Member]
0..* or *Any numberlist[Loan], dict[str, Loan]
1..*At least onelist[OrderLine] plus a check in the constructor

Interview tip: the aggregation versus composition question is really "who creates it and who deletes it". Answer that in words and nobody will check the diamond.

Abstract classes and interfaces

Reading and drawing UML

Python has two ways to write the contract. Use an ABC when implementations share code or you want instantiation of an incomplete class to fail early; use a Protocol when you only need "anything with these methods", including classes you do not own.

ABCProtocol
TypingNominal: must subclassStructural: must have the methods
CheckedAt instantiation (runtime) and by type checkersBy type checkers only, unless @runtime_checkable
Shared codeYes: concrete methods, template methodsNot its purpose
Best forFamilies you own: State, Sink, VehiclePorts to the outside: Clock, Repository, PaymentGateway

Sequence diagrams

Reading and drawing UML

One use case, time flowing down. Use it to prove that every responsibility has an owner and to show ordering that matters (lock, check, write, unlock).

Solid arrow: call. Dashed arrow: return. The alt box is an if / else; a loop box repeats.
  • Participants are objects or interfaces from your class diagram, in call order left to right.
  • Keep it to one scenario and about 10 messages; draw a second diagram for the failure path if the alt boxes nest more than two deep.
  • Skip getters and constructors. Show the messages that carry a decision.

State diagrams

Reading and drawing UML

One object, its states and the events that move it between them. Anything not drawn is an illegal transition, which is exactly what the code must reject.

An order. The same event (cancel) means different things in different states; there is no arrow out of Shipped for cancel.
Draw a state diagram whenSkip it when
An entity has three or more states and operations are legal only in someThe "state" is one boolean (is_free)
The prompt says lifecycle, workflow, machine, status, or "cannot X after Y"The object is a value or a pure calculation
You are about to write if status == ... in several methodsTransitions are a straight line with no branches

Implementation scales with size: an Enum plus a table of allowed transitions for small machines; the State pattern when behaviour, not just legality, differs per state.

Modelling decisions

Part 4 of 7 · where the marks are

Most LLD problems are decided by a handful of recurring choices: what has identity, where a rule lives, and where the seams go.

Entities, value objects, enums, money

Modelling decisions

EntityValue object
Equal whenSame identity (id), whatever the fields sayAll fields equal
MutableYes: it has a lifecycleNo: replace it, never edit it
Python@dataclass(eq=False) or compare by id@dataclass(frozen=True): equality and hashing for free
ExamplesAccount, Order, Seat, Ticket, Vehicle in the lotMoney, Address, DateRange, Position, Book description
  • Ids: integers or opaque strings generated in one place (a repository or a counter). Never use a display name as an id.
  • Enums for fixed sets: statuses, kinds, directions. A bare string like "car" is a typo waiting to happen and cannot be listed.
  • Money as integers in the minor unit (paise, cents) with a currency. Floats cannot represent 0.1 exactly.
  • Immutability by default for anything shared between objects or threads; it removes a whole class of bugs.

Composition over inheritance

Modelling decisions

Inherit only for a true is-a that will stay one-dimensional. When two things vary independently (loan length and fine rule; vehicle type and pricing), subclasses multiply; composed parts add.

No StudentMember, StaffMember, CappedStudentMember. A member is configured with parts, and parts can wrap parts.

Trade-off: composition costs one more object and one more constructor argument. Inheritance is still right for a shallow, stable hierarchy where children share real code, such as the states of one machine.

Where behaviour lives

Modelling decisions

Tell, don't ask: do not pull data out of an object, decide, and push the result back. Tell the object what you want; the rule sits next to the data it protects.

SmellLooks likeFix
Anaemic modelClasses with only fields; every rule in XManagerMove each rule to the class whose fields it reads
God classParkingLot that parks, prices, prints and persistsSplit by reason to change: pricing, storage, allocation
Feature envyA method that mostly touches another object's fieldsMove the method to that object
Type switchif kind == A ... elif kind == B in several placesPolymorphism: one interface, one class per kind
Primitive obsessiondict and str for everythingSmall value objects and enums

Rule of thumb for placement: a rule about one entity goes in that entity; a rule that needs several entities or a repository goes in a service. See Design Principles for single responsibility and the rest of SOLID.

Interfaces and dependency injection

Modelling decisions

Put an interface exactly where something varies or where the outside world begins (time, randomness, storage, payment, notification). Then pass the implementation in through the constructor instead of creating it inside.

The service depends only on interfaces (hexagons). Only the composition root, main or a test, knows the concrete classes.
  • Gain: tests swap in a fake clock or in-memory store; a new variant is a new class; no hidden globals.
  • Pay: more constructor arguments and one place that wires everything. That is the right place for wiring.
  • Do not add an interface with a single implementation and no test double "for the future"; add it when the second implementation appears.

Senior signal: inject the clock and the random source. "How do you test the expiry?" has a one-line answer when now is a dependency.

Service, repository, strategy

Modelling decisions

This split fits most machine-coding problems: entities hold state and their own rules, a repository stores and finds them, a strategy holds the rule that varies, and a service runs one use case by coordinating the three.

Arrows point from the service to interfaces. Storage and pricing can each change without touching the service or the entity.

Interview tip: in a 90-minute round, skip the repository interface if there is one store and no test double; keep the class. The seam is the class boundary, the Protocol is a one-minute addition later.

Domain exceptions

Modelling decisions

A rule violation is an exception named in the language of the domain, under one base class per module. Callers catch the base; tests assert the specific class.

DoAvoid
class SeatUnavailable(BookingError) with a message naming the seatreturn None, return -1, return False, "msg"
Validate at the boundary (constructor, service method), then trust the objectRe-validating the same thing in every method
Raise before mutating, so a failed call changes nothingHalf-applied operations
Translate lookups: KeyError becomes OrderNotFoundLeaking KeyError or IndexError to the caller
Catch DomainError once, at the command loop or API edgeexcept Exception: pass

A return value is still right for an expected, frequent "no": RateLimiter.allow() returns False; a cache get returns a default.

Patterns that actually come up

Part 5 of 7 · needs first, names second

Nine patterns cover almost every LLD question. Recognise the need, then reach for the name; the mechanics are on the Design Patterns page.

Need to pattern map

Patterns that actually come up

Recurring needPatternWhere it shows upPython shortcut
Interchangeable algorithmsStrategyPricing, fees, split rules, matching, elevator scheduling, evictionPass a function when there is one method and no state
Behaviour depends on stateStateVending machine, order, elevator car, ATM sessionEnum plus transition table for small machines
Notify others of a changeObserverPrice alerts, booking confirmations, pub-sub, cache invalidationA list of callables
Create the right variantFactoryVehicle or spot from a type code, limiter from config, piece from a symbolA dict from key to class
Create a family that belongs togetherAbstract FactoryPer-region tax plus invoice format; rarely needed in 90 minutes
Assemble something with many optional partsBuilderPizza or meal orders, query or request objectsKeyword arguments and dataclass defaults usually suffice
One shared instanceSingletonConfig, registry, logger root, connection poolCreate one in main and inject it; a module-level object
Undo, redo, queued or logged actionsCommandText editor, job scheduler, bank transactions, game movesA dataclass with execute and undo
Add responsibilities without subclassingDecoratorToppings, capped or discounted pricing, caching or retrying wrappersA wrapper class with the same interface
Tree of parts and wholesCompositeFile system, org chart, menu, nested expense groups
Request passes through a pipelineChain of ResponsibilityLog filters, validation, approval levels, ATM note dispensing, middlewareA list of handlers run in order

Why prefer injection over Singleton: a global instance hides the dependency, shares state between tests and makes a second instance (per tenant, per test) impossible. "There is one" is a wiring decision; make one in main and pass it in.

Pattern overuse

Patterns that actually come up

A pattern is justified by a variation point you can name. Without one it is indirection that costs reading time and marks.

  • Strategy with one strategy. Write the method; extract the interface when the second rule arrives, and say so.
  • Factory that only calls a constructor. A factory earns its place when the caller holds a key (string, enum, config), not a class.
  • Singleton for convenience. If it is there to avoid passing an argument, pass the argument.
  • Observer for one known listener. A direct call is easier to follow and to debug.
  • State pattern for two states. A boolean or an enum check is clearer.
  • Builder for three fields. Use keyword arguments.
  • Deep inheritance to share two lines. Share a helper or compose.
  • Naming classes after patterns (ParkingStrategyFactoryManager) instead of after the domain (HourlyPricing).

Interview tip: name the pattern after you have described the need: "pricing varies by lot, so it sits behind an interface; that is Strategy". Leading with the name sounds like pattern matching.

Concurrency in LLD

Part 6 of 7 · shared state inside one process

The LLD concurrency question is always the same: which objects are shared between threads, and which sequences of steps on them must not interleave. Mechanics of threads, locks and queues in Python are in Python Concurrency.

Where shared state lives

Concurrency in LLD

Kind of objectShared between threads?What to do
Value objects, frozen dataclasses, enumsYes, safelyNothing: immutable
Request-scoped objects (a command, a DTO)NoNothing: confined to one thread
Repositories, inventories, seat maps, caches, countersYes, and mutableGuard with a lock, or use a thread-safe structure
Services holding only injected dependenciesYes, but statelessSafe if what they call is safe; the invariant may still span calls
Singletons, registries, lazy initialisersYesSafe creation and safe mutation are two separate questions
The race in every booking problem: check-then-act. The fix is to make the check and the act one indivisible step.

Failure mode: the GIL makes single bytecode operations atomic, not your method. if stock > 0: stock -= 1 can be interleaved between the test and the write, and stock -= 1 itself is a read, a subtract and a store.

Making a class thread-safe

Concurrency in LLD

Give the object that owns the invariant one private lock, take it in every method that reads or writes the guarded fields, and keep the whole check-then-act inside it.

  • Deterministic by construction: which ten buyers win varies from run to run; that exactly ten win does not. Assert the invariant, not the interleaving.
  • Lock granularity: one lock per object is the default. A lock per seat or per key raises throughput and brings ordering problems; a single global lock is correct and often good enough to state first.
  • Never call out (payment, callbacks, I/O) while holding the lock; hold it for memory operations only.

Lock ordering

Concurrency in LLD

An operation on two objects needs both locks. If two threads take them in opposite orders, each holds one and waits for the other forever. Always acquire in one global order, for example by id.

Left: a cycle of holds and waits. Right: both transfers take A before B, so no cycle can form.

Interview tip: other valid answers are one coarse lock over both accounts, or lock.acquire(timeout=...) with back-off and retry. State the ordering rule first; it is the one with no failure path.

Optimistic versioning and idempotent operations

Concurrency in LLD

A lock is pessimistic: it blocks others while you work. The optimistic alternative lets everyone read, and makes the write conditional on the version read; the loser re-reads and retries or reports the conflict. Use it when conflicts are rare or the work between read and write is slow (user think time, a remote call).

Compare-and-set. Only the comparison and the write are atomic; nobody waits on a lock while a user decides.
  • Idempotent: doing it twice has the same effect as once. Needed wherever a caller may retry: payments, confirmations, message handlers.
  • Make it so with a caller-supplied request id remembered with the result, or by designing the operation as "set to X" instead of "add X".
  • Under threads, the "seen before?" check and the insert are themselves a check-then-act and need the lock.

Thread-safe singletons and caches

Concurrency in LLD

Lazy creation is a check-then-act on "does it exist yet". Simplest correct answer in Python: create the instance at import time or in main. If it must be lazy, lock the creation and re-check inside the lock.

  • Trade-off: this cache holds one lock while loading, so loads of different keys queue behind each other. A lock per key (or a stored future per key) fixes that at the cost of more code; say it, write it only if asked.
  • functools.lru_cache keeps its own structure consistent under threads, but two threads that miss together may both run the function.
  • A bounded cache also needs eviction to be inside the same lock as the insert; see the LRU case in LLD Case Studies.

Bounded blocking queue

Concurrency in LLD

The classic coordination problem: producers must wait when the queue is full, consumers when it is empty. One lock, two conditions.

The bound is the point: a full queue slows producers down (backpressure) instead of growing without limit.

Interview tip: in real code this is queue.Queue(maxsize=n). Write it by hand only when asked, and mention the three details that get probed: while around wait, both conditions on the same lock, and how consumers are told to stop.

"Is this thread-safe?"

Concurrency in LLD

Do not answer yes or no. Answer in four sentences:

  1. What is shared: "The seat map and the holds dictionary are shared; requests and bookings are per call."
  2. What invariant is at risk: "A seat must have at most one holder; that is a check-then-act."
  3. What protects it: "One lock in Show around the check and the write; nothing slow happens inside it."
  4. What it costs and the next step: "All bookings for a show serialise. If that is too coarse: a lock per seat taken in seat-id order, or optimistic versions."
ToolUse whenWatch for
Immutability, confinementAlways firstNothing; this is the free option
One lock per objectInvariant inside one objectHolding it across I/O or callbacks
Ordered locksInvariant across two or more objectsA code path that takes them in another order
RLockA locked method calls another locked method on the same objectHides tangled call graphs; restructure if you can
Optimistic versionRare conflicts, slow work between read and writeRetry storms under contention
Queue with one workerAll mutations can be serialised through one threadLatency; backpressure when the queue fills

Senior signal: say where the same invariant is enforced once there is more than one process: a unique constraint or conditional write in the database, not the in-process lock. Data Systems and Distributed Systems Patterns cover that level (Data Systems, Distributed Systems Patterns).

Machine-coding playbook

Part 7 of 7 · 90 minutes, working code

The round rewards a runnable core with clean seams. Decide the layout and the order before typing.

File and module layout

Machine-coding playbook

  • Dependencies point one way: main to services to strategies and repositories to models. Models import nothing of yours.
  • If the platform allows one file only, keep the same order top to bottom with a comment banner per section.
  • Do not create a package per class. Five to seven files is the right size for 90 minutes.

Order of implementation

Machine-coding playbook

Build a thin vertical slice that runs, then loop: one use case at a time through service and driver.
MinuteYou should have
10Requirements written as comments; entity list; public method signatures
25Models, in-memory store, first use case running from main
55All required use cases running on the happy path
70Variation point behind an interface; domain errors; one failure path demonstrated
82Three to six tests passing
90Dead code removed, names fixed, demo output matches the prompt

An input-driven command loop

Machine-coding playbook

Many prompts give input as lines of commands. Keep parsing in one thin class that maps a command name to a handler, catches domain errors, and never contains business rules.

Interview tip: the service never sees a string that needs parsing and never prints. That one boundary is what lets you test the rules without the loop, and swap the loop for an HTTP handler in the follow-up.

A few tests, fast

Machine-coding playbook

Use unittest: it is always installed. Test the core rule, one boundary and one failure; five tests in five minutes is the target.

  • Name tests as sentences about behaviour; the list of names is your requirements checklist.
  • Inject the clock, the random source and the store so no test sleeps or depends on order.
  • For concurrency, assert the invariant after joining all threads, as in Making a class thread-safe.

What to cut, and the pre-submit checklist

Machine-coding playbook

Short of time? Cut in this orderNever cut
1. Optional requirements (say which, in a comment)A demo that runs without errors
2. Second and third strategy implementations (keep the interface and one)The core use case, end to end
3. Input parsing niceties; hard-code a driver insteadEntities with behaviour, not dictionaries
4. Repository interfaces (keep the classes)One failure path with a named exception
5. Thread safety in code (explain where the lock goes)Readable names

Pre-submit checklist

  • Runs from a clean start with one command; output matches the prompt's format exactly.
  • Every stated requirement is visible in the demo or a test; anything skipped is listed.
  • No dead code, commented-out blocks, debug prints or unused imports.
  • No if kind == ... chain that the stated extension would have to edit.
  • No magic numbers: limits, rates and durations are named constants or constructor arguments.
  • Errors are domain exceptions; nothing returns None to mean failure.
  • Time, randomness and storage are injected; tests do not sleep.
  • You can say in one sentence each: what is shared between threads, and what you would add next.

Cheat sheet

TopicRemember
Order of workScope, use cases, entities and verbs, relationships, class diagram, interfaces, walk a flow, patterns, concurrency and edges, extensions
Entity vs valueIdentity and lifecycle vs equal-by-fields and frozen
Placement of rulesOne entity: in the entity. Several entities or storage: in a service. Varies: behind a strategy
ArrowsDashed open: uses. Solid open: holds. Hollow diamond: has, shared. Filled diamond: owns. Hollow triangle solid: is-a. Hollow triangle dashed: implements
Diagram choiceClass for structure, sequence for one flow, state for a lifecycle with three or more states
InterfacesAt variation points and at the edge of the process: clock, random, store, gateway. ABC for families you own, Protocol for ports
PatternsStrategy, State, Observer, Factory, Builder, Command, Decorator, Composite, Chain. Name the variation point first
DataEnums for fixed sets, integer minor units for money, generated ids, frozen dataclasses for values
ErrorsOne base exception per module, specific subclasses, raise before mutating
Thread safetyFind shared mutable state; make check-then-act atomic; one lock per owner; order multiple locks; no I/O under a lock
Alternatives to a lockImmutability, confinement, optimistic version, single-writer queue, idempotent operations
Machine codingRunnable slice by minute 25; models, store, service, driver, tests; cut breadth before quality

Next: ten designs worked through with this method in LLD Case Studies.