On this page

The LLD Interview Framework

A low-level design interview has a strange shape. The prompt is about a dozen words long ("design a library system"), the room has a whiteboard or a shared editor, and you get 45 minutes. In that time the interviewer wants to watch you turn a vague sentence into a set of classes that hold the right data and do the right things, and then defend those choices. Nobody expects a finished product. They expect a visible, orderly thought process that ends with a design they would be happy to extend.

Most candidates who fail LLD rounds don't lack knowledge. They mismanage time. They spend 20 minutes on clarifying questions and never write code, or they open the editor in minute two and paint themselves into a corner. Some draw a beautiful class diagram and then can't say what happens when two people borrow the last copy of a book at once. This page gives you a fixed route through the 45 minutes. It isn't a script. It's a set of checkpoints, so you always know where you are and what to do next.

The route has ten steps. We carry one example, a library lending system, through all of them, so you can see what each step produces. If you want the full library case study with every class in detail, read Design a Library Management System. This page is about the method, and the library is just the vehicle.

The timeline at a glance

#StepMinutesClockWhat exists at the end
1Clarify requirements and scope50–5A short written list of in-scope and out-of-scope features
2Use cases35–84–6 actor–verb–object lines
3Entities and relationships58–13Nouns with owners, cardinalities and lifecycles
4Class diagram713–20A Mermaid or whiteboard diagram of 6–10 classes
5Interfaces and APIs420–24Public method signatures of the main service plus the extension points
6Core logic in code1124–35The one or two methods that carry the business rules, compiling
7Patterns and why335–38Each pattern tied to a requirement, with the alternative you rejected
8Concurrency338–41The shared state named, the locking choice explained
9Extensions341–44One or two "what if" changes shown as small diffs
10Wrap-up144–45A 30-second summary and the known gaps
flowchart LR
    S1["1 Clarify<br/>0-5"] --> S2["2 Use cases<br/>5-8"]
    S2 --> S3["3 Entities<br/>8-13"]
    S3 --> S4["4 Class diagram<br/>13-20"]
    S4 --> S5["5 Interfaces<br/>20-24"]
    S5 --> S6["6 Core code<br/>24-35"]
    S6 --> S7["7 Patterns<br/>35-38"]
    S7 --> S8["8 Concurrency<br/>38-41"]
    S8 --> S9["9 Extensions<br/>41-44"]
    S9 --> S10["10 Wrap-up<br/>44-45"]

These budgets add up to exactly 45 minutes, which means there's no slack in them. Real interviews lose two or three minutes to introductions and a few more to the interviewer's own questions. So treat the clock column as a schedule you're allowed to run behind on by at most three minutes. If you're further behind than that, use the recovery rules in When you fall behind.

Why this order

The order goes from cheap to expensive to change. A wrong requirement costs you a sentence to fix in minute 3 and a rewrite in minute 30. Entities are cheaper to change than classes, classes cheaper than signatures, and signatures cheaper than code. Each step locks in decisions that the next step builds on, so you want the interviewer to confirm each one before you build on it.

How this differs from the overview you may have seen

The LLD interviews overview describes a six-step approach: requirements, entities, relationships, class diagram, code, patterns. This framework is a finer-grained version of the same idea. It adds three steps that interviewers increasingly ask about explicitly (use cases, interfaces, and concurrency), plus a wrap-up that most candidates skip. If the six-step version already works for you, keep it, and borrow just the parts below that fill your gaps.

Step 1: Clarify requirements and scope (0–5 min)

The prompt is vague on purpose. "Design a library system" could mean a catalogue search engine, a self-service kiosk, a librarian's back-office tool, an inter-library loan network, or an e-book licensing service. Each of those is a different design. The interviewer wants to see whether you notice that and narrow the problem down yourself instead of guessing.

What to say aloud

"Before I draw anything, I'd like to pin down what the system does, so I design the right thing. I'll ask a few questions, write down what we agree, and then confirm the list with you."

Then actually write the list down, in a corner of the whiteboard or at the top of the shared document. It becomes your contract. When the interviewer later asks "what about X?", you can point at the list and say whether X was in scope.

The questions to ask

Group your questions so they don't sound like a random interrogation. Four groups cover almost every LLD prompt:

  1. Actors. Who uses it? Members, librarians, an admin, an automated job? Do different actors have different permissions?
  2. Core operations. What are the three or four things the system must do? For the library: search, borrow, return, maybe reserve.
  3. Rules and limits. Where's the business logic? How many books can a member hold? How long is a loan? Are there fines, and how are they calculated? Can a loan be renewed?
  4. Boundaries. Single library or a chain of branches? In-memory or persisted? Is there a UI, or do we stop at the service layer? Do we care about concurrency, meaning several librarians at different desks?

Avoid questions about scale ("how many requests per second?") unless the interviewer brings it up. That's a high-level design question, and asking it in an LLD round suggests you've mixed up the two interviews. A single-process design is the default. If the interviewer wants distributed concerns, they'll say so. The system design course covers that side.

What you write down for the library

IN SCOPE
- Members borrow and return physical copies of books
- A book (title, ISBN) has many copies, and each copy is tracked separately
- Loan limit per member (default 3), loan period 14 days
- Late returns incur a fine: per day late, capped
- Several librarian desks may act at the same time

OUT OF SCOPE (for now)
- Payments for fines (we only compute the amount)
- Search ranking, e-books, inter-branch transfer
- Persistence (in-memory, behind interfaces)

LIKELY EXTENSIONS
- Reservations / holds on a book
- Different member tiers with different limits and fines

