Design a Library Management System
The library management problem tests CRUD modeling, state transitions (book lifecycle), and business rule enforcement (borrowing limits, fine calculation). It is a practical, relatable problem that interviewers use to assess clean domain modeling.
How this page fits with the framework
The LLD Interview Framework uses a small library as its running example, with one lock around every operation and holds sketched as an extension. This page is the full answer: holds as a real queue with a pickup window, fines against an injected clock, and per-title locking so that desks lending different books never wait for each other, while two desks fighting over the last copy still get exactly one winner.
1. Clarifying questions and requirements
| Question | Assumption if the interviewer says "you decide" | What it changes |
|---|---|---|
| Book or copy? | A Title (ISBN) has many physical Copy objects. Loans are of copies. | Two classes, not one |
| What happens when every copy is out? | The member places a hold. Holds are served first come, first served. | A FIFO queue per title |
| When a held book comes back? | It goes on the hold shelf for the first member in the queue, who has 3 days to collect it. Then it passes to the next. | A READY state, an expiry job, a notifier |
| Loan period and fines? | 14 days. 0.25 per started day late, capped at 10.00. Fines of 10.00 or more block borrowing. | FinePolicy strategy, integer cents, an injected clock |
| Borrowing limit? | Per member, default 5. | An atomic slot counter on Member |
| Several desks at once? | Yes. Two desks can try to lend the last copy at the same moment. | The concurrency design |
| Renewals, lost books, search? | Later, if there's time. | Extensions |
Requirements & Use Cases
Functional Requirements
- Manage books: add, remove, search by title/author/ISBN
- Manage members: register, update, deactivate
- Lending: members borrow books, return books
- Each book can have multiple copies (physical items)
- Borrowing limits: max 5 books per member
- Lending period: 14 days, with fines for late returns
- Reservation: member can reserve a book if all copies are lent out
- Notifications: notify member when reserved book becomes available
Non-Functional Requirements
- Search should be fast (indexed by title, author, ISBN)
- Support concurrent checkouts (two librarians at two desks)
- Fine calculation must be deterministic and auditable
Use Cases
| Actor | Use Case |
|---|---|
| Librarian | Add / remove books from catalog |
| Librarian | Issue a book to a member |
| Librarian | Process a book return |
| Member | Search for a book |
| Member | Reserve a book |
| Member | Pay fines |
| System | Calculate overdue fines |
| System | Notify member when reservation is ready |
2. Entities and relationships
| Entity | Owns or knows | Invariant it protects |
|---|---|---|
Title | Its copies, its waiting queue, its READY holds | A copy is AVAILABLE only when nobody is waiting for the title |
Copy | Barcode, ISBN, status | Exactly one of AVAILABLE, ON_LOAN or ON_HOLD_SHELF |
Member | Loan count, fines owed | Loan count never exceeds the limit |
Loan | Member, copy, due instant | At most one open loan per copy |
Hold | Member, ISBN, status, the copy once READY, pickup deadline | A READY copy can only be borrowed by its holder |
FinePolicy | The fine for an overdue duration | Pure function, no clock inside |
HoldNotifier | Delivery of "your book is ready" | Called outside every lock |
Library | Titles, members, open loans, clock, policies | Coordinates. Every invariant above is enforced by the object that owns the data. |
The key modelling move is the Title aggregate. Copies and the hold queue of one ISBN change together: a return either shelves the copy or hands it to the queue. Putting both behind one object, with one lock, makes that decision atomic without locking the whole library. From Nouns to Classes covers aggregates.
3. Class diagram
classDiagram
class Library {
-titles: Map~String,Title~
-members: Map~String,Member~
-openLoans: Map~String,Loan~
-clock: Clock
-fines: FinePolicy
-notifier: HoldNotifier
+addCopy(isbn, barcode)
+checkout(memberId, isbn) Loan
+returnCopy(barcode) long
+placeHold(memberId, isbn) Hold
+expireHolds()
}
class Title {
+isbn: String
+copies: List~Copy~
+waiting: Deque~Hold~
+ready: List~Hold~
+passOn(copy, readyUntil) Hold
}
class Copy {
+barcode: String
+status: CopyStatus
}
class Member {
+id: String
+maxLoans: int
+tryTakeSlot() boolean
+freeSlot()
+addFine(cents)
}
class Hold {
+status: HoldStatus
+copy: Copy
+readyUntil: Instant
}
class Loan {
<<record>>
+member: Member
+copy: Copy
+due: Instant
}
class FinePolicy {
<<interface>>
+fineCents(overdue) long
}
class PerDayFine
class HoldNotifier {
<<interface>>
+holdReady(hold)
}
Library "1" *-- "many" Title
Library "1" o-- "many" Member
Library "1" o-- "many" Loan : open
Title "1" *-- "many" Copy
Title "1" o-- "many" Hold : queue
Loan --> Copy
Loan --> Member
Hold --> Member
Library --> FinePolicy
Library --> HoldNotifier
FinePolicy <|.. PerDayFine
The first-pass diagram below is kept. Its Book/BookItem split is the same idea as Title/Copy, and its Reservation is a Hold. What it lacks is an owner for the hold queue, which is where its holds bug comes from (see the correction in section 6).
Class Diagram
classDiagram
class Library {
-catalog: BookCatalog
-members: Map~string, Member~
-activeLoans: Map~string, Loan~
+addBook(book: Book, copies: int): void
+registerMember(member: Member): void
+issueBook(memberId: string, isbn: string): Loan?
+returnBook(loanId: string): Fine?
+searchBooks(query: string): Book[]
}
class BookCatalog {
-books: Map~string, Book~
-items: Map~string, BookItem[]~
+addBook(book: Book, copies: int): void
+search(query: string): Book[]
+getAvailableCopy(isbn: string): BookItem?
}
class Book {
-isbn: string
-title: string
-author: string
-publisher: string
-year: int
-category: string
}
class BookItem {
-barcode: string
-isbn: string
-status: BookStatus
-condition: BookCondition
+checkout(): void
+checkin(): void
+isAvailable(): boolean
}
class Member {
-memberId: string
-name: string
-email: string
-activeLoans: Loan[]
-totalFinesOwed: number
-status: MemberStatus
+canBorrow(): boolean
+addLoan(loan: Loan): void
+removeLoan(loanId: string): void
}
class Loan {
-loanId: string
-member: Member
-bookItem: BookItem
-issueDate: Date
-dueDate: Date
-returnDate: Date?
+isOverdue(): boolean
+calculateFine(strategy: FineStrategy): number
}
class Reservation {
-reservationId: string
-member: Member
-book: Book
-createdAt: Date
-status: ReservationStatus
+fulfill(): void
+cancel(): void
}
class FineStrategy {
<<interface>>
+calculate(daysOverdue: int): number
}
class FlatFineStrategy {
-dailyRate: number
+calculate(daysOverdue: int): number
}
class TieredFineStrategy {
+calculate(daysOverdue: int): number
}
class NotificationService {
<<interface>>
+notify(member: Member, message: string): void
}
class EmailNotification {
+notify(member: Member, message: string): void
}
class SMSNotification {
+notify(member: Member, message: string): void
}
Library *-- BookCatalog
Library --> Member
Library --> Loan
BookCatalog *-- Book
BookCatalog *-- BookItem
Book "1" --> "*" BookItem
Member "1" --> "*" Loan
Loan --> BookItem
Loan --> Member
Library --> Reservation
Reservation --> Member
Reservation --> Book
FineStrategy <|.. FlatFineStrategy
FineStrategy <|.. TieredFineStrategy
NotificationService <|.. EmailNotification
NotificationService <|.. SMSNotification
Library --> FineStrategy
Library --> NotificationService
4. Key flows
Two desks, the last copy
sequenceDiagram
participant A as Desk A for ann
participant B as Desk B for bob
participant L as Library
participant T as Title 978-1 lock
A->>L: checkout(ann, 978-1)
B->>L: checkout(bob, 978-1)
L->>L: ann.tryTakeSlot() and bob.tryTakeSlot() both succeed
L->>T: lock for ann
Note over T: bob's thread waits here
T-->>L: C1 is AVAILABLE, mark ON_LOAN
L-->>A: Loan L1
L->>T: lock for bob
T-->>L: no AVAILABLE copy
L->>L: bob.freeSlot()
L-->>B: error, place a hold
Return with a hold waiting
sequenceDiagram
participant D as Desk
participant L as Library
participant C as Clock
participant F as FinePolicy
participant T as Title
participant N as HoldNotifier
D->>L: returnCopy(C1)
L->>L: remove open loan for C1, atomically
L->>C: instant()
L->>F: fineCents(now minus due)
F-->>L: 75
L->>T: passOn(C1), under the title lock
T-->>L: bob's hold is READY until now plus 3 days
L->>N: holdReady(bob), after the lock is released
L-->>D: fine 0.75
Lifecycles
stateDiagram-v2
state "Copy" as CopyLife {
[*] --> AVAILABLE
AVAILABLE --> ON_LOAN: checkout
ON_LOAN --> AVAILABLE: return, nobody waiting
ON_LOAN --> ON_HOLD_SHELF: return, queue not empty
ON_HOLD_SHELF --> ON_LOAN: holder checks out
ON_HOLD_SHELF --> ON_HOLD_SHELF: pickup expires, next in queue
ON_HOLD_SHELF --> AVAILABLE: pickup expires, queue empty
}
state "Hold" as HoldLife {
[*] --> WAITING: placeHold
WAITING --> READY: a copy is passed on
READY --> FULFILLED: holder checks out
READY --> EXPIRED: pickup window passes
FULFILLED --> [*]
EXPIRED --> [*]
}
5. Patterns used, and the alternatives rejected
| Pattern | Where | Why |
|---|---|---|
| Strategy | FinePolicy | Fine rules change by branch, tier and year. Library doesn't. |
| Decorator | GracePeriodFine (extension 3) | A rule wrapped around another rule |
| Observer | HoldNotifier | Email, SMS and app push can be added without touching lending |
| Aggregate | Title owns copies and holds | One lock per decision that must be atomic |
| Injected clock | Clock parameter | Fines and expiry are tested by moving time. See Designing for Testability. |
| Alternative | Why it was rejected |
|---|---|
| One lock around the whole library | Correct (the framework page uses it), but desks lending different books wait for each other |
| A lock per copy | The decision "any copy free, or give it to the queue" spans all copies of a title |
State pattern for Copy | Three states and five transitions fit in one class. Reach for State when each state has substantial behaviour. |
Member.borrow(book) | The member doesn't own the copy or the queue. Rules spanning both belong to the coordinator. |
| A priority queue for holds | Nothing asked for priority, and FIFO is what members expect. |
Design Patterns Used
| Pattern | Where | Why |
|---|---|---|
| Strategy | FineStrategy with Flat and Tiered implementations | Swap fine calculation logic without modifying Loan or Library |
| Observer | NotificationService notifies members on reservation readiness | Decouple notification delivery from reservation logic |
| Facade | Library class | Single entry point for all operations; hides catalog/loan/reservation internals |
| Repository | BookCatalog encapsulates book storage and search | Separation of storage concerns from business logic |
6. Complete code
Each version runs on its own and prints library: all checks passed. All three ran before publishing, and the Java demo's two race tests each repeat 100 times:
- Java 24:
javac -d out LibraryDemo.java && java -cp out LibraryDemo - Python 3.12:
python library.py - TypeScript (strict):
tsc --strict --noEmit --target es2022 --types node library.ts && npx tsx library.ts
import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
enum CopyStatus { AVAILABLE, ON_LOAN, ON_HOLD_SHELF }
enum HoldStatus { WAITING, READY, FULFILLED, EXPIRED }
final class Copy {
final String barcode, isbn;
CopyStatus status = CopyStatus.AVAILABLE; // guarded by its Title's monitor
Copy(String barcode, String isbn) { this.barcode = barcode; this.isbn = isbn; }
}
final class Member {
final String id;
final int maxLoans;
private final AtomicInteger loans = new AtomicInteger();
private final AtomicLong finesCents = new AtomicLong();
Member(String id, int maxLoans) { this.id = id; this.maxLoans = maxLoans; }
/** Atomically claims one loan slot, or fails if the member is at the limit. */
boolean tryTakeSlot() {
while (true) {
int n = loans.get();
if (n >= maxLoans) return false;
if (loans.compareAndSet(n, n + 1)) return true;
}
}
void freeSlot() { loans.decrementAndGet(); }
int loans() { return loans.get(); }
void addFine(long cents) { finesCents.addAndGet(cents); }
long finesCents() { return finesCents.get(); }
}
final class Hold {
final String id; final Member member; final String isbn;
HoldStatus status = HoldStatus.WAITING; // guarded by its Title's monitor
Copy copy; Instant readyUntil;
Hold(String id, Member member, String isbn) { this.id = id; this.member = member; this.isbn = isbn; }
}
record Loan(String id, Member member, Copy copy, Instant due) {}
/** All copies and holds of one ISBN. Its monitor is the lock for both. */
final class Title {
final String isbn;
final List<Copy> copies = new ArrayList<>();
final Deque<Hold> waiting = new ArrayDeque<>();
final List<Hold> ready = new ArrayList<>();
Title(String isbn) { this.isbn = isbn; }
/** A returned or released copy goes to the next waiting hold, else back on the shelf. */
Hold passOn(Copy copy, Instant readyUntil) {
Hold next = waiting.poll();
if (next == null) { copy.status = CopyStatus.AVAILABLE; return null; }
next.status = HoldStatus.READY; next.copy = copy; next.readyUntil = readyUntil;
copy.status = CopyStatus.ON_HOLD_SHELF;
ready.add(next);
return next;
}
}
interface FinePolicy { long fineCents(Duration overdue); }
/** Per started day late, capped. */
final class PerDayFine implements FinePolicy {
private final long centsPerDay, capCents;
PerDayFine(long centsPerDay, long capCents) { this.centsPerDay = centsPerDay; this.capCents = capCents; }
public long fineCents(Duration overdue) {
if (overdue.isNegative() || overdue.isZero()) return 0;
long startedDays = (overdue.toSeconds() + 86_399) / 86_400;
return Math.min(capCents, startedDays * centsPerDay);
}
}
interface HoldNotifier { void holdReady(Hold hold); }
final class Library {
static final Duration LOAN_PERIOD = Duration.ofDays(14), PICKUP_WINDOW = Duration.ofDays(3);
static final long BLOCK_AT_CENTS = 1_000;
private final Map<String, Title> titles = new ConcurrentHashMap<>();
private final Map<String, Member> members = new ConcurrentHashMap<>();
private final Map<String, Loan> openLoans = new ConcurrentHashMap<>(); // barcode -> loan
private final AtomicLong seq = new AtomicLong();
private final Clock clock;
private final FinePolicy fines;
private final HoldNotifier notifier;
Library(Clock clock, FinePolicy fines, HoldNotifier notifier) {
this.clock = clock; this.fines = fines; this.notifier = notifier;
}
void addCopy(String isbn, String barcode) {
Title t = titles.computeIfAbsent(isbn, Title::new);
Hold ready;
synchronized (t) {
Copy c = new Copy(barcode, isbn);
t.copies.add(c);
ready = t.passOn(c, clock.instant().plus(PICKUP_WINDOW));
}
if (ready != null) notifier.holdReady(ready);
}
void addMember(Member m) { members.put(m.id, m); }
Loan checkout(String memberId, String isbn) {
Member m = get(members, memberId);
Title t = get(titles, isbn);
if (m.finesCents() >= BLOCK_AT_CENTS) throw new IllegalStateException("fines owed");
if (!m.tryTakeSlot()) throw new IllegalStateException("loan limit reached");
try {
synchronized (t) {
Copy c = takeReadyHoldCopy(t, m);
if (c == null) {
c = t.copies.stream().filter(x -> x.status == CopyStatus.AVAILABLE).findFirst()
.orElseThrow(() -> new IllegalStateException("no copy available, place a hold"));
}
c.status = CopyStatus.ON_LOAN;
Loan loan = new Loan("L" + seq.incrementAndGet(), m, c, clock.instant().plus(LOAN_PERIOD));
openLoans.put(c.barcode, loan);
return loan;
}
} catch (RuntimeException e) {
m.freeSlot(); // give the slot back on any failure
throw e;
}
}
private Copy takeReadyHoldCopy(Title t, Member m) {
for (Iterator<Hold> it = t.ready.iterator(); it.hasNext(); ) {
Hold h = it.next();
if (h.member == m) { it.remove(); h.status = HoldStatus.FULFILLED; return h.copy; }
}
return null;
}
/** Returns the fine charged, in cents. */
long returnCopy(String barcode) {
Loan loan = openLoans.remove(barcode); // atomic: one return per loan
if (loan == null) throw new IllegalArgumentException("no open loan for " + barcode);
long fine = fines.fineCents(Duration.between(loan.due(), clock.instant()));
loan.member().addFine(fine);
loan.member().freeSlot();
Title t = titles.get(loan.copy().isbn);
Hold ready;
synchronized (t) { ready = t.passOn(loan.copy(), clock.instant().plus(PICKUP_WINDOW)); }
if (ready != null) notifier.holdReady(ready); // never call out while holding a lock
return fine;
}
Hold placeHold(String memberId, String isbn) {
Member m = get(members, memberId);
Title t = get(titles, isbn);
synchronized (t) {
if (t.copies.stream().anyMatch(c -> c.status == CopyStatus.AVAILABLE))
throw new IllegalStateException("a copy is available, borrow it instead");
if (t.waiting.stream().anyMatch(h -> h.member == m) || t.ready.stream().anyMatch(h -> h.member == m))
throw new IllegalStateException("already holding");
Hold h = new Hold("H" + seq.incrementAndGet(), m, isbn);
t.waiting.add(h);
return h;
}
}
/** Run periodically. Uncollected holds expire and their copies move on. */
void expireHolds() {
Instant now = clock.instant();
List<Hold> notify = new ArrayList<>();
for (Title t : titles.values()) {
synchronized (t) {
for (Hold h : List.copyOf(t.ready)) {
if (now.isAfter(h.readyUntil)) {
t.ready.remove(h);
h.status = HoldStatus.EXPIRED;
Hold next = t.passOn(h.copy, now.plus(PICKUP_WINDOW));
if (next != null) notify.add(next);
}
}
}
}
notify.forEach(notifier::holdReady);
}
private static <T> T get(Map<String, T> map, String key) {
T v = map.get(key);
if (v == null) throw new IllegalArgumentException("unknown id " + key);
return v;
}
}
final class FakeClock extends Clock {
private volatile Instant now;
FakeClock(Instant start) { now = start; }
void advance(Duration d) { now = now.plus(d); }
public Instant instant() { return now; }
public ZoneId getZone() { return ZoneOffset.UTC; }
public Clock withZone(ZoneId z) { return this; }
}
public class LibraryDemo {
static void check(boolean ok, String msg) { if (!ok) throw new AssertionError(msg); }
static boolean fails(Runnable r) {
try { r.run(); return false; } catch (RuntimeException e) { return true; }
}
public static void main(String[] args) throws Exception {
FakeClock clock = new FakeClock(Instant.parse("2026-11-10T10:00:00Z"));
List<String> notified = new ArrayList<>();
Library lib = new Library(clock, new PerDayFine(25, 1_000), h -> notified.add(h.member.id));
lib.addCopy("978-1", "C1");
for (String id : List.of("ann", "bob", "cat")) lib.addMember(new Member(id, 2));
// Fines: due in 14 days, returned 2 days and 1 second late = 3 started days.
lib.checkout("ann", "978-1");
clock.advance(Duration.ofDays(16).plusSeconds(1));
check(lib.returnCopy("C1") == 75, "3 started days at 25c");
check(fails(() -> lib.returnCopy("C1")), "double return rejected");
// Holds: queue is FIFO and a READY copy is kept for its holder.
lib.checkout("ann", "978-1");
check(fails(() -> lib.checkout("bob", "978-1")), "no copy for bob");
lib.placeHold("bob", "978-1");
lib.placeHold("cat", "978-1");
lib.returnCopy("C1");
check(notified.equals(List.of("bob")), "bob notified first");
check(fails(() -> lib.checkout("cat", "978-1")), "copy on the hold shelf is bob's");
clock.advance(Duration.ofDays(3).plusSeconds(1)); // bob never collects
lib.expireHolds();
check(notified.equals(List.of("bob", "cat")), "hold passes to cat");
check(lib.checkout("cat", "978-1").copy().barcode.equals("C1"), "cat collects");
// Concurrency 1: 16 desks race for the last copy, 100 rounds.
for (int round = 0; round < 100; round++) {
Library race = new Library(clock, new PerDayFine(25, 1_000), h -> {});
race.addCopy("978-9", "LAST");
for (int i = 0; i < 16; i++) race.addMember(new Member("m" + i, 5));
check(runTogether(16, i -> race.checkout("m" + i, "978-9")) == 1, "exactly one winner");
}
// Concurrency 2: one member at 8 desks borrowing 8 different books, limit 2.
for (int round = 0; round < 100; round++) {
Library race = new Library(clock, new PerDayFine(25, 1_000), h -> {});
for (int i = 0; i < 8; i++) race.addCopy("isbn-" + i, "b" + i);
Member m = new Member("greedy", 2);
race.addMember(m);
check(runTogether(8, i -> race.checkout("greedy", "isbn-" + i)) == 2, "limit holds under races");
check(m.loans() == 2, "slot count matches loans");
}
System.out.println("library: all checks passed");
}
/** Starts n tasks at once and counts the ones that didn't throw. */
static int runTogether(int n, java.util.function.IntConsumer task) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(n);
CountDownLatch start = new CountDownLatch(1);
List<Future<Boolean>> fs = new ArrayList<>();
for (int i = 0; i < n; i++) {
int id = i;
fs.add(pool.submit(() -> { start.await(); try { task.accept(id); return true; } catch (IllegalStateException e) { return false; } }));
}
start.countDown();
int ok = 0;
for (Future<Boolean> f : fs) if (f.get()) ok++;
pool.shutdown();
return ok;
}
}
from __future__ import annotations
import itertools
import threading
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from typing import Callable, Optional, Protocol
LOAN_PERIOD = timedelta(days=14)
PICKUP_WINDOW = timedelta(days=3)
BLOCK_AT_CENTS = 1_000
class CopyStatus(Enum):
AVAILABLE = "AVAILABLE"
ON_LOAN = "ON_LOAN"
ON_HOLD_SHELF = "ON_HOLD_SHELF"
class HoldStatus(Enum):
WAITING = "WAITING"
READY = "READY"
FULFILLED = "FULFILLED"
EXPIRED = "EXPIRED"
@dataclass(eq=False)
class Copy:
barcode: str
isbn: str
status: CopyStatus = CopyStatus.AVAILABLE # guarded by its Title's lock
class Member:
def __init__(self, member_id: str, max_loans: int):
self.id = member_id
self.max_loans = max_loans
self.loans = 0
self.fines_cents = 0
self._lock = threading.Lock()
def try_take_slot(self) -> bool:
with self._lock:
if self.loans >= self.max_loans:
return False
self.loans += 1
return True
def free_slot(self) -> None:
with self._lock:
self.loans -= 1
def add_fine(self, cents: int) -> None:
with self._lock:
self.fines_cents += cents
@dataclass(eq=False)
class Hold:
id: str
member: Member
isbn: str
status: HoldStatus = HoldStatus.WAITING
copy: Optional[Copy] = None
ready_until: Optional[datetime] = None
@dataclass(frozen=True)
class Loan:
id: str
member: Member
copy: Copy
due: datetime
@dataclass(eq=False)
class Title:
"""All copies and holds of one ISBN, guarded by one lock."""
isbn: str
copies: list[Copy] = field(default_factory=list)
waiting: deque[Hold] = field(default_factory=deque)
ready: list[Hold] = field(default_factory=list)
lock: threading.Lock = field(default_factory=threading.Lock)
def pass_on(self, copy: Copy, ready_until: datetime) -> Optional[Hold]:
if not self.waiting:
copy.status = CopyStatus.AVAILABLE
return None
nxt = self.waiting.popleft()
nxt.status, nxt.copy, nxt.ready_until = HoldStatus.READY, copy, ready_until
copy.status = CopyStatus.ON_HOLD_SHELF
self.ready.append(nxt)
return nxt
class FinePolicy(Protocol):
def fine_cents(self, overdue: timedelta) -> int: ...
class PerDayFine:
def __init__(self, cents_per_day: int, cap_cents: int):
self._per_day, self._cap = cents_per_day, cap_cents
def fine_cents(self, overdue: timedelta) -> int:
if overdue <= timedelta(0):
return 0
started_days = -(-int(overdue.total_seconds()) // 86_400)
return min(self._cap, started_days * self._per_day)
class LibraryError(Exception):
pass
class Library:
def __init__(self, clock: Callable[[], datetime], fines: FinePolicy,
notify: Callable[[Hold], None]):
self._clock, self._fines, self._notify = clock, fines, notify
self._titles: dict[str, Title] = {}
self._members: dict[str, Member] = {}
self._open_loans: dict[str, Loan] = {} # barcode -> loan
self._loans_lock = threading.Lock()
self._seq = itertools.count(1)
def add_copy(self, isbn: str, barcode: str) -> None:
title = self._titles.setdefault(isbn, Title(isbn))
with title.lock:
copy = Copy(barcode, isbn)
title.copies.append(copy)
ready = title.pass_on(copy, self._clock() + PICKUP_WINDOW)
if ready:
self._notify(ready)
def add_member(self, member: Member) -> None:
self._members[member.id] = member
def checkout(self, member_id: str, isbn: str) -> Loan:
member, title = self._members[member_id], self._titles[isbn]
if member.fines_cents >= BLOCK_AT_CENTS:
raise LibraryError("fines owed")
if not member.try_take_slot():
raise LibraryError("loan limit reached")
try:
with title.lock:
copy = self._take_ready_hold_copy(title, member)
if copy is None:
copy = next((c for c in title.copies if c.status is CopyStatus.AVAILABLE), None)
if copy is None:
raise LibraryError("no copy available, place a hold")
copy.status = CopyStatus.ON_LOAN
loan = Loan(f"L{next(self._seq)}", member, copy, self._clock() + LOAN_PERIOD)
with self._loans_lock:
self._open_loans[copy.barcode] = loan
return loan
except Exception:
member.free_slot()
raise
@staticmethod
def _take_ready_hold_copy(title: Title, member: Member) -> Optional[Copy]:
for hold in title.ready:
if hold.member is member:
title.ready.remove(hold)
hold.status = HoldStatus.FULFILLED
return hold.copy
return None
def return_copy(self, barcode: str) -> int:
with self._loans_lock:
loan = self._open_loans.pop(barcode, None)
if loan is None:
raise LibraryError(f"no open loan for {barcode}")
fine = self._fines.fine_cents(self._clock() - loan.due)
loan.member.add_fine(fine)
loan.member.free_slot()
title = self._titles[loan.copy.isbn]
with title.lock:
ready = title.pass_on(loan.copy, self._clock() + PICKUP_WINDOW)
if ready:
self._notify(ready) # outside the lock
return fine
def place_hold(self, member_id: str, isbn: str) -> Hold:
member, title = self._members[member_id], self._titles[isbn]
with title.lock:
if any(c.status is CopyStatus.AVAILABLE for c in title.copies):
raise LibraryError("a copy is available, borrow it instead")
if any(h.member is member for h in [*title.waiting, *title.ready]):
raise LibraryError("already holding")
hold = Hold(f"H{next(self._seq)}", member, isbn)
title.waiting.append(hold)
return hold
def expire_holds(self) -> None:
now, to_notify = self._clock(), []
for title in list(self._titles.values()):
with title.lock:
for hold in [h for h in title.ready if now > h.ready_until]:
title.ready.remove(hold)
hold.status = HoldStatus.EXPIRED
nxt = title.pass_on(hold.copy, now + PICKUP_WINDOW)
if nxt:
to_notify.append(nxt)
for hold in to_notify:
self._notify(hold)
class FakeClock:
def __init__(self, start: datetime):
self.now = start
def __call__(self) -> datetime:
return self.now
def advance(self, delta: timedelta) -> None:
self.now += delta
def fails(fn: Callable[[], object]) -> bool:
try:
fn()
return False
except LibraryError:
return True
def demo() -> None:
clock = FakeClock(datetime(2026, 11, 10, 10, 0))
notified: list[str] = []
lib = Library(clock, PerDayFine(25, 1_000), lambda h: notified.append(h.member.id))
lib.add_copy("978-1", "C1")
for mid in ("ann", "bob", "cat"):
lib.add_member(Member(mid, 2))
lib.checkout("ann", "978-1")
clock.advance(timedelta(days=16, seconds=1))
assert lib.return_copy("C1") == 75
assert fails(lambda: lib.return_copy("C1"))
lib.checkout("ann", "978-1")
assert fails(lambda: lib.checkout("bob", "978-1"))
lib.place_hold("bob", "978-1")
lib.place_hold("cat", "978-1")
lib.return_copy("C1")
assert notified == ["bob"]
assert fails(lambda: lib.checkout("cat", "978-1")) # the shelf copy is bob's
clock.advance(timedelta(days=3, seconds=1))
lib.expire_holds()
assert notified == ["bob", "cat"]
assert lib.checkout("cat", "978-1").copy.barcode == "C1"
print("library: all checks passed")
if __name__ == "__main__":
demo()
const DAY_MS = 86_400_000;
const LOAN_PERIOD_MS = 14 * DAY_MS;
const PICKUP_WINDOW_MS = 3 * DAY_MS;
const BLOCK_AT_CENTS = 1_000;
type CopyStatus = "AVAILABLE" | "ON_LOAN" | "ON_HOLD_SHELF";
type HoldStatus = "WAITING" | "READY" | "FULFILLED" | "EXPIRED";
class Copy {
status: CopyStatus = "AVAILABLE";
constructor(readonly barcode: string, readonly isbn: string) {}
}
class Member {
loans = 0;
finesCents = 0;
constructor(readonly id: string, readonly maxLoans: number) {}
tryTakeSlot(): boolean {
if (this.loans >= this.maxLoans) return false;
this.loans++;
return true;
}
}
class Hold {
status: HoldStatus = "WAITING";
copy: Copy | null = null;
readyUntilMs = 0;
constructor(readonly id: string, readonly member: Member, readonly isbn: string) {}
}
interface Loan { readonly id: string; readonly member: Member; readonly copy: Copy; readonly dueMs: number }
class Title {
readonly copies: Copy[] = [];
readonly waiting: Hold[] = [];
readonly ready: Hold[] = [];
constructor(readonly isbn: string) {}
passOn(copy: Copy, readyUntilMs: number): Hold | null {
const next = this.waiting.shift();
if (!next) { copy.status = "AVAILABLE"; return null; }
next.status = "READY"; next.copy = copy; next.readyUntilMs = readyUntilMs;
copy.status = "ON_HOLD_SHELF";
this.ready.push(next);
return next;
}
}
interface FinePolicy { fineCents(overdueMs: number): number }
class PerDayFine implements FinePolicy {
constructor(private readonly centsPerDay: number, private readonly capCents: number) {}
fineCents(overdueMs: number): number {
if (overdueMs <= 0) return 0;
return Math.min(this.capCents, Math.ceil(overdueMs / DAY_MS) * this.centsPerDay);
}
}
class LibraryError extends Error {}
class Library {
protected readonly titles = new Map<string, Title>();
protected readonly members = new Map<string, Member>();
protected readonly openLoans = new Map<string, Loan>(); // barcode -> loan
private seq = 0;
constructor(
protected readonly now: () => number,
private readonly fines: FinePolicy,
private readonly notify: (hold: Hold) => void,
) {}
addCopy(isbn: string, barcode: string): void {
let title = this.titles.get(isbn);
if (!title) { title = new Title(isbn); this.titles.set(isbn, title); }
const copy = new Copy(barcode, isbn);
title.copies.push(copy);
const ready = title.passOn(copy, this.now() + PICKUP_WINDOW_MS);
if (ready) this.notify(ready);
}
addMember(m: Member): void { this.members.set(m.id, m); }
/** Synchronous from first check to last write: no await, so no interleaving. */
checkout(memberId: string, isbn: string): Loan {
const member = this.must(this.members, memberId);
const title = this.must(this.titles, isbn);
if (member.finesCents >= BLOCK_AT_CENTS) throw new LibraryError("fines owed");
if (!member.tryTakeSlot()) throw new LibraryError("loan limit reached");
const readyIdx = title.ready.findIndex((h) => h.member === member);
let copy: Copy | undefined;
if (readyIdx >= 0) {
const [hold] = title.ready.splice(readyIdx, 1);
hold.status = "FULFILLED";
copy = hold.copy!;
} else {
copy = title.copies.find((c) => c.status === "AVAILABLE");
}
if (!copy) { member.loans--; throw new LibraryError("no copy available, place a hold"); }
copy.status = "ON_LOAN";
const loan: Loan = { id: `L${++this.seq}`, member, copy, dueMs: this.now() + LOAN_PERIOD_MS };
this.openLoans.set(copy.barcode, loan);
return loan;
}
returnCopy(barcode: string): number {
const loan = this.openLoans.get(barcode);
if (!loan) throw new LibraryError(`no open loan for ${barcode}`);
this.openLoans.delete(barcode);
const fine = this.fines.fineCents(this.now() - loan.dueMs);
loan.member.finesCents += fine;
loan.member.loans--;
const ready = this.titles.get(loan.copy.isbn)!.passOn(loan.copy, this.now() + PICKUP_WINDOW_MS);
if (ready) this.notify(ready);
return fine;
}
placeHold(memberId: string, isbn: string): Hold {
const member = this.must(this.members, memberId);
const title = this.must(this.titles, isbn);
if (title.copies.some((c) => c.status === "AVAILABLE")) throw new LibraryError("a copy is available, borrow it instead");
if ([...title.waiting, ...title.ready].some((h) => h.member === member)) throw new LibraryError("already holding");
const hold = new Hold(`H${++this.seq}`, member, isbn);
title.waiting.push(hold);
return hold;
}
expireHolds(): void {
const now = this.now();
for (const title of this.titles.values()) {
for (const hold of title.ready.filter((h) => now > h.readyUntilMs)) {
title.ready.splice(title.ready.indexOf(hold), 1);
hold.status = "EXPIRED";
const next = title.passOn(hold.copy!, now + PICKUP_WINDOW_MS);
if (next) this.notify(next);
}
}
}
protected must<T>(map: Map<string, T>, key: string): T {
const v = map.get(key);
if (v === undefined) throw new LibraryError(`unknown id ${key}`);
return v;
}
}
// ─── Demo and self-checks ─────────────────────────────────
function check(ok: boolean, msg: string): void { if (!ok) throw new Error(`check failed: ${msg}`); }
function fails(fn: () => unknown): boolean { try { fn(); return false; } catch (e) { return e instanceof LibraryError; } }
const lookup = () => new Promise<void>((r) => setTimeout(r, Math.random() * 3)); // a desk's I/O
async function main(): Promise<void> {
let nowMs = Date.parse("2026-11-10T10:00:00Z");
const notified: string[] = [];
const lib = new Library(() => nowMs, new PerDayFine(25, 1_000), (h) => notified.push(h.member.id));
lib.addCopy("978-1", "C1");
for (const id of ["ann", "bob", "cat"]) lib.addMember(new Member(id, 2));
lib.checkout("ann", "978-1");
nowMs += 16 * DAY_MS + 1_000;
check(lib.returnCopy("C1") === 75, "3 started days");
check(fails(() => lib.returnCopy("C1")), "double return");
lib.checkout("ann", "978-1");
lib.placeHold("bob", "978-1");
lib.placeHold("cat", "978-1");
lib.returnCopy("C1");
check(notified.join() === "bob", "bob first");
check(fails(() => lib.checkout("cat", "978-1")), "shelf copy is bob's");
nowMs += 3 * DAY_MS + 1_000;
lib.expireHolds();
check(notified.join() === "bob,cat", "passes to cat");
check(lib.checkout("cat", "978-1").copy.barcode === "C1", "cat collects");
// 16 async desks race for the last copy. Each awaits I/O, then checks out synchronously.
const race = new Library(() => nowMs, new PerDayFine(25, 1_000), () => {});
race.addCopy("978-9", "LAST");
for (let i = 0; i < 16; i++) race.addMember(new Member(`m${i}`, 5));
const results = await Promise.all(Array.from({ length: 16 }, async (_, i) => {
await lookup();
return !fails(() => race.checkout(`m${i}`, "978-9"));
}));
check(results.filter(Boolean).length === 1, "exactly one winner");
console.log("library: all checks passed");
}
main().catch((e) => { console.error(e); process.exit(1); });
checkout takes the member's slot before the title lock and gives it back on any failure. That ordering means no thread ever holds two locks, so there's no lock-ordering rule to get wrong.
Earlier reference implementation
The first version of this page is kept below. It reads well, but it has the bugs listed after it.
Core Classes & Interfaces
TypeScript Implementation
// ─── Enums ───────────────────────────────────────────────
enum BookStatus {
AVAILABLE = 'AVAILABLE',
CHECKED_OUT = 'CHECKED_OUT',
RESERVED = 'RESERVED',
LOST = 'LOST',
DAMAGED = 'DAMAGED',
}
enum BookCondition {
NEW = 'NEW',
GOOD = 'GOOD',
FAIR = 'FAIR',
POOR = 'POOR',
}
enum MemberStatus {
ACTIVE = 'ACTIVE',
SUSPENDED = 'SUSPENDED',
CLOSED = 'CLOSED',
}
enum ReservationStatus {
PENDING = 'PENDING',
READY = 'READY',
FULFILLED = 'FULFILLED',
CANCELLED = 'CANCELLED',
}
// ─── Constants ───────────────────────────────────────────
const MAX_BOOKS_PER_MEMBER = 5;
const LOAN_PERIOD_DAYS = 14;
const MAX_FINE_BEFORE_SUSPENSION = 50; // dollars
// ─── Book & BookItem ─────────────────────────────────────
class Book {
constructor(
public readonly isbn: string,
public readonly title: string,
public readonly author: string,
public readonly publisher: string,
public readonly year: number,
public readonly category: string
) {}
}
class BookItem {
private status: BookStatus = BookStatus.AVAILABLE;
constructor(
public readonly barcode: string,
public readonly isbn: string,
public readonly condition: BookCondition = BookCondition.NEW
) {}
isAvailable(): boolean {
return this.status === BookStatus.AVAILABLE;
}
getStatus(): BookStatus {
return this.status;
}
checkout(): void {
if (!this.isAvailable()) {
throw new Error(`Book item ${this.barcode} is not available`);
}
this.status = BookStatus.CHECKED_OUT;
}
checkin(): void {
this.status = BookStatus.AVAILABLE;
}
markLost(): void {
this.status = BookStatus.LOST;
}
markDamaged(): void {
this.status = BookStatus.DAMAGED;
}
}
// ─── Member ──────────────────────────────────────────────
class Member {
private activeLoans: Map<string, Loan> = new Map();
private totalFinesOwed: number = 0;
private status: MemberStatus = MemberStatus.ACTIVE;
constructor(
public readonly memberId: string,
public name: string,
public email: string
) {}
canBorrow(): boolean {
return (
this.status === MemberStatus.ACTIVE &&
this.activeLoans.size < MAX_BOOKS_PER_MEMBER &&
this.totalFinesOwed < MAX_FINE_BEFORE_SUSPENSION
);
}
addLoan(loan: Loan): void {
this.activeLoans.set(loan.loanId, loan);
}
removeLoan(loanId: string): void {
this.activeLoans.delete(loanId);
}
getActiveLoans(): Loan[] {
return Array.from(this.activeLoans.values());
}
addFine(amount: number): void {
this.totalFinesOwed += amount;
if (this.totalFinesOwed >= MAX_FINE_BEFORE_SUSPENSION) {
this.status = MemberStatus.SUSPENDED;
}
}
payFine(amount: number): void {
this.totalFinesOwed = Math.max(0, this.totalFinesOwed - amount);
if (
this.totalFinesOwed < MAX_FINE_BEFORE_SUSPENSION &&
this.status === MemberStatus.SUSPENDED
) {
this.status = MemberStatus.ACTIVE;
}
}
getTotalFines(): number {
return this.totalFinesOwed;
}
getStatus(): MemberStatus {
return this.status;
}
}
// ─── Loan ────────────────────────────────────────────────
class Loan {
public returnDate: Date | null = null;
constructor(
public readonly loanId: string,
public readonly member: Member,
public readonly bookItem: BookItem,
public readonly issueDate: Date = new Date(),
public readonly dueDate: Date = new Date(
Date.now() + LOAN_PERIOD_DAYS * 24 * 60 * 60 * 1000
)
) {}
isOverdue(): boolean {
const compareDate = this.returnDate ?? new Date();
return compareDate > this.dueDate;
}
getDaysOverdue(): number {
if (!this.isOverdue()) return 0;
const compareDate = this.returnDate ?? new Date();
const diff = compareDate.getTime() - this.dueDate.getTime();
return Math.ceil(diff / (1000 * 60 * 60 * 24));
}
calculateFine(strategy: FineStrategy): number {
return strategy.calculate(this.getDaysOverdue());
}
}
// ─── Fine Strategy (Strategy Pattern) ────────────────────
interface FineStrategy {
calculate(daysOverdue: number): number;
}
class FlatFineStrategy implements FineStrategy {
constructor(private dailyRate: number = 1.0) {}
calculate(daysOverdue: number): number {
return Math.max(0, daysOverdue * this.dailyRate);
}
}
/**
* Days 1-7: $1/day
* Days 8-14: $2/day
* Days 15+: $5/day
*/
class TieredFineStrategy implements FineStrategy {
calculate(daysOverdue: number): number {
if (daysOverdue <= 0) return 0;
let fine = 0;
const tier1 = Math.min(daysOverdue, 7);
fine += tier1 * 1;
if (daysOverdue > 7) {
const tier2 = Math.min(daysOverdue - 7, 7);
fine += tier2 * 2;
}
if (daysOverdue > 14) {
const tier3 = daysOverdue - 14;
fine += tier3 * 5;
}
return fine;
}
}
// ─── Reservation ─────────────────────────────────────────
class Reservation {
private status: ReservationStatus = ReservationStatus.PENDING;
constructor(
public readonly reservationId: string,
public readonly member: Member,
public readonly book: Book,
public readonly createdAt: Date = new Date()
) {}
getStatus(): ReservationStatus {
return this.status;
}
fulfill(): void {
this.status = ReservationStatus.FULFILLED;
}
markReady(): void {
this.status = ReservationStatus.READY;
}
cancel(): void {
this.status = ReservationStatus.CANCELLED;
}
}
// ─── Notification Service (Observer-like) ────────────────
interface NotificationService {
notify(member: Member, message: string): void;
}
class EmailNotification implements NotificationService {
notify(member: Member, message: string): void {
console.log(`EMAIL to ${member.email}: ${message}`);
// In production: integrate with email provider
}
}
class SMSNotification implements NotificationService {
notify(member: Member, message: string): void {
console.log(`SMS to ${member.memberId}: ${message}`);
}
}
// ─── Book Catalog ────────────────────────────────────────
class BookCatalog {
private books: Map<string, Book> = new Map();
private items: Map<string, BookItem[]> = new Map();
private barcodeCounter: number = 0;
addBook(book: Book, copies: number): void {
this.books.set(book.isbn, book);
if (!this.items.has(book.isbn)) {
this.items.set(book.isbn, []);
}
const itemList = this.items.get(book.isbn)!;
for (let i = 0; i < copies; i++) {
const barcode = `BC-${++this.barcodeCounter}`;
itemList.push(new BookItem(barcode, book.isbn));
}
}
getBook(isbn: string): Book | undefined {
return this.books.get(isbn);
}
search(query: string): Book[] {
const q = query.toLowerCase();
return Array.from(this.books.values()).filter(
(b) =>
b.title.toLowerCase().includes(q) ||
b.author.toLowerCase().includes(q) ||
b.isbn.includes(q)
);
}
getAvailableCopy(isbn: string): BookItem | null {
const items = this.items.get(isbn) ?? [];
return items.find((item) => item.isAvailable()) ?? null;
}
getItems(isbn: string): BookItem[] {
return this.items.get(isbn) ?? [];
}
}
// ─── Library (Facade) ────────────────────────────────────
class Library {
private catalog: BookCatalog = new BookCatalog();
private members: Map<string, Member> = new Map();
private activeLoans: Map<string, Loan> = new Map();
private reservations: Map<string, Reservation[]> = new Map();
private loanCounter: number = 0;
private reservationCounter: number = 0;
constructor(
private fineStrategy: FineStrategy = new FlatFineStrategy(),
private notificationService: NotificationService = new EmailNotification()
) {}
// ── Book Management ──────────────────────────────────
addBook(book: Book, copies: number): void {
this.catalog.addBook(book, copies);
}
searchBooks(query: string): Book[] {
return this.catalog.search(query);
}
// ── Member Management ────────────────────────────────
registerMember(member: Member): void {
this.members.set(member.memberId, member);
}
getMember(memberId: string): Member | undefined {
return this.members.get(memberId);
}
// ── Lending ──────────────────────────────────────────
issueBook(memberId: string, isbn: string): Loan | null {
const member = this.members.get(memberId);
if (!member || !member.canBorrow()) return null;
const bookItem = this.catalog.getAvailableCopy(isbn);
if (!bookItem) return null;
bookItem.checkout();
const loanId = `LN-${++this.loanCounter}`;
const loan = new Loan(loanId, member, bookItem);
member.addLoan(loan);
this.activeLoans.set(loanId, loan);
return loan;
}
returnBook(loanId: string): number {
const loan = this.activeLoans.get(loanId);
if (!loan) throw new Error(`Loan ${loanId} not found`);
loan.returnDate = new Date();
loan.bookItem.checkin();
loan.member.removeLoan(loanId);
this.activeLoans.delete(loanId);
// Calculate and apply fine
let fine = 0;
if (loan.isOverdue()) {
fine = loan.calculateFine(this.fineStrategy);
loan.member.addFine(fine);
}
// Check pending reservations for this book
this.processReservations(loan.bookItem.isbn);
return fine;
}
// ── Reservations ─────────────────────────────────────
reserveBook(memberId: string, isbn: string): Reservation | null {
const member = this.members.get(memberId);
const book = this.catalog.getBook(isbn);
if (!member || !book) return null;
// Only allow reservation if no copies are available
if (this.catalog.getAvailableCopy(isbn)) return null;
const resId = `RES-${++this.reservationCounter}`;
const reservation = new Reservation(resId, member, book);
if (!this.reservations.has(isbn)) {
this.reservations.set(isbn, []);
}
this.reservations.get(isbn)!.push(reservation);
return reservation;
}
private processReservations(isbn: string): void {
const pending = this.reservations.get(isbn);
if (!pending || pending.length === 0) return;
// FIFO: first reservation gets notified
const next = pending.find(
(r) => r.getStatus() === ReservationStatus.PENDING
);
if (next) {
next.markReady();
this.notificationService.notify(
next.member,
`Your reserved book "${next.book.title}" is now available. ` +
`Please pick it up within 3 days.`
);
}
}
// ── Fine Management ──────────────────────────────────
payFine(memberId: string, amount: number): void {
const member = this.members.get(memberId);
if (!member) throw new Error(`Member ${memberId} not found`);
member.payFine(amount);
}
setFineStrategy(strategy: FineStrategy): void {
this.fineStrategy = strategy;
}
}
Python Implementation
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from typing import Optional
import math
# ─── Enums ──────────────────────────────────────────────
class BookStatus(Enum):
AVAILABLE = "AVAILABLE"
CHECKED_OUT = "CHECKED_OUT"
RESERVED = "RESERVED"
LOST = "LOST"
DAMAGED = "DAMAGED"
class MemberStatus(Enum):
ACTIVE = "ACTIVE"
SUSPENDED = "SUSPENDED"
CLOSED = "CLOSED"
class ReservationStatus(Enum):
PENDING = "PENDING"
READY = "READY"
FULFILLED = "FULFILLED"
CANCELLED = "CANCELLED"
# ─── Constants ──────────────────────────────────────────
MAX_BOOKS_PER_MEMBER = 5
LOAN_PERIOD_DAYS = 14
MAX_FINE_BEFORE_SUSPENSION = 50.0
# ─── Book & BookItem ───────────────────────────────────
@dataclass(frozen=True)
class Book:
isbn: str
title: str
author: str
publisher: str
year: int
category: str
class BookItem:
def __init__(self, barcode: str, isbn: str):
self.barcode = barcode
self.isbn = isbn
self._status = BookStatus.AVAILABLE
@property
def is_available(self) -> bool:
return self._status == BookStatus.AVAILABLE
def checkout(self) -> None:
if not self.is_available:
raise ValueError(f"Book item {self.barcode} is not available")
self._status = BookStatus.CHECKED_OUT
def checkin(self) -> None:
self._status = BookStatus.AVAILABLE
def mark_lost(self) -> None:
self._status = BookStatus.LOST
# ─── Member ────────────────────────────────────────────
class Member:
def __init__(self, member_id: str, name: str, email: str):
self.member_id = member_id
self.name = name
self.email = email
self._active_loans: dict[str, "Loan"] = {}
self._total_fines = 0.0
self._status = MemberStatus.ACTIVE
@property
def can_borrow(self) -> bool:
return (
self._status == MemberStatus.ACTIVE
and len(self._active_loans) < MAX_BOOKS_PER_MEMBER
and self._total_fines < MAX_FINE_BEFORE_SUSPENSION
)
def add_loan(self, loan: "Loan") -> None:
self._active_loans[loan.loan_id] = loan
def remove_loan(self, loan_id: str) -> None:
self._active_loans.pop(loan_id, None)
def add_fine(self, amount: float) -> None:
self._total_fines += amount
if self._total_fines >= MAX_FINE_BEFORE_SUSPENSION:
self._status = MemberStatus.SUSPENDED
def pay_fine(self, amount: float) -> None:
self._total_fines = max(0, self._total_fines - amount)
if (
self._total_fines < MAX_FINE_BEFORE_SUSPENSION
and self._status == MemberStatus.SUSPENDED
):
self._status = MemberStatus.ACTIVE
@property
def total_fines(self) -> float:
return self._total_fines
# ─── Loan ───────────────────────────────────────────────
class Loan:
def __init__(
self,
loan_id: str,
member: Member,
book_item: BookItem,
):
self.loan_id = loan_id
self.member = member
self.book_item = book_item
self.issue_date = datetime.now()
self.due_date = datetime.now() + timedelta(days=LOAN_PERIOD_DAYS)
self.return_date: Optional[datetime] = None
@property
def is_overdue(self) -> bool:
compare = self.return_date or datetime.now()
return compare > self.due_date
@property
def days_overdue(self) -> int:
if not self.is_overdue:
return 0
compare = self.return_date or datetime.now()
return math.ceil((compare - self.due_date).total_seconds() / 86400)
def calculate_fine(self, strategy: "FineStrategy") -> float:
return strategy.calculate(self.days_overdue)
# ─── Fine Strategy ──────────────────────────────────────
class FineStrategy(ABC):
@abstractmethod
def calculate(self, days_overdue: int) -> float:
...
class FlatFineStrategy(FineStrategy):
def __init__(self, daily_rate: float = 1.0):
self._daily_rate = daily_rate
def calculate(self, days_overdue: int) -> float:
return max(0, days_overdue * self._daily_rate)
class TieredFineStrategy(FineStrategy):
"""
Days 1-7: $1/day
Days 8-14: $2/day
Days 15+: $5/day
"""
def calculate(self, days_overdue: int) -> float:
if days_overdue <= 0:
return 0
fine = 0.0
fine += min(days_overdue, 7) * 1
if days_overdue > 7:
fine += min(days_overdue - 7, 7) * 2
if days_overdue > 14:
fine += (days_overdue - 14) * 5
return fine
# ─── Reservation ────────────────────────────────────────
class Reservation:
def __init__(self, reservation_id: str, member: Member, book: Book):
self.reservation_id = reservation_id
self.member = member
self.book = book
self.created_at = datetime.now()
self._status = ReservationStatus.PENDING
@property
def status(self) -> ReservationStatus:
return self._status
def mark_ready(self) -> None:
self._status = ReservationStatus.READY
def fulfill(self) -> None:
self._status = ReservationStatus.FULFILLED
def cancel(self) -> None:
self._status = ReservationStatus.CANCELLED
# ─── Notification Service ──────────────────────────────
class NotificationService(ABC):
@abstractmethod
def notify(self, member: Member, message: str) -> None:
...
class EmailNotification(NotificationService):
def notify(self, member: Member, message: str) -> None:
print(f"EMAIL to {member.email}: {message}")
class SMSNotification(NotificationService):
def notify(self, member: Member, message: str) -> None:
print(f"SMS to {member.member_id}: {message}")
# ─── Book Catalog ───────────────────────────────────────
class BookCatalog:
def __init__(self):
self._books: dict[str, Book] = {}
self._items: dict[str, list[BookItem]] = {}
self._barcode_counter = 0
def add_book(self, book: Book, copies: int) -> None:
self._books[book.isbn] = book
if book.isbn not in self._items:
self._items[book.isbn] = []
for _ in range(copies):
self._barcode_counter += 1
barcode = f"BC-{self._barcode_counter}"
self._items[book.isbn].append(BookItem(barcode, book.isbn))
def search(self, query: str) -> list[Book]:
q = query.lower()
return [
b for b in self._books.values()
if q in b.title.lower() or q in b.author.lower() or q in b.isbn
]
def get_available_copy(self, isbn: str) -> Optional[BookItem]:
items = self._items.get(isbn, [])
return next((i for i in items if i.is_available), None)
def get_book(self, isbn: str) -> Optional[Book]:
return self._books.get(isbn)
# ─── Library (Facade) ──────────────────────────────────
class Library:
def __init__(
self,
fine_strategy: Optional[FineStrategy] = None,
notification_service: Optional[NotificationService] = None,
):
self._catalog = BookCatalog()
self._members: dict[str, Member] = {}
self._active_loans: dict[str, Loan] = {}
self._reservations: dict[str, list[Reservation]] = {}
self._loan_counter = 0
self._res_counter = 0
self._fine_strategy = fine_strategy or FlatFineStrategy()
self._notification = notification_service or EmailNotification()
def add_book(self, book: Book, copies: int) -> None:
self._catalog.add_book(book, copies)
def search_books(self, query: str) -> list[Book]:
return self._catalog.search(query)
def register_member(self, member: Member) -> None:
self._members[member.member_id] = member
def issue_book(self, member_id: str, isbn: str) -> Optional[Loan]:
member = self._members.get(member_id)
if not member or not member.can_borrow:
return None
book_item = self._catalog.get_available_copy(isbn)
if not book_item:
return None
book_item.checkout()
self._loan_counter += 1
loan = Loan(f"LN-{self._loan_counter}", member, book_item)
member.add_loan(loan)
self._active_loans[loan.loan_id] = loan
return loan
def return_book(self, loan_id: str) -> float:
loan = self._active_loans.get(loan_id)
if not loan:
raise ValueError(f"Loan {loan_id} not found")
loan.return_date = datetime.now()
loan.book_item.checkin()
loan.member.remove_loan(loan_id)
del self._active_loans[loan_id]
fine = 0.0
if loan.is_overdue:
fine = loan.calculate_fine(self._fine_strategy)
loan.member.add_fine(fine)
self._process_reservations(loan.book_item.isbn)
return fine
def reserve_book(
self, member_id: str, isbn: str
) -> Optional[Reservation]:
member = self._members.get(member_id)
book = self._catalog.get_book(isbn)
if not member or not book:
return None
if self._catalog.get_available_copy(isbn):
return None
self._res_counter += 1
res = Reservation(f"RES-{self._res_counter}", member, book)
self._reservations.setdefault(isbn, []).append(res)
return res
def _process_reservations(self, isbn: str) -> None:
pending = self._reservations.get(isbn, [])
for res in pending:
if res.status == ReservationStatus.PENDING:
res.mark_ready()
self._notification.notify(
res.member,
f'Your reserved book "{res.book.title}" is now available.',
)
break
def pay_fine(self, member_id: str, amount: float) -> None:
member = self._members.get(member_id)
if not member:
raise ValueError(f"Member {member_id} not found")
member.pay_fine(amount)
Correction (2026-11-10): a READY reservation doesn't reserve the copy
In the first-pass code, returnBook calls checkin(), which makes the copy AVAILABLE, and then marks the first reservation READY. Nothing stops the next issueBook from any member taking that AVAILABLE copy, so the member who was told "your book is ready" can arrive to find it gone. The copy needs a third state (on the hold shelf, tied to the hold), and checkout must give it only to the holder. The complete code does this with ON_HOLD_SHELF and Title.ready.
Correction (2026-11-10): fines aren't deterministic in the first-pass code
The requirements ask for deterministic, auditable fines, but Loan and returnBook call new Date() / datetime.now() directly, and amounts are floating point. Neither can be tested at the "one second late" boundary, and floating-point sums drift. Inject a clock and keep money in integer cents.
7. Concurrency
| Shared state | Invariant | Mechanism |
|---|---|---|
| A title's copies and holds | A copy goes to one borrower or one hold | The Title's lock (synchronized, threading.Lock) |
| A member's loan count | Never above the limit | Compare-and-set loop in Java, a short lock in Python |
| Open loans | One return per loan | remove returns the loan to one caller |
| Fines owed | No lost updates | AtomicLong.addAndGet |
The last copy. Two desks both see C1 available. Under the title lock, "find an AVAILABLE copy" and "mark it ON_LOAN" are one step, so the second desk finds nothing and the member's slot is returned.
The loan limit. A member at two desks borrowing two different books takes two different title locks, so the title lock can't protect the limit. tryTakeSlot is a separate atomic step. The Java demo runs eight threads for one member with a limit of 2, and asserts exactly two loans every time.
Return racing a hold. placeHold refuses when a copy is AVAILABLE. Both run under the same title lock, so either the hold is queued first and the return hands it the copy, or the return shelves the copy first and the hold is refused ("borrow it instead"). Nobody ends up waiting for a book that's on the shelf.
Notify outside the lock. Sending email can take seconds, and holding a title lock that long blocks every desk working on that title. The notifier is called after the lock is released.
TypeScript runs one thread, so checkout is atomic as long as it contains no await. The TypeScript race test runs 16 async desks that each await I/O before calling checkout, and exactly one wins.
See Thread-Safe Class Design and Concurrency Patterns in LLD.
Concurrency Considerations
Critical Section: Book Checkout
Two librarians could simultaneously issue the last copy of a book to two different members.
Solutions:
- Pessimistic lock on BookItem — Lock the specific
BookItemduring checkout. Only one thread can check availability and change status atomically.
class BookItem {
private lock = new Mutex();
async checkout(): Promise<void> {
return this.lock.runExclusive(() => {
if (!this.isAvailable()) throw new Error('Not available');
this.status = BookStatus.CHECKED_OUT;
});
}
}
-
Database-level: Use
SELECT ... FOR UPDATEwhen fetching an available copy, ensuring the row is locked until the transaction commits. -
Optimistic concurrency: Add a version column to
book_items. The UPDATE includesWHERE version = ?. If affected rows = 0, retry.
Correction (2026-11-10): locking one BookItem isn't enough
The pessimistic-lock snippet above locks a single BookItem. But issueBook picks the copy before calling checkout, so two desks can pick the same copy, and the loser gets an exception even if another copy is free. The lock has to cover "choose a copy and take it", which means locking the title. Also, Mutex isn't built into JavaScript (it comes from a package such as async-mutex), and a synchronous method doesn't need one.
8. Extensibility: "the interviewer adds X"
Extension 1: renewals, unless someone is waiting
"Members can renew twice, but not if anyone has a hold on the title, and not once overdue." Where: a new renew method that checks the queue under the same title lock placeHold takes, so a hold can't slip in between the check and the renewal. Unchanged: checkout, return, holds and fines.
from dataclasses import replace
MAX_RENEWALS = 2
class RenewingLibrary(Library):
"""Renewal extends the due date, unless someone is waiting for the title."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._renewals: dict[str, int] = {} # loan id -> times renewed
def renew(self, barcode: str) -> Loan:
with self._loans_lock:
loan = self._open_loans.get(barcode)
if loan is None:
raise LibraryError(f"no open loan for {barcode}")
title = self._titles[loan.copy.isbn]
with title.lock: # same lock place_hold takes
if title.waiting:
raise LibraryError("someone is waiting for this title")
if self._renewals.get(loan.id, 0) >= MAX_RENEWALS:
raise LibraryError("renewal limit reached")
if self._clock() > loan.due:
raise LibraryError("overdue loans can't be renewed")
renewed = replace(loan, due=loan.due + LOAN_PERIOD)
with self._loans_lock:
self._open_loans[barcode] = renewed
self._renewals[loan.id] = self._renewals.get(loan.id, 0) + 1
return renewed
Extension 2: lost copies
"A member reports a book lost. Charge the replacement price and take the copy out of circulation." Where: a reportLost method. It closes the loan without calling passOn, so the lost copy is never handed to a hold. Unchanged: everything else.
/** A lost copy: close the loan, charge a replacement fee, and take the copy out of circulation. */
class LostAwareLibrary extends Library {
constructor(now: () => number, fines: FinePolicy, notify: (h: Hold) => void,
private readonly replacementCents: (isbn: string) => number) {
super(now, fines, notify);
}
reportLost(barcode: string): number {
const loan = this.must(this.openLoans, barcode);
this.openLoans.delete(barcode);
const title = this.titles.get(loan.copy.isbn)!;
title.copies.splice(title.copies.indexOf(loan.copy), 1); // never passed on to a hold
const charge = this.replacementCents(loan.copy.isbn);
loan.member.finesCents += charge;
loan.member.loans--;
return charge;
}
}
Extension 3: a grace period on fines
"The first two days late are free." Where: a decorator around any FinePolicy. Nothing else changes.
/** Decorator: the first graceDays of lateness are free, then the wrapped policy applies to the rest. */
final class GracePeriodFine implements FinePolicy {
private final FinePolicy inner;
private final Duration grace;
GracePeriodFine(FinePolicy inner, int graceDays) { this.inner = inner; this.grace = Duration.ofDays(graceDays); }
public long fineCents(Duration overdue) {
return overdue.compareTo(grace) <= 0 ? 0 : inner.fineCents(overdue.minus(grace));
}
}
Each extension ran against the complete code with its own checks.
Extensions & Follow-ups
| Extension | Design Impact |
|---|---|
| Renewal | Add renewLoan(loanId) that extends dueDate by another 14 days (max 2 renewals) |
| Waitlist priority | Reservation queue with FIFO; add position to Reservation |
| Digital books (e-books) | DigitalBookItem with concurrent lending (no physical limit), download link |
| Search indexing | Replace linear search with inverted index or integrate Elasticsearch |
| Audit trail | Event sourcing: every issue/return/fine/payment is an immutable event |
| Multi-branch | Add Branch class; Library contains multiple branches, each with its own catalog |
| Self-checkout kiosk | Reuse Library.issueBook() via a kiosk controller; add barcode scanner interface |
9. Testing
Use a fake clock and test boundaries: returned exactly on the due instant is not late, one second later is one day, a huge delay hits the cap. Test the holds queue in order: FIFO, a READY copy reserved for its holder, expiry passing to the next, and a newly added copy going to the queue first. For the race, start all threads on a barrier, repeat, and also assert that the losers got their loan slot back. Save the Python code as library.py to run this suite:
import threading
import unittest
from datetime import datetime, timedelta
from library import FakeClock, Library, LibraryError, Member, PerDayFine
class LibraryTest(unittest.TestCase):
def setUp(self):
self.clock = FakeClock(datetime(2026, 11, 10, 10, 0))
self.notified = []
self.lib = Library(self.clock, PerDayFine(25, 1_000), lambda h: self.notified.append(h.member.id))
self.lib.add_copy("978-1", "C1")
for mid in ("ann", "bob", "cat"):
self.lib.add_member(Member(mid, 2))
def test_returned_exactly_on_the_due_instant_is_not_late(self):
self.lib.checkout("ann", "978-1")
self.clock.advance(timedelta(days=14))
self.assertEqual(self.lib.return_copy("C1"), 0)
def test_one_second_late_is_one_day(self):
self.lib.checkout("ann", "978-1")
self.clock.advance(timedelta(days=14, seconds=1))
self.assertEqual(self.lib.return_copy("C1"), 25)
def test_fine_is_capped(self):
self.lib.checkout("ann", "978-1")
self.clock.advance(timedelta(days=400))
self.assertEqual(self.lib.return_copy("C1"), 1_000)
def test_fines_over_the_limit_block_borrowing(self):
self.lib.checkout("ann", "978-1")
self.clock.advance(timedelta(days=400))
self.lib.return_copy("C1")
with self.assertRaises(LibraryError):
self.lib.checkout("ann", "978-1")
def test_cannot_hold_an_available_title(self):
with self.assertRaises(LibraryError):
self.lib.place_hold("bob", "978-1")
def test_ready_copy_is_reserved_for_the_holder(self):
self.lib.checkout("ann", "978-1")
self.lib.place_hold("bob", "978-1")
self.lib.return_copy("C1")
with self.assertRaises(LibraryError):
self.lib.checkout("cat", "978-1")
self.assertEqual(self.lib.checkout("bob", "978-1").copy.barcode, "C1")
def test_new_copy_goes_to_the_queue_first(self):
self.lib.checkout("ann", "978-1")
self.lib.place_hold("bob", "978-1")
self.lib.add_copy("978-1", "C2")
self.assertEqual(self.notified, ["bob"])
def test_last_copy_race_has_one_winner(self):
for _ in range(50):
lib = Library(self.clock, PerDayFine(25, 1_000), lambda h: None)
lib.add_copy("978-9", "LAST")
members = [Member(f"m{i}", 5) for i in range(12)]
for m in members:
lib.add_member(m)
barrier, wins = threading.Barrier(12), []
def desk(mid):
barrier.wait()
try:
wins.append(lib.checkout(mid, "978-9"))
except LibraryError:
pass
threads = [threading.Thread(target=desk, args=(m.id,)) for m in members]
[t.start() for t in threads]
[t.join() for t in threads]
self.assertEqual(len(wins), 1)
self.assertEqual(sum(m.loans for m in members), 1) # losers got their slot back
if __name__ == "__main__":
unittest.main()
Testing Strategy
| Test Type | What to Test |
|---|---|
| Unit | FlatFineStrategy: 0 days = $0, 5 days = $5 |
| Unit | TieredFineStrategy: 3 days = $3, 10 days = $13, 20 days = $51 |
| Unit | Member.canBorrow(): active + under limit + no excessive fines |
| Integration | Issue book → return on time → no fine |
| Integration | Issue book → return late → correct fine applied |
| Integration | Issue 5 books → 6th attempt returns null |
| Integration | Reserve → return by another member → notification sent |
| Edge case | Fine exceeds threshold → member suspended → can't borrow |
| Edge case | Pay fine → drops below threshold → member reactivated |
10. Common mistakes
- A READY hold that doesn't reserve the copy. The member is told to come in and the book is gone.
- Locking the copy instead of the title. The decision spans all copies and the queue.
- Protecting the loan limit with the title lock. Two different books mean two different locks.
- Calling the notifier inside the lock. One slow email blocks a title.
now()insideLoanor the fine policy. The boundaries become untestable.- Forgetting to give the slot back when checkout fails. The member slowly "fills up" with loans that don't exist. The Python race test checks for this.
11. Interview follow-ups
How does the hold expiry run in production?
A scheduled job calls expireHolds() every few minutes. It's idempotent, so running it twice or late is harmless. With many titles, keep READY holds in a priority queue ordered by deadline and pop only the expired ones, instead of scanning every title.
What changes with a database and several servers?
The title lock becomes a row lock (SELECT ... FOR UPDATE on the title row) or an optimistic version column on it. The slot counter becomes UPDATE member SET loans = loans + 1 WHERE id = ? AND loans < max_loans. The one-return rule becomes a conditional update on the loan row. Booking and Inventory Concurrency covers both styles.
Should fines be charged at return, or accrue daily?
At return is simpler and enough for most libraries. If members must be blocked while a very late book is still out, compute the "live" fine on read from the due date and the clock, rather than running a daily job that updates balances.
A member places holds on 50 titles. Is that a problem?
It's a business rule, so ask. If there's a cap, it belongs in placeHold, counted per member, with the same atomic-counter technique as loans.