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 changes between the two rounds
- The two formats: design discussion and machine coding
- How it is scored: the rubric interviewers fill in
HLD vs LLD
High-level design decides which boxes exist and how they talk over the network. Low-level design opens one box and decides its classes.
| Aspect | HLD | LLD |
|---|---|---|
| Scope | Whole system: services, stores, queues, regions | One service or library: classes, interfaces, methods |
| Unit of design | Process or data store | Class, function, in-memory data structure |
| Artefacts | Architecture diagram, API list, data model, capacity numbers | Class diagram, sequence or state diagram, interfaces, code |
| Main forces | Scale, availability, consistency, cost | Change: which requirement is likely to vary next |
| Concurrency means | Replicas, partitions, distributed transactions | Threads, locks, atomic check-then-act inside one process |
| What is evaluated | Trade-offs, bottlenecks, failure handling | Modelling, 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
| Design discussion | Machine coding | |
|---|---|---|
| Length | 45 to 60 minutes | 60 to 90 minutes of coding, often plus a 20 to 30 minute review |
| Output | Class diagram, key method signatures, one walked use case | Code that runs: a demo or test proving each requirement |
| Medium | Whiteboard or shared document | Your own editor, or a shared pad with a run button |
| Depth | Broad: every entity named, a few methods written out | Narrow: the core flows fully working, the rest stubbed behind interfaces |
| Storage and I/O | Discussed | In memory; input from a driver function or a command loop |
| Common failure | A diagram of nouns with no behaviour | Half 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
Rubrics differ by company, but the same dimensions recur. Order below is roughly by weight in machine coding.
| Dimension | Earns the mark | Loses it |
|---|---|---|
| Correctness | Every stated requirement demonstrably works | Crashes on the demo input; requirements silently skipped |
| Modelling | Entities match the domain; each class has one job; state lives where the rules are | One god class; dictionaries of dictionaries; data classes with all logic in a manager |
| Extensibility | A new pricing rule or vehicle type is a new class, not an edit to five if chains | if kind == "car" spread across the code |
| Readability | Intention-revealing names, short methods, type hints | mgr, data2, 80-line methods |
| Patterns, with restraint | A pattern only where a variation point exists, and you can name what varies | Factory, Singleton and Observer added to a 100-line program |
| Edge cases and errors | Invalid input and rule violations raise named domain errors | Returning None or -1; bare except |
| Concurrency | Shared state identified; check-then-act made atomic; you can explain why | "Python has a GIL, so it is fine" |
| Tests | A few fast tests of the core rule and one failure path | None, 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
- Steps 1 and 2: requirements, scope, use cases
- Steps 3 and 4: entities, behaviours, relationships
- Steps 5 and 6: class diagram and key interfaces
- Step 7: walk one use case
- The runnable skeleton
- Steps 8 to 10: patterns, concurrency and edges, extensions
The ten steps and the time budget
| Step | Artefact | 45 min discussion | 90 min machine coding |
|---|---|---|---|
| 1. Clarify requirements and scope | In-scope and out-of-scope lists | 5 | 5 |
| 2. Use cases and actors | Numbered use-case list | 3 | 3 |
| 3. Entities (nouns) and behaviours (verbs) | Entity table | 5 | 4 |
| 4. Relationships | Has-a, is-a, uses, with multiplicity | 3 | 2 |
| 5. Class diagram | Diagram with key members only | 8 | 3 (a sketch) |
| 6. Key interfaces and APIs | Public method signatures | 5 | 3 |
| 7. Walk one use case | Sequence diagram, or running code | 6 | 50 (the code) |
| 8. Patterns at variation points | Named variation point and interface | 4 | 5 |
| 9. Concurrency, errors, edge cases | Lock placement, domain exceptions | 4 | 10 (with tests) |
| 10. Extensions | "To add X, I add class Y" | 2 | 5 |
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 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 ask | Answer 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
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.
| Noun | Kind | Knows | Does (verbs it owns) |
|---|---|---|---|
Book | Value object | ISBN, title | Nothing; it is a description |
Copy | Entity | Copy id, its book, status | check_out, check_in |
Member | Entity | Member id, name, loan limit | Nothing yet |
Loan | Entity | Copy, member, due date, return date | fine |
CopyStatus | Enum | Available, on loan | |
LendingDesk | Service | Copies, open loans | lend, give_back: rules that span several entities |
| Librarian | Actor only | Not 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_loansopen 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 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
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.
The runnable skeleton
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
With a working model, look for what will vary, what can go wrong and what the interviewer will add next.
| Step | Question | Lending desk answer |
|---|---|---|
| 8. Patterns | What varies independently of the rest? | Fine rules per member type: a FinePolicy interface (Strategy). "Notify when a copy returns": Observer, only if asked |
| 9. Concurrency | Which 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 edges | What input breaks an invariant? | Unknown copy id, returning a copy that is not on loan, same member borrowing twice: each a named LendingError |
| 10. Extensions | What 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: members and visibility
- Relationships: six arrows and multiplicity
- Abstract classes and interfaces: ABC and Protocol
- Sequence diagrams
- State diagrams, and when to draw one
The class box
Three compartments: name, attributes, operations. Show only the members that explain the design.
| Marker | Meaning | Python convention |
|---|---|---|
+ | Public | name |
# | Protected: the class and its subclasses | _name (by agreement only) |
- | Private | _name; __name mangles the name, it does not enforce privacy |
| Underlined | Static or class-level member | @staticmethod, @classmethod, class attribute |
Italic, <<abstract>> | Abstract class or operation | ABC with @abstractmethod |
<<interface>> | Operations only, no state | Protocol, or an ABC with only abstract methods |
<<enumeration>> | Fixed set of values | Enum |
Relationships
Six arrows, from weakest coupling to strongest. When unsure between two, draw the weaker one.
| Relationship | Drawn as | Means | In Python | Example |
|---|---|---|---|---|
| Dependency | Dashed line, open arrow | Uses it briefly: a parameter, a local, a return type | Argument or local variable | LendingDesk.lend takes a Member |
| Association | Solid line, open arrow | Holds a lasting reference; neither owns the other | Attribute pointing at another object | Loan to Member |
| Aggregation | Hollow diamond at the whole | Whole and parts, but parts outlive the whole and may be shared | Attribute holding objects created elsewhere | Team and Player |
| Composition | Filled diamond at the whole | Parts are created by, owned by and die with the whole | Attribute holding objects the whole creates | Order and OrderLine |
| Inheritance | Solid line, hollow triangle at the parent | Is-a: the child reuses and specialises the parent | class Car(Vehicle) | Vehicle and Car |
| Realisation | Dashed line, hollow triangle at the interface | Implements a contract; no code inherited | Subclass of an ABC, or matches a Protocol | PricingStrategy and HourlyPricing |
| Multiplicity | Reads as | Field type in Python |
|---|---|---|
1 | Exactly one | Member |
0..1 | Optional | Optional[Member] |
0..* or * | Any number | list[Loan], dict[str, Loan] |
1..* | At least one | list[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
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.
ABC | Protocol | |
|---|---|---|
| Typing | Nominal: must subclass | Structural: must have the methods |
| Checked | At instantiation (runtime) and by type checkers | By type checkers only, unless @runtime_checkable |
| Shared code | Yes: concrete methods, template methods | Not its purpose |
| Best for | Families you own: State, Sink, Vehicle | Ports to the outside: Clock, Repository, PaymentGateway |
Sequence diagrams
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).
- 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
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.
| Draw a state diagram when | Skip it when |
|---|---|
| An entity has three or more states and operations are legal only in some | The "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 methods | Transitions 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
- Composition over inheritance
- Where behaviour lives: tell, don't ask
- Interfaces and dependency injection
- Service, repository, strategy: the split that fits most problems
- Domain exceptions
Entities, value objects, enums, money
| Entity | Value object | |
|---|---|---|
| Equal when | Same identity (id), whatever the fields say | All fields equal |
| Mutable | Yes: it has a lifecycle | No: replace it, never edit it |
| Python | @dataclass(eq=False) or compare by id | @dataclass(frozen=True): equality and hashing for free |
| Examples | Account, Order, Seat, Ticket, Vehicle in the lot | Money, 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
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.
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
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.
| Smell | Looks like | Fix |
|---|---|---|
| Anaemic model | Classes with only fields; every rule in XManager | Move each rule to the class whose fields it reads |
| God class | ParkingLot that parks, prices, prints and persists | Split by reason to change: pricing, storage, allocation |
| Feature envy | A method that mostly touches another object's fields | Move the method to that object |
| Type switch | if kind == A ... elif kind == B in several places | Polymorphism: one interface, one class per kind |
| Primitive obsession | dict and str for everything | Small 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
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.
- 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
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.
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
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.
| Do | Avoid |
|---|---|
class SeatUnavailable(BookingError) with a message naming the seat | return None, return -1, return False, "msg" |
| Validate at the boundary (constructor, service method), then trust the object | Re-validating the same thing in every method |
| Raise before mutating, so a failed call changes nothing | Half-applied operations |
Translate lookups: KeyError becomes OrderNotFound | Leaking KeyError or IndexError to the caller |
Catch DomainError once, at the command loop or API edge | except 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
- Pattern overuse: the warning list
Need to pattern map
Patterns that actually come up
| Recurring need | Pattern | Where it shows up | Python shortcut |
|---|---|---|---|
| Interchangeable algorithms | Strategy | Pricing, fees, split rules, matching, elevator scheduling, eviction | Pass a function when there is one method and no state |
| Behaviour depends on state | State | Vending machine, order, elevator car, ATM session | Enum plus transition table for small machines |
| Notify others of a change | Observer | Price alerts, booking confirmations, pub-sub, cache invalidation | A list of callables |
| Create the right variant | Factory | Vehicle or spot from a type code, limiter from config, piece from a symbol | A dict from key to class |
| Create a family that belongs together | Abstract Factory | Per-region tax plus invoice format; rarely needed in 90 minutes | |
| Assemble something with many optional parts | Builder | Pizza or meal orders, query or request objects | Keyword arguments and dataclass defaults usually suffice |
| One shared instance | Singleton | Config, registry, logger root, connection pool | Create one in main and inject it; a module-level object |
| Undo, redo, queued or logged actions | Command | Text editor, job scheduler, bank transactions, game moves | A dataclass with execute and undo |
| Add responsibilities without subclassing | Decorator | Toppings, capped or discounted pricing, caching or retrying wrappers | A wrapper class with the same interface |
| Tree of parts and wholes | Composite | File system, org chart, menu, nested expense groups | |
| Request passes through a pipeline | Chain of Responsibility | Log filters, validation, approval levels, ATM note dispensing, middleware | A 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
- Making a class thread-safe: atomic check-then-act
- Lock ordering: two objects, no deadlock
- Optimistic versioning and idempotent operations
- Thread-safe singletons and caches
- Bounded blocking queue: producer and consumer
- "Is this thread-safe?": what to say
Making a class thread-safe
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
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.
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
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).
- 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
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_cachekeeps 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
The classic coordination problem: producers must wait when the queue is full, consumers when it is empty. One lock, two conditions.
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?"
Do not answer yes or no. Answer in four sentences:
- What is shared: "The seat map and the holds dictionary are shared; requests and bookings are per call."
- What invariant is at risk: "A seat must have at most one holder; that is a check-then-act."
- What protects it: "One lock in
Showaround the check and the write; nothing slow happens inside it." - 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."
| Tool | Use when | Watch for |
|---|---|---|
| Immutability, confinement | Always first | Nothing; this is the free option |
| One lock per object | Invariant inside one object | Holding it across I/O or callbacks |
| Ordered locks | Invariant across two or more objects | A code path that takes them in another order |
RLock | A locked method calls another locked method on the same object | Hides tangled call graphs; restructure if you can |
| Optimistic version | Rare conflicts, slow work between read and write | Retry storms under contention |
| Queue with one worker | All mutations can be serialised through one thread | Latency; 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
- Dependencies point one way:
maintoservicestostrategiesandrepositoriestomodels. 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
| Minute | You should have |
|---|---|
| 10 | Requirements written as comments; entity list; public method signatures |
| 25 | Models, in-memory store, first use case running from main |
| 55 | All required use cases running on the happy path |
| 70 | Variation point behind an interface; domain errors; one failure path demonstrated |
| 82 | Three to six tests passing |
| 90 | Dead code removed, names fixed, demo output matches the prompt |
An input-driven command loop
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
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
| Short of time? Cut in this order | Never 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 instead | Entities 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
Noneto 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
| Topic | Remember |
|---|---|
| Order of work | Scope, use cases, entities and verbs, relationships, class diagram, interfaces, walk a flow, patterns, concurrency and edges, extensions |
| Entity vs value | Identity and lifecycle vs equal-by-fields and frozen |
| Placement of rules | One entity: in the entity. Several entities or storage: in a service. Varies: behind a strategy |
| Arrows | Dashed open: uses. Solid open: holds. Hollow diamond: has, shared. Filled diamond: owns. Hollow triangle solid: is-a. Hollow triangle dashed: implements |
| Diagram choice | Class for structure, sequence for one flow, state for a lifecycle with three or more states |
| Interfaces | At variation points and at the edge of the process: clock, random, store, gateway. ABC for families you own, Protocol for ports |
| Patterns | Strategy, State, Observer, Factory, Builder, Command, Decorator, Composite, Chain. Name the variation point first |
| Data | Enums for fixed sets, integer minor units for money, generated ids, frozen dataclasses for values |
| Errors | One base exception per module, specific subclasses, raise before mutating |
| Thread safety | Find shared mutable state; make check-then-act atomic; one lock per owner; order multiple locks; no I/O under a lock |
| Alternatives to a lock | Immutability, confinement, optimistic version, single-writer queue, idempotent operations |
| Machine coding | Runnable 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.