The "likely extensions" list does two jobs. It shows the interviewer that you can see where the design will grow, and it tells you where to put interfaces. Every item on it is a hint about which parts of the design should be swappable.

Don't over-clarify

Five minutes means about six to ten questions. If you hit fifteen, you're stalling. A good trick is to propose answers rather than ask open questions: "I'll assume a single branch and in-memory storage unless you'd like otherwise." That's one sentence, and it moves the conversation forward whether the interviewer agrees or not.

Non-functional requirements in LLD

In LLD, "non-functional" doesn't mean latency budgets. It means properties of the code:

  • Correctness under concurrency. Two desks must not lend the same copy.
  • Extensibility. New fine rules or member tiers without editing the core service.
  • Testability. Time-dependent logic (due dates, fines) must be testable without waiting 14 days.

Say these aloud. They justify design decisions later: the injectable clock, the FinePolicy interface, the lock around borrowing.

Step 2: Use cases (5–8 min)

Use cases turn the requirements into concrete interactions. You don't need UML use-case diagrams, because nobody draws them in interviews. A short list in the form actor → verb → object (→ result) is enough:

UC1  Member borrows a copy       -> Loan created, copy ON_LOAN, due date set
UC2  Member returns a copy       -> Loan closed, copy AVAILABLE, fine computed
UC3  Member tries to borrow over limit -> rejected with a reason
UC4  Two desks lend the same copy at once -> exactly one succeeds
UC5  Librarian adds a book and its copies
UC6  (extension) Member places a hold on a book

What to say aloud

"These are the flows I'll design for. UC1 and UC2 are the core, so they're what I'll code. UC3 and UC4 are the edge cases that shape the design. UC5 is plumbing, and I'll treat it as simple setup."

That last sentence matters. You've told the interviewer which use cases you'll implement, which you'll design for, and which you'll wave through. Now you have permission to skip the boring parts later without looking as if you forgot them.

Questions to ask

  • "Is this the right set of flows, or is there one you care about that I've missed?"
  • "Should a failed borrow explain why (over limit, copy unavailable), or is a yes/no enough?" The answer decides between exceptions with messages or result types, and boolean returns.

Use cases also surface edge cases cheaply. Walk each one and ask "what can go wrong here?" For UC2: returning a copy that isn't on loan, or returning on the due date (is that late?). Write the answers next to the use case. You'll turn them into validation code in step 6.

Step 3: Entities and relationships (8–13 min)

Now pull the nouns out of the requirements and use cases. The classic technique is to underline every noun and then throw away the ones that are just attributes or are out of scope. The From Nouns to Classes lesson covers that process in depth, including entities vs value objects. Here's what it produces for the library:

Candidate nounVerdictReason
LibraryBecomes the serviceIt coordinates, it doesn't hold its own data
MemberEntityHas identity and state (active loans)
LibrarianDrop for nowAn actor, but no behaviour of their own in scope
BookValue-like entityTitle and ISBN, shared by all its copies
Copy (book item)EntityIdentity matters: this copy is on loan
LoanEntityLinks a member to a copy over a time window
Due date, fineAttributes / computedA date on Loan, an amount computed by a policy
Fine ruleInterfaceIt's on the "likely extensions" list, so make it swappable
HoldLaterIt's an extension, so we'll leave room for it

The single most important modelling decision in this problem is splitting Book from BookCopy. A candidate who models only Book with a quantity field can't say which copy is damaged, overdue or on hold. Point the split out explicitly, because it's exactly the kind of insight the interviewer is looking for.

Relationships, cardinality and lifecycle

For each pair of entities, state three things: how many, who owns whom, and whether one can exist without the other.

  • Book 1 — * BookCopy. A copy belongs to exactly one book. Copies are created when the library acquires them.
  • Member 1 — * Loan. A member has zero or more loans over time, and at most loanLimit open ones.
  • BookCopy 1 — * Loan. A copy has many loans over its life, but at most one open loan at a time. That's an invariant, and the code must enforce it.
  • Loan → FinePolicy. A loan doesn't own its fine rule. The service applies a policy to a closed loan.

What to say aloud

"The key invariant is: a copy has at most one open loan, and a member has at most N open loans. Everything in the borrow method exists to protect those two facts."

Naming invariants this early is a strong signal. It shows you think of a design as a set of guarantees, not just a set of boxes. When you reach the concurrency step, you'll protect the same two invariants.

Questions to ask

  • "Do we need loan history, or only current loans?" History means keeping closed Loan objects around. Current-only means we can delete them.
  • "Is a member's limit the same for everyone?" If not, the limit lives on a member tier, not as a global constant.

Step 4: Class diagram (13–20 min)

Draw the classes with their key fields and methods, and the relationships between them. Use UML notation loosely but consistently. UML for Interviews covers which arrows to use and which to skip. Aim for six to ten classes. Fewer than five usually means a god class is hiding somewhere. More than twelve in a 45-minute round usually means you're modelling things you won't code.

classDiagram
    class LibraryService {
        -members: map of id to Member
        -copies: map of id to BookCopy
        -openLoans: map of copyId to Loan
        -finePolicy: FinePolicy
        -today: date supplier
        +borrow(memberId, copyId) Loan
        +returnCopy(copyId) long
    }
    class Book {
        +isbn: String
        +title: String
    }
    class BookCopy {
        -id: String
        -status: CopyStatus
        +checkOut()
        +checkIn()
    }
    class CopyStatus {
        <<enumeration>>
        AVAILABLE
        ON_LOAN
    }
    class Member {
        -id: String
        -loanLimit: int
        -activeLoans: int
        +canBorrow() boolean
        +startLoan()
        +endLoan()
    }
    class Loan {
        -dueOn: LocalDate
        -returnedOn: LocalDate
        +daysLate(on) long
        +close(on)
    }
    class FinePolicy {
        <<interface>>
        +fineCents(loan, returnedOn) long
    }
    class PerDayFine {
        -centsPerDay: long
        -capCents: long
    }
    LibraryService o-- Member
    LibraryService o-- BookCopy
    LibraryService o-- Loan
    LibraryService --> FinePolicy
    FinePolicy <|.. PerDayFine
    Book "1" -- "*" BookCopy
    BookCopy --> CopyStatus
    Loan --> BookCopy
    Loan --> Member

A few things about this diagram are deliberate, and you should say them aloud as you draw.

  1. State lives where it belongs. BookCopy owns its status and refuses illegal transitions (checkOut on a copy already on loan throws). Member owns its loan count and refuses to exceed the limit. The service coordinates. It doesn't reach in and flip fields. This is the opposite of an anaemic model.
  2. One interface, where change is expected. FinePolicy is an interface because fines are on the extension list. Member is not an interface, because nothing suggests we need multiple member implementations. Interfaces cost something, so add them only where the requirements point.
  3. Time is a dependency. The service gets "today" from an injected supplier, not from the system clock. That one decision makes the fine logic testable.
  4. No Librarian class. The librarian is the caller of the service, not a domain object with behaviour. If the interviewer adds permissions later, it can come back as a role.

What to say aloud

"I'm keeping LibraryService as a thin coordinator: it looks things up, checks rules in the right order and records the loan. The rules themselves live on Member, BookCopy and FinePolicy, so each one can be tested on its own."

Questions to ask

  • "Does this match what you had in mind, or should I go deeper on any part before I write code?" Ask this every time. Interviewers sometimes have a part they specifically want to see, such as fines or holds, and this is your chance to find out before you spend 11 minutes coding the wrong thing.

Step 5: Interfaces and APIs (20–24 min)

Before writing method bodies, write the signatures of the public surface. It takes four minutes, and it forces you to decide on names, inputs, outputs and failure behaviour while changes are still cheap.

// Public surface of the library core
interface FinePolicy {
    long fineCents(Loan loan, LocalDate returnedOn);   // amount in cents, never negative
}

// LibraryService (a concrete class: one implementation, no interface needed)
//   LibraryService(FinePolicy finePolicy, Supplier<LocalDate> today, int loanDays)
//   Loan borrow(String memberId, String copyId)   throws LibraryException with a reason
//   long returnCopy(String copyId)                returns the fine in cents

Decisions worth saying aloud, because each one is something the interviewer might probe:

  • Money is an integer number of cents. Floating point in money code is a classic red flag. If the interviewer pushes, introduce a small Money value object (see primitive obsession).
  • IDs in, objects out. Callers pass IDs, because that's what a desk terminal or an HTTP layer would have. The service returns domain objects or plain values.
  • Failures are exceptions with reasons. Borrowing can fail for several distinct reasons (unknown member, over limit, copy unavailable). A boolean would hide them. In a language with result types you might return a result instead. Either is fine as long as you choose on purpose.
  • Dependencies through the constructor. The fine policy and the clock are passed in, never created inside. That's dependency injection at its simplest, without a container.

Interfaces are promises

An interface signature is a promise about behaviour as well as types. Write the comment that states the promise: "never negative", "throws if over limit". The interviewer reads those comments as evidence that you think about contracts, which is what the Liskov Substitution Principle is really about.

Step 6: Core logic in code (24–35 min)

This is the longest step, and it's where many interviews are won or lost. You have about 11 minutes. That isn't enough to write everything, so choose the methods that carry the business rules and write those properly. For the library, that's borrow and returnCopy, plus the small domain methods they call. Constructors, getters and setup are typing, not design. Write them last, or abbreviate them with a comment if time is short.

What to say aloud while coding

Narrate decisions, not keystrokes. "Now I'm typing a for loop" is noise. These are signal:

"I check the member's limit before changing the copy's status, so a failed borrow leaves no partial state."

"Return computes the fine from the date the loan closed, using the injected clock, so tests can fast-forward time."

"I'm making the service methods synchronized for now. I'll come back to whether that's too coarse in the concurrency step."

Order of operations matters

Look at how borrow is ordered in the code below. It checks everything that can fail, then mutates state. If you mutate first (mark the copy on loan, then discover the member is over limit), you need rollback code, and rollback code is where bugs live. "Validate, then mutate" is a habit worth showing every time.

The code

All three versions are complete and runnable. Each ends with a small main that walks through the use cases and checks the results, including the concurrent-borrow case.

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

enum CopyStatus { AVAILABLE, ON_LOAN }

class LibraryException extends RuntimeException {
    LibraryException(String message) { super(message); }
}

record Book(String isbn, String title) {}

final class BookCopy {
    private final String id;
    private final Book book;
    private CopyStatus status = CopyStatus.AVAILABLE;

    BookCopy(String id, Book book) { this.id = id; this.book = book; }
    String id() { return id; }
    Book book() { return book; }
    CopyStatus status() { return status; }

    void checkOut() {
        if (status != CopyStatus.AVAILABLE) throw new LibraryException("copy " + id + " is not available");
        status = CopyStatus.ON_LOAN;
    }

    void checkIn() {
        if (status != CopyStatus.ON_LOAN) throw new LibraryException("copy " + id + " is not on loan");
        status = CopyStatus.AVAILABLE;
    }
}

final class Member {
    private final String id;
    private final int loanLimit;
    private int activeLoans;

    Member(String id, int loanLimit) { this.id = id; this.loanLimit = loanLimit; }
    String id() { return id; }
    boolean canBorrow() { return activeLoans < loanLimit; }

    void startLoan() {
        if (!canBorrow()) throw new LibraryException("member " + id + " is at the loan limit of " + loanLimit);
        activeLoans++;
    }

    void endLoan() { activeLoans--; }
}

final class Loan {
    private final BookCopy copy;
    private final Member member;
    private final LocalDate dueOn;
    private LocalDate returnedOn;

    Loan(BookCopy copy, Member member, LocalDate dueOn) {
        this.copy = copy; this.member = member; this.dueOn = dueOn;
    }
    BookCopy copy() { return copy; }
    Member member() { return member; }
    LocalDate dueOn() { return dueOn; }
    long daysLate(LocalDate on) { return Math.max(0, ChronoUnit.DAYS.between(dueOn, on)); }
    void close(LocalDate on) { returnedOn = on; }
}

interface FinePolicy {
    long fineCents(Loan loan, LocalDate returnedOn); // never negative
}

final class PerDayFine implements FinePolicy {
    private final long centsPerDay;
    private final long capCents;

    PerDayFine(long centsPerDay, long capCents) { this.centsPerDay = centsPerDay; this.capCents = capCents; }

    public long fineCents(Loan loan, LocalDate returnedOn) {
        return Math.min(capCents, loan.daysLate(returnedOn) * centsPerDay);
    }
}

final class LibraryService {
    private final Map<String, Member> members = new HashMap<>();
    private final Map<String, BookCopy> copies = new HashMap<>();
    private final Map<String, Loan> openLoans = new HashMap<>(); // keyed by copy id
    private final FinePolicy finePolicy;
    private final Supplier<LocalDate> today;
    private final int loanDays;

    LibraryService(FinePolicy finePolicy, Supplier<LocalDate> today, int loanDays) {
        this.finePolicy = finePolicy; this.today = today; this.loanDays = loanDays;
    }

    synchronized void addMember(Member m) { members.put(m.id(), m); }
    synchronized void addCopy(BookCopy c) { copies.put(c.id(), c); }

    synchronized Loan borrow(String memberId, String copyId) {
        Member member = members.get(memberId);
        BookCopy copy = copies.get(copyId);
        if (member == null) throw new LibraryException("unknown member " + memberId);
        if (copy == null) throw new LibraryException("unknown copy " + copyId);
        if (!member.canBorrow()) throw new LibraryException("member " + memberId + " is at the loan limit");
        copy.checkOut();      // throws if not available, before any other state changes
        member.startLoan();   // cannot fail now: limit checked above, under the same lock
        Loan loan = new Loan(copy, member, today.get().plusDays(loanDays));
        openLoans.put(copyId, loan);
        return loan;
    }

    synchronized long returnCopy(String copyId) {
        Loan loan = openLoans.remove(copyId);
        if (loan == null) throw new LibraryException("copy " + copyId + " has no open loan");
        LocalDate now = today.get();
        loan.close(now);
        loan.copy().checkIn();
        loan.member().endLoan();
        return finePolicy.fineCents(loan, now);
    }
}

public class Library {
    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
        System.out.println("ok  " + what);
    }

    public static void main(String[] args) throws Exception {
        LocalDate[] now = { LocalDate.of(2026, 1, 1) };
        LibraryService lib = new LibraryService(new PerDayFine(25, 500), () -> now[0], 14);
        Book ddd = new Book("978-0321125217", "Domain-Driven Design");
        lib.addCopy(new BookCopy("c1", ddd));
        lib.addCopy(new BookCopy("c2", ddd));
        lib.addMember(new Member("alice", 1));
        lib.addMember(new Member("bob", 3));

        Loan loan = lib.borrow("alice", "c1");
        check(loan.dueOn().equals(LocalDate.of(2026, 1, 15)), "UC1 due date is 14 days out");

        try { lib.borrow("alice", "c2"); check(false, "UC3 limit"); }
        catch (LibraryException e) { check(e.getMessage().contains("limit"), "UC3 over-limit borrow rejected"); }

        try { lib.borrow("bob", "c1"); check(false, "copy taken"); }
        catch (LibraryException e) { check(e.getMessage().contains("not available"), "copy on loan cannot be lent again"); }

        now[0] = LocalDate.of(2026, 1, 18); // 3 days late
        check(lib.returnCopy("c1") == 75, "UC2 fine is 3 days x 25 cents");

        // UC4: eight desks race for the same copy, exactly one wins
        ExecutorService pool = Executors.newFixedThreadPool(8);
        AtomicInteger wins = new AtomicInteger();
        CountDownLatch start = new CountDownLatch(1);
        List<Future<?>> tasks = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            String id = "m" + i;
            lib.addMember(new Member(id, 3));
            tasks.add(pool.submit(() -> {
                start.await();
                try { lib.borrow(id, "c2"); wins.incrementAndGet(); } catch (LibraryException ignored) { }
                return null;
            }));
        }
        start.countDown();
        for (Future<?> t : tasks) t.get();
        pool.shutdown();
        check(wins.get() == 1, "UC4 exactly one concurrent borrow succeeds");
    }
}
from __future__ import annotations

import threading
from dataclasses import dataclass
from datetime import date, timedelta
from enum import Enum
from typing import Callable, Protocol


class CopyStatus(Enum):
    AVAILABLE = "available"
    ON_LOAN = "on_loan"


class LibraryError(Exception):
    pass


@dataclass(frozen=True)
class Book:
    isbn: str
    title: str


class BookCopy:
    def __init__(self, copy_id: str, book: Book) -> None:
        self.id = copy_id
        self.book = book
        self.status = CopyStatus.AVAILABLE

    def check_out(self) -> None:
        if self.status is not CopyStatus.AVAILABLE:
            raise LibraryError(f"copy {self.id} is not available")
        self.status = CopyStatus.ON_LOAN

    def check_in(self) -> None:
        if self.status is not CopyStatus.ON_LOAN:
            raise LibraryError(f"copy {self.id} is not on loan")
        self.status = CopyStatus.AVAILABLE


class Member:
    def __init__(self, member_id: str, loan_limit: int) -> None:
        self.id = member_id
        self._loan_limit = loan_limit
        self._active_loans = 0

    def can_borrow(self) -> bool:
        return self._active_loans < self._loan_limit

    def start_loan(self) -> None:
        if not self.can_borrow():
            raise LibraryError(f"member {self.id} is at the loan limit of {self._loan_limit}")
        self._active_loans += 1

    def end_loan(self) -> None:
        self._active_loans -= 1


class Loan:
    def __init__(self, copy: BookCopy, member: Member, due_on: date) -> None:
        self.copy = copy
        self.member = member
        self.due_on = due_on
        self.returned_on: date | None = None

    def days_late(self, on: date) -> int:
        return max(0, (on - self.due_on).days)

    def close(self, on: date) -> None:
        self.returned_on = on


class FinePolicy(Protocol):
    def fine_cents(self, loan: Loan, returned_on: date) -> int: ...


class PerDayFine:
    def __init__(self, cents_per_day: int, cap_cents: int) -> None:
        self._per_day = cents_per_day
        self._cap = cap_cents

    def fine_cents(self, loan: Loan, returned_on: date) -> int:
        return min(self._cap, loan.days_late(returned_on) * self._per_day)


class LibraryService:
    def __init__(self, fine_policy: FinePolicy, today: Callable[[], date], loan_days: int) -> None:
        self._members: dict[str, Member] = {}
        self._copies: dict[str, BookCopy] = {}
        self._open_loans: dict[str, Loan] = {}  # keyed by copy id
        self._fines = fine_policy
        self._today = today
        self._loan_days = loan_days
        self._lock = threading.Lock()

    def add_member(self, m: Member) -> None:
        with self._lock:
            self._members[m.id] = m

    def add_copy(self, c: BookCopy) -> None:
        with self._lock:
            self._copies[c.id] = c

    def borrow(self, member_id: str, copy_id: str) -> Loan:
        with self._lock:
            member = self._members.get(member_id)
            copy = self._copies.get(copy_id)
            if member is None:
                raise LibraryError(f"unknown member {member_id}")
            if copy is None:
                raise LibraryError(f"unknown copy {copy_id}")
            if not member.can_borrow():
                raise LibraryError(f"member {member_id} is at the loan limit")
            copy.check_out()  # raises before any other state changes
            member.start_loan()
            loan = Loan(copy, member, self._today() + timedelta(days=self._loan_days))
            self._open_loans[copy_id] = loan
            return loan

    def return_copy(self, copy_id: str) -> int:
        with self._lock:
            loan = self._open_loans.pop(copy_id, None)
            if loan is None:
                raise LibraryError(f"copy {copy_id} has no open loan")
            now = self._today()
            loan.close(now)
            loan.copy.check_in()
            loan.member.end_loan()
            return self._fines.fine_cents(loan, now)


def main() -> None:
    now = [date(2026, 1, 1)]
    lib = LibraryService(PerDayFine(25, 500), lambda: now[0], 14)
    ddd = Book("978-0321125217", "Domain-Driven Design")
    lib.add_copy(BookCopy("c1", ddd))
    lib.add_copy(BookCopy("c2", ddd))
    lib.add_member(Member("alice", 1))
    lib.add_member(Member("bob", 3))

    loan = lib.borrow("alice", "c1")
    assert loan.due_on == date(2026, 1, 15), "UC1 due date"

    try:
        lib.borrow("alice", "c2")
        raise AssertionError("UC3 should fail")
    except LibraryError as e:
        assert "limit" in str(e)

    try:
        lib.borrow("bob", "c1")
        raise AssertionError("copy should be taken")
    except LibraryError as e:
        assert "not available" in str(e)

    now[0] = date(2026, 1, 18)  # 3 days late
    assert lib.return_copy("c1") == 75, "UC2 fine"

    # UC4: eight threads race for the same copy
    wins: list[str] = []
    barrier = threading.Barrier(8)

    def attempt(member_id: str) -> None:
        barrier.wait()
        try:
            lib.borrow(member_id, "c2")
            wins.append(member_id)
        except LibraryError:
            pass

    threads = []
    for i in range(8):
        lib.add_member(Member(f"m{i}", 3))
        threads.append(threading.Thread(target=attempt, args=(f"m{i}",)))
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    assert len(wins) == 1, "UC4 exactly one concurrent borrow succeeds"
    print("all library checks passed")


if __name__ == "__main__":
    main()
enum CopyStatus { Available = "AVAILABLE", OnLoan = "ON_LOAN" }

class LibraryError extends Error {}

interface Book { readonly isbn: string; readonly title: string }

class BookCopy {
  private status = CopyStatus.Available;
  constructor(readonly id: string, readonly book: Book) {}

  get currentStatus(): CopyStatus { return this.status; }

  checkOut(): void {
    if (this.status !== CopyStatus.Available) throw new LibraryError(`copy ${this.id} is not available`);
    this.status = CopyStatus.OnLoan;
  }

  checkIn(): void {
    if (this.status !== CopyStatus.OnLoan) throw new LibraryError(`copy ${this.id} is not on loan`);
    this.status = CopyStatus.Available;
  }
}

class Member {
  private activeLoans = 0;
  constructor(readonly id: string, private readonly loanLimit: number) {}

  canBorrow(): boolean { return this.activeLoans < this.loanLimit; }

  startLoan(): void {
    if (!this.canBorrow()) throw new LibraryError(`member ${this.id} is at the loan limit of ${this.loanLimit}`);
    this.activeLoans++;
  }

  endLoan(): void { this.activeLoans--; }
}

const DAY_MS = 24 * 60 * 60 * 1000;
const addDays = (d: Date, n: number): Date => new Date(d.getTime() + n * DAY_MS);

class Loan {
  returnedOn: Date | null = null;
  constructor(readonly copy: BookCopy, readonly member: Member, readonly dueOn: Date) {}

  daysLate(on: Date): number {
    return Math.max(0, Math.floor((on.getTime() - this.dueOn.getTime()) / DAY_MS));
  }

  close(on: Date): void { this.returnedOn = on; }
}

interface FinePolicy {
  fineCents(loan: Loan, returnedOn: Date): number; // never negative
}

class PerDayFine implements FinePolicy {
  constructor(private readonly centsPerDay: number, private readonly capCents: number) {}
  fineCents(loan: Loan, returnedOn: Date): number {
    return Math.min(this.capCents, loan.daysLate(returnedOn) * this.centsPerDay);
  }
}

class LibraryService {
  private readonly members = new Map<string, Member>();
  private readonly copies = new Map<string, BookCopy>();
  private readonly openLoans = new Map<string, Loan>(); // keyed by copy id

  constructor(
    private readonly finePolicy: FinePolicy,
    private readonly today: () => Date,
    private readonly loanDays: number,
  ) {}

  addMember(m: Member): void { this.members.set(m.id, m); }
  addCopy(c: BookCopy): void { this.copies.set(c.id, c); }

  // Synchronous, so it runs to completion on the event loop: no interleaving.
  borrow(memberId: string, copyId: string): Loan {
    const member = this.members.get(memberId);
    const copy = this.copies.get(copyId);
    if (!member) throw new LibraryError(`unknown member ${memberId}`);
    if (!copy) throw new LibraryError(`unknown copy ${copyId}`);
    if (!member.canBorrow()) throw new LibraryError(`member ${memberId} is at the loan limit`);
    copy.checkOut();
    member.startLoan();
    const loan = new Loan(copy, member, addDays(this.today(), this.loanDays));
    this.openLoans.set(copyId, loan);
    return loan;
  }

  returnCopy(copyId: string): number {
    const loan = this.openLoans.get(copyId);
    if (!loan) throw new LibraryError(`copy ${copyId} has no open loan`);
    this.openLoans.delete(copyId);
    const now = this.today();
    loan.close(now);
    loan.copy.checkIn();
    loan.member.endLoan();
    return this.finePolicy.fineCents(loan, now);
  }
}

function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(`FAILED: ${what}`);
  console.log(`ok  ${what}`);
}

function expectError(fn: () => unknown, fragment: string, what: string): void {
  try { fn(); } catch (e) { check(e instanceof LibraryError && e.message.includes(fragment), what); return; }
  check(false, what);
}

let now = new Date(Date.UTC(2026, 0, 1));
const lib = new LibraryService(new PerDayFine(25, 500), () => now, 14);
const ddd: Book = { isbn: "978-0321125217", title: "Domain-Driven Design" };
lib.addCopy(new BookCopy("c1", ddd));
lib.addCopy(new BookCopy("c2", ddd));
lib.addMember(new Member("alice", 1));
lib.addMember(new Member("bob", 3));

const loan = lib.borrow("alice", "c1");
check(loan.dueOn.getTime() === Date.UTC(2026, 0, 15), "UC1 due date is 14 days out");
expectError(() => lib.borrow("alice", "c2"), "limit", "UC3 over-limit borrow rejected");
expectError(() => lib.borrow("bob", "c1"), "not available", "copy on loan cannot be lent again");
now = new Date(Date.UTC(2026, 0, 18));
check(lib.returnCopy("c1") === 75, "UC2 fine is 3 days x 25 cents");

// UC4: concurrent requests are interleaved promises, but borrow() itself never awaits
const attempts = Array.from({ length: 8 }, (_, i) => {
  lib.addMember(new Member(`m${i}`, 3));
  return Promise.resolve().then(() => lib.borrow(`m${i}`, "c2"));
});
Promise.allSettled(attempts).then((results) => {
  check(results.filter((r) => r.status === "fulfilled").length === 1, "UC4 exactly one concurrent borrow succeeds");
});

Here's the borrow flow from the code as a sequence diagram. Drawing one takes about a minute, and it's a strong way to prove the order of operations to the interviewer.

sequenceDiagram
    actor Desk as Librarian desk
    participant S as LibraryService
    participant M as Member
    participant C as BookCopy
    participant L as Loan
    Desk->>S: borrow(memberId, copyId)
    S->>S: acquire lock, look up member and copy
    S->>M: canBorrow()
    M-->>S: true
    S->>C: checkOut()
    Note over C: AVAILABLE becomes ON_LOAN or throws
    S->>M: startLoan()
    S->>L: new Loan(copy, member, today plus 14)
    S->>S: openLoans.put(copyId, loan), release lock
    S-->>Desk: Loan with due date

If you run out of time in this step

Write the method signature, then the body as numbered comments (// 1. look up, // 2. check limit, // 3. check out copy, ...), then fill in the most interesting line or two for real. A clear skeleton of correct logic beats half a method of real code that stops in the middle. Say aloud what you're skipping: "I'm leaving the lookup boilerplate as comments so I can show the fine logic."

Step 7: Patterns and why (35–38 min)

You've probably already used patterns by this point without naming them. This step is where you name them and justify them. The rule is simple. Every pattern must be tied to a requirement from step 1, and you should mention the alternative you rejected.

PatternWhereRequirement it servesAlternative rejected
StrategyFinePolicy / PerDayFine"Different member tiers with different fines" is a likely extensionAn if (tier == ...) chain inside returnCopy, which would need editing for every new tier
Dependency injectionConstructor takes the policy and the date supplierTestability of time-based rulesCalling LocalDate.now() inside the service, which makes fines untestable without waiting
Facade (light)LibraryServiceCallers need one entry point per use caseLetting callers mutate BookCopy and Member directly, which would spread the invariants around
Repository (deferred)The maps inside the service"Persistence out of scope"Introducing MemberRepository interfaces now, which is unjustified until storage is in scope

The last row is deliberate. Saying "I considered X and chose not to use it yet, because Y" is as strong a signal as using X. It shows that patterns are tools you pick up when needed, not a checklist. The over-patterning mistake is about candidates who put every pattern they know into a 45-minute design.

What to say aloud

"I used Strategy for fines because fine rules are the part you said will vary. I deliberately didn't add a State pattern for the copy status. With two states and two transitions, an enum with guarded methods is clearer. If we add holds, damaged and lost, I'd reconsider."

Questions to ask

  • "Are there other areas you expect to vary that I should make pluggable?" Sometimes the interviewer will reveal the extension they plan to ask about, which gives you a head start on step 9.

Step 8: Concurrency (38–41 min)

Many candidates skip this step unless asked. Don't. Even three minutes on it marks you as someone who has shipped code that runs on more than one thread. The structure is always the same.

  1. Name the shared mutable state. Here it's the openLoans map, each copy's status, and each member's loan count.
  2. Name the invariant at risk. A copy must have at most one open loan, and a member must not exceed the limit.
  3. Show the race. Desk A and desk B both read "c2 is AVAILABLE", and both mark it ON_LOAN. Now two members hold the same physical book.
  4. Choose a mechanism and its granularity. Say what you chose and what it costs.
sequenceDiagram
    participant A as Desk A
    participant C as BookCopy c2
    participant B as Desk B
    Note over A,B: Without a lock
    A->>C: read status, AVAILABLE
    B->>C: read status, AVAILABLE
    A->>C: set ON_LOAN
    B->>C: set ON_LOAN
    Note over A,B: Two loans for one copy, the invariant is broken

For our code, the answer is "one lock around each service operation", which is what synchronized and threading.Lock give us. Say the trade-off honestly:

"A single lock is correct and easy to reason about. Its cost is that two desks lending different books wait for each other. For a library that's fine, because a borrow takes microseconds. If contention mattered, I'd lock per copy and per member, always acquiring them in a fixed order to avoid deadlock. Or I'd use a compare-and-set on the copy status."

Mention two finer points if you have time:

  • Check-then-act must be atomic. canBorrow() followed by startLoan() is only safe because both happen under the same lock. Without the lock, two borrows by the same member could both pass the check.
  • TypeScript's model is different. A single Node.js process runs JavaScript on one thread. A synchronous method like borrow runs to completion without interleaving, so it needs no lock. The danger appears as soon as the method contains an await between the check and the update. Then another request can run in the gap. Say this if you code in TypeScript, because it shows you understand why locks exist, not just how to call them.

For a deeper treatment, see race conditions and mutexes, semaphores and monitors.

Step 9: Extensions (41–44 min)

The interviewer will almost always ask "what if we now need X?" This tests whether your design bends or breaks. Answer in three moves:

  1. Say where the change goes. Name the class or interface that absorbs it.
  2. Say what doesn't change. The less you touch, the better the original design was.
  3. Show the diff. A few lines of code or a new box on the diagram.

Extension A: member tiers with different fines and limits

"The loan limit is already per member. For fines, I add a TieredFine policy that looks up the member's tier, or I give each tier its own FinePolicy and pick it in returnCopy. BookCopy, Loan and the borrow logic don't change."

// New class only, nothing existing is edited
final class TieredFine implements FinePolicy {
    private final Map<String, FinePolicy> byTier;   // "student" -> PerDayFine(10, 200), ...
    private final Function<Member, String> tierOf;
    TieredFine(Map<String, FinePolicy> byTier, Function<Member, String> tierOf) {
        this.byTier = byTier; this.tierOf = tierOf;
    }
    public long fineCents(Loan loan, LocalDate returnedOn) {
        return byTier.get(tierOf.apply(loan.member())).fineCents(loan, returnedOn);
    }
}

This is the Open/Closed Principle in its everyday form: new behaviour arrives as a new class.

Extension B: holds (reservations)

This one does touch existing code, and you should say so. Not every extension can be absorbed for free, and pretending otherwise isn't credible.

"Holds add a state to the copy: when a held book is returned, the copy becomes ON_HOLD for the first member in the queue, not AVAILABLE. So CopyStatus gains a value, BookCopy gains a holdFor(member) transition, and returnCopy asks a HoldQueue who's next. borrow must then let the holder, and only the holder, check out an ON_HOLD copy. With four states and more transitions, this is the point where I'd consider the State pattern for BookCopy."

stateDiagram-v2
    [*] --> AVAILABLE
    AVAILABLE --> ON_LOAN: checkOut
    ON_LOAN --> AVAILABLE: checkIn, no holds
    ON_LOAN --> ON_HOLD: checkIn, hold queue not empty
    ON_HOLD --> ON_LOAN: checkOut by holder
    ON_HOLD --> AVAILABLE: hold expires, queue empty

Notice how the earlier decision to keep status changes inside BookCopy pays off here. All the new transitions go in one class. If the service had been flipping status fields directly, holds would mean hunting for every place that sets status.

Step 10: Wrap-up (44–45 min)

Spend the last minute summarising. Most candidates are still typing when time runs out, and the interview just stops. A deliberate wrap-up stands out. It also gives the interviewer a clean recap for their notes, and those notes are what the hiring decision is based on.

"To summarise: the design has one coordinating service and three domain objects that each guard their own rules. Fines are a strategy, so new rules are new classes, and time is injected, so everything is testable. A single lock protects the two invariants. Known gaps: there's no persistence, there's no loan history query, and holds are designed but not coded. If I had more time, I'd write tests for the fine edge cases, like returning on the due date and hitting the cap."

Mentioning the gaps yourself is not admitting weakness. It shows you know where the design stands, and it saves the interviewer from asking.

When you fall behind

Every interview drifts. These rules tell you what to cut, in order, so the most important signals survive.

Behind byCut thisKeep this
3–5 min at the class diagramFields on minor classes and the enum detailsRelationships and the main service's methods
5 min at code startSetup code, getters, constructors (use comments)The body of the one method with the core rule
5+ min after codeExtensions (offer them verbally)Concurrency: name the race and the lock, in 60 seconds
Out of timeEverythingThe 30-second wrap-up, which is always worth it

Two more recovery tactics:

  • Ask the interviewer to choose. "I have about eight minutes left. Would you rather see the return-and-fine logic in code, or discuss concurrency?" This isn't weakness. It's prioritisation, and the interviewer gets to see what they care about most.
  • Don't apologise repeatedly. Saying once "I'm going to compress this part" is fine. Narrating anxiety costs time and reads as a lack of confidence.

Adapting the framework

A 60-minute round

Give the extra 15 minutes to code (add 8, so you can write returnCopy and a test or two), extensions (add 4) and concurrency (add 3). Don't stretch requirements gathering. Five minutes is still enough.

The interviewer drives

Some interviewers walk you through their own sequence ("start with the classes", "now show me the borrow code"). Follow them. The framework still works as an internal checklist. When they move on, make a mental note of which steps you haven't covered, such as concurrency or extensions, and offer them in the wrap-up if they never came up.

Code-first or machine-coding variants

If the round expects runnable code at the end, the shape changes a lot. You'll spend less time on diagrams and much more on a clean project layout, in-memory storage and a driver. That's a different format, covered in Machine Coding Rounds.

Language choice

Use the language you write fastest in. Java and C# make classes and interfaces explicit, which helps interviewers read the design. Python and TypeScript are quicker to type, but you should be more explicit about types in them (type hints, interfaces) so the design stays visible. All three are fine. What isn't fine is switching languages halfway because you got stuck.

A one-page cheat sheet

0-5   CLARIFY      actors / operations / rules / boundaries; write IN, OUT, LIKELY-EXTENSIONS
5-8   USE CASES    actor -> verb -> object; mark which you'll code; list the edge cases
8-13  ENTITIES     nouns -> keep, drop, attribute; cardinality; NAME THE INVARIANTS
13-20 DIAGRAM      6-10 classes; state lives with its owner; interfaces only at extension points
20-24 INTERFACES   signatures, failure behaviour, units (cents), constructor-injected deps
24-35 CODE         core rule methods first; validate then mutate; narrate decisions
35-38 PATTERNS     pattern -> requirement -> alternative rejected
38-41 CONCURRENCY  shared state -> invariant -> race -> lock and its granularity
41-44 EXTENSIONS   where it goes / what doesn't change / small diff
44-45 WRAP-UP      30-second summary + known gaps

Where to go next

Interview questions

These are questions interviewers ask about your process, often at the end of the round or in a debrief. Practise answering each in under a minute.

  1. "Why did you ask about concurrency in the first five minutes?" Because whether multiple actors can mutate the same object at once changes the design. It decides whether status checks and updates must be atomic, and that affects method boundaries, not just a lock you add at the end.
  2. "Why is FinePolicy an interface but Member isn't?" Interfaces should sit where the requirements predict variation. Fine rules were named as a likely change, and nothing suggested multiple kinds of member behaviour. An interface with one implementation and no expected second one is just indirection.
  3. "What's the most important invariant in your design, and where is it enforced?" A copy has at most one open loan. BookCopy.checkOut refuses a second checkout, and the service lock makes check-and-update atomic across threads.
  4. "How would you test the fine calculation without waiting two weeks?" The service takes a date supplier in its constructor. The test passes a supplier it controls, borrows on day 0, moves the date forward and returns. That's the whole reason time is injected.
  5. "You ran out of time before coding returns. What would it have looked like?" Give the steps in order: remove the open loan (fail if missing), close it with today's date, check the copy in, decrement the member's count, then compute the fine from the policy. Saying the order fluently is nearly as good as having typed it.
  6. "If you had to cut one step of your process, which would it be?" Usually the separate interfaces step, which can fold into the class diagram by writing full signatures there. Never cut clarification or the wrap-up. They're the cheapest steps and among the highest-signal ones.
  7. "How would this design change if it had to run across several servers?" The in-process lock no longer protects anything. The invariant has to move into shared storage, for example a conditional update on the copy's row. That's a step into high-level design, and it's worth saying so explicitly.