Library management system
Design a library management system: books versus copies, members, loans, a hold queue, fines as a strategy, search, and notifications with the Observer pattern.
On this page
- The problem: one class called Book that does everything
- 1. Clarify the requirements
- 2. Entities: the book-versus-copy split
- 3. What varies: fines and notifications
- 4. The copy lifecycle
- 5. The code
- 6. Concurrency: two desks, one copy
- 7. Options and trade-offs
- 8. Extensions the interviewer will ask for
- When not to over-design
- In the interview
- Quiz
The problem: one class called Book that does everything
"Design a library management system" sounds like a database exercise, and many candidates treat it as one: a Book class with an isAvailable flag and a borrowedBy field. It works until the library buys a second copy.
class Book {
String isbn, title, author;
boolean available = true;
String borrowedBy; // which member has it
LocalDate due;
Queue<String> waitingList = new LinkedList<>();
}
The problems:
- Title and copy are mixed up. The library owns three copies of The Hobbit. With one
Bookobject per ISBN there is oneavailableflag, so either all three are out or none are. With oneBookobject per copy, the title, author and waiting list are duplicated three times, and a hold on "the next free copy" has nowhere to live. - No loan history. When
borrowedByis overwritten, the record of who had it (and who returned it late) is gone. - Fine rules are hard-coded, and change (children free, a cap per item, a grace day).
- Notifications are welded in. If
returnBook()sends an e-mail itself, adding SMS means editing the lending code.
1. Clarify the requirements
The interviewer says "Design a library management system." Write 5–6 questions and agree a list of requirements.
Compare with our answer
Questions worth asking: Several copies per title? Who are the users: members, librarians, both? Loan period and maximum books per member? Can members reserve (place holds on) a book that is out? How are fines computed, and do unpaid fines block borrowing? What search is needed? How are members notified? One branch or many?
A strong answer mentions: books versus physical copies · loan limits and due dates · a hold queue with a pickup window · fines and what they block · search by title or author · notifications for holds and overdue items · explicit out of scope: payments, several branches, e-books.
The agreed list:
| Requirement | Detail |
|---|---|
| Catalogue | A book (title) has an ISBN, title and author; the library owns one or more copies of it, each with a barcode |
| Members | Have an id and a loan limit (say 2 or 5 books) |
| Checkout | A member borrows a specific copy for 14 days; refused if over the limit or with unpaid fines |
| Return | Ends the loan; a late return adds a fine |
| Holds | A member can queue for a title. When a copy comes back, it is kept for the first person in the queue for 3 days |
| Fines | 0.25 a day late, capped at 10.00 per loan; the rule will change |
| Search | By words in the title or author |
| Notifications | "Your hold is ready", "your hold lapsed", "your book is overdue" by e-mail now, SMS later |
Out of scope: taking card payments, several branches with transfers, e-books, and the librarian user interface.
2. Entities: the book-versus-copy split
Underline the nouns: book, copy, member, loan, hold, fine, catalogue, notification. The key modelling decision is to separate the title from the physical item. Most of the interview's follow-ups depend on it.
Book is the title; BookCopy is the physical item
| Class / type | Kind | Responsibility |
|---|---|---|
Book | value object | ISBN, title, author. One per title |
BookCopy | entity | Barcode, the book it is a copy of, its CopyStatus, and who it is reserved for while on the hold shelf |
CopyStatus | enum | AVAILABLE, ON_LOAN, ON_HOLD_SHELF, LOST |
Member | value object | Id, name, loan limit |
Loan | entity | Copy, member, borrowed date, due date, returned date. Kept as history after the return |
FinePolicy | interface (Strategy) | fineCents(loan, returnedOn) |
LibraryListener | interface (Observer) | onEvent(type, member, message) |
Library | facade | The one entry point: checkout, returnCopy, placeHold, search, dailyRun |
Two relationships are worth saying out loud:
- Loans are on copies, because a member takes a specific item home and must return that barcode.
- Holds are on books (titles), because the member wants any copy of Dune. The hold queue is per ISBN, and the first copy returned goes to the first person waiting.
3. What varies: fines and notifications
FinePolicy is a strategy; listeners are observers
- Fines are a strategy. Today it is 25 cents a day with a cap. Tomorrow children pay nothing and new releases cost 1.00 a day. Each rule is a class;
Libraryasks the policy and never changes. Money is in integer cents, neverdouble. - Notifications use the Observer pattern. The library publishes events (
HOLD_READY,HOLD_EXPIRED,OVERDUE) to a list of listeners. AnEmailNotifiersubscribes today; anSmsNotifieris one more class tomorrow. The lending code never mentions e-mail.
The library publishes events; notifiers subscribe
4. The copy lifecycle
Most bugs in this problem are illegal state changes: lending a copy that is on the hold shelf for someone else, or putting a returned copy back on the open shelf while people are queued for it. Draw the states before writing code.
The states a copy moves through
| From | Event | To |
|---|---|---|
AVAILABLE | checkout | ON_LOAN |
ON_LOAN | return, nobody queued | AVAILABLE |
ON_LOAN | return, queue waiting | ON_HOLD_SHELF, reserved for the first member in the queue who does not already have a copy reserved |
ON_HOLD_SHELF | the reserved member checks out | ON_LOAN |
ON_HOLD_SHELF | pickup window passes | next member in the queue, or AVAILABLE |
ON_LOAN | declared lost | LOST |
A hold placed while a copy is sitting on the open shelf reserves it immediately, so the member is notified at once.
5. The code
The complete model: catalogue with copies, a word index for search, members with loan limits, loans with due dates, a FIFO hold queue per title with a pickup window, a fine strategy, and listeners. Dates are passed in (today) rather than read from the system clock, so the demo can jump forward 19 days in one line.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
enum CopyStatus { AVAILABLE, ON_LOAN, ON_HOLD_SHELF, LOST }
/** The title: one record per ISBN, however many physical copies exist. */
record Book(String isbn, String title, String author) {}
/** A physical copy with a barcode. Loans and holds are about copies. */
final class BookCopy {
final String barcode; final Book book;
CopyStatus status = CopyStatus.AVAILABLE;
String reservedFor; // member id while ON_HOLD_SHELF
LocalDate holdExpires;
BookCopy(String barcode, Book book) { this.barcode = barcode; this.book = book; }
}
record Member(String id, String name, int maxLoans) {}
final class Loan {
final BookCopy copy; final Member member; final LocalDate borrowed, due;
LocalDate returned;
Loan(BookCopy copy, Member member, LocalDate borrowed, LocalDate due) {
this.copy = copy; this.member = member; this.borrowed = borrowed; this.due = due;
}
}
/** Strategy: how much a late return costs, in cents. */
interface FinePolicy { long fineCents(Loan loan, LocalDate returnedOn); }
final class PerDayFine implements FinePolicy {
private final long centsPerDay, capCents;
PerDayFine(long centsPerDay, long capCents) { this.centsPerDay = centsPerDay; this.capCents = capCents; }
public long fineCents(Loan loan, LocalDate on) {
long late = ChronoUnit.DAYS.between(loan.due, on);
return late <= 0 ? 0 : Math.min(capCents, late * centsPerDay);
}
}
/** Observer: the library publishes events; e-mail, SMS or an app subscribe. */
interface LibraryListener { void onEvent(String type, Member member, String message); }
final class EmailNotifier implements LibraryListener {
public void onEvent(String type, Member m, String msg) { System.out.println(" [email to " + m.name() + "] " + type + ": " + msg); }
}
class LibraryException extends RuntimeException { LibraryException(String m) { super(m); } }
final class Library {
static final int LOAN_DAYS = 14, HOLD_PICKUP_DAYS = 3;
private final Map<String, Book> books = new HashMap<>(); // isbn -> title
private final Map<String, BookCopy> copies = new HashMap<>(); // barcode -> copy
private final Map<String, List<BookCopy>> copiesByIsbn = new HashMap<>();
private final Map<String, Set<String>> wordIndex = new HashMap<>(); // search: word -> isbns
private final Map<String, Member> members = new HashMap<>();
private final Map<String, Loan> activeLoans = new HashMap<>(); // barcode -> loan
private final Map<String, Deque<String>> holds = new HashMap<>(); // isbn -> member ids, FIFO
private final Map<String, Long> finesOwed = new HashMap<>();
private final List<LibraryListener> listeners = new ArrayList<>();
private final FinePolicy fines;
Library(FinePolicy fines) { this.fines = fines; }
void subscribe(LibraryListener l) { listeners.add(l); }
private void publish(String type, Member m, String msg) { for (LibraryListener l : listeners) l.onEvent(type, m, msg); }
synchronized void addCopy(Book b, String barcode) {
books.putIfAbsent(b.isbn(), b);
BookCopy c = new BookCopy(barcode, b);
copies.put(barcode, c);
copiesByIsbn.computeIfAbsent(b.isbn(), k -> new ArrayList<>()).add(c);
for (String w : (b.title() + " " + b.author()).toLowerCase().split("\\W+"))
wordIndex.computeIfAbsent(w, k -> new HashSet<>()).add(b.isbn());
}
synchronized void addMember(Member m) { members.put(m.id(), m); }
/** Titles matching every word of the query, with how many copies are on the shelf. */
synchronized List<String> search(String query) {
Set<String> hits = null;
for (String w : query.toLowerCase().split("\\W+")) {
Set<String> s = wordIndex.getOrDefault(w, Set.of());
if (hits == null) hits = new TreeSet<>(s); else hits.retainAll(s);
}
List<String> out = new ArrayList<>();
for (String isbn : hits == null ? Set.<String>of() : hits) {
long free = copiesByIsbn.get(isbn).stream().filter(c -> c.status == CopyStatus.AVAILABLE).count();
out.add(books.get(isbn).title() + " (" + free + " on shelf)");
}
return out;
}
synchronized Loan checkout(String memberId, String barcode, LocalDate today) {
Member m = member(memberId); BookCopy c = copy(barcode);
expireHolds(today);
if (finesOwed.getOrDefault(memberId, 0L) > 0) throw new LibraryException(m.name() + " has unpaid fines");
long onLoan = activeLoans.values().stream().filter(l -> l.member.equals(m)).count();
if (onLoan >= m.maxLoans()) throw new LibraryException(m.name() + " is at the loan limit");
boolean heldForMe = c.status == CopyStatus.ON_HOLD_SHELF && memberId.equals(c.reservedFor);
if (c.status != CopyStatus.AVAILABLE && !heldForMe) throw new LibraryException(barcode + " is " + c.status);
if (heldForMe) holds.get(c.book.isbn()).remove(memberId);
c.status = CopyStatus.ON_LOAN; c.reservedFor = null; c.holdExpires = null;
Loan loan = new Loan(c, m, today, today.plusDays(LOAN_DAYS));
activeLoans.put(barcode, loan);
return loan;
}
/** Returns the fine charged. A waiting hold gets this copy before the shelf does. */
synchronized long returnCopy(String barcode, LocalDate today) {
Loan loan = activeLoans.remove(barcode);
if (loan == null) throw new LibraryException(barcode + " is not on loan");
loan.returned = today;
long fine = fines.fineCents(loan, today);
if (fine > 0) finesOwed.merge(loan.member.id(), fine, Long::sum);
assignToNextHold(loan.copy, today);
return fine;
}
synchronized void placeHold(String memberId, String isbn, LocalDate today) {
Member m = member(memberId);
if (!books.containsKey(isbn)) throw new LibraryException("unknown book " + isbn);
Deque<String> q = holds.computeIfAbsent(isbn, k -> new ArrayDeque<>());
if (q.contains(memberId)) throw new LibraryException(m.name() + " already holds " + isbn);
q.addLast(memberId);
// A copy may be sitting on the shelf right now: reserve it straight away
copiesByIsbn.get(isbn).stream().filter(c -> c.status == CopyStatus.AVAILABLE).findFirst()
.ifPresent(c -> assignToNextHold(c, today));
}
synchronized void payFine(String memberId, long cents) { finesOwed.merge(memberId, -cents, Long::sum); }
/** Daily job: lapse uncollected holds, and warn about overdue loans. */
synchronized void dailyRun(LocalDate today) {
expireHolds(today);
for (Loan l : activeLoans.values())
if (today.isAfter(l.due)) publish("OVERDUE", l.member, l.copy.book.title() + " was due " + l.due);
}
private void assignToNextHold(BookCopy c, LocalDate today) {
Deque<String> q = holds.getOrDefault(c.book.isbn(), new ArrayDeque<>());
String next = q.stream().filter(id -> copiesByIsbn.get(c.book.isbn()).stream()
.noneMatch(o -> id.equals(o.reservedFor))).findFirst().orElse(null); // skip members already given a copy
if (next == null) { c.status = CopyStatus.AVAILABLE; c.reservedFor = null; return; }
c.status = CopyStatus.ON_HOLD_SHELF; c.reservedFor = next; c.holdExpires = today.plusDays(HOLD_PICKUP_DAYS);
publish("HOLD_READY", members.get(next), c.book.title() + " is waiting until " + c.holdExpires);
}
private void expireHolds(LocalDate today) {
for (BookCopy c : copies.values())
if (c.status == CopyStatus.ON_HOLD_SHELF && today.isAfter(c.holdExpires)) {
holds.get(c.book.isbn()).remove(c.reservedFor);
publish("HOLD_EXPIRED", members.get(c.reservedFor), c.book.title());
c.reservedFor = null;
assignToNextHold(c, today);
}
}
private Member member(String id) { Member m = members.get(id); if (m == null) throw new LibraryException("no member " + id); return m; }
private BookCopy copy(String bc) { BookCopy c = copies.get(bc); if (c == null) throw new LibraryException("no copy " + bc); return c; }
synchronized CopyStatus status(String bc) { return copy(bc).status; }
}
public class LibraryDemo {
public static void main(String[] args) {
Library lib = new Library(new PerDayFine(25, 1_000)); // 0.25 a day, capped at 10.00
lib.subscribe(new EmailNotifier());
Book dune = new Book("978-0441013593", "Dune", "Frank Herbert");
Book hobbit = new Book("978-0547928227", "The Hobbit", "J. R. R. Tolkien");
lib.addCopy(dune, "D-1"); lib.addCopy(hobbit, "H-1"); lib.addCopy(hobbit, "H-2");
lib.addMember(new Member("m1", "asha", 2)); lib.addMember(new Member("m2", "ben", 2)); lib.addMember(new Member("m3", "chen", 2));
System.out.println("search 'tolkien hobbit': " + lib.search("tolkien hobbit"));
LocalDate d0 = LocalDate.of(2026, 3, 2);
Loan loan = lib.checkout("m1", "D-1", d0);
System.out.println("asha borrows Dune, due " + loan.due);
try { lib.checkout("m2", "D-1", d0); } catch (LibraryException e) { System.out.println("ben: " + e.getMessage()); }
lib.placeHold("m2", dune.isbn(), d0); // ben, then chen, queue for Dune
lib.placeHold("m3", dune.isbn(), d0);
System.out.println("asha returns 5 days late, fine " + lib.returnCopy("D-1", d0.plusDays(19)) + " cents");
try { lib.checkout("m3", "D-1", d0.plusDays(19)); } catch (LibraryException e) { System.out.println("chen: " + e.getMessage()); }
lib.dailyRun(d0.plusDays(23)); // ben never collects: hold lapses, chen is next
lib.checkout("m3", "D-1", d0.plusDays(24));
System.out.println("chen has D-1: " + lib.status("D-1"));
try { lib.checkout("m1", "H-1", d0.plusDays(24)); } catch (LibraryException e) { System.out.println("asha: " + e.getMessage()); }
lib.payFine("m1", 125);
lib.checkout("m1", "H-1", d0.plusDays(24));
System.out.println("search 'hobbit': " + lib.search("hobbit"));
lib.dailyRun(d0.plusDays(40));
}
}import re
import threading
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass
from datetime import date, timedelta
from enum import Enum
from typing import Optional
class CopyStatus(Enum):
AVAILABLE = "AVAILABLE"
ON_LOAN = "ON_LOAN"
ON_HOLD_SHELF = "ON_HOLD_SHELF"
LOST = "LOST"
@dataclass(frozen=True)
class Book: # the title: one per ISBN
isbn: str
title: str
author: str
@dataclass(eq=False)
class BookCopy: # a physical copy with a barcode
barcode: str
book: Book
status: CopyStatus = CopyStatus.AVAILABLE
reserved_for: Optional[str] = None # member id while ON_HOLD_SHELF
hold_expires: Optional[date] = None
@dataclass(frozen=True)
class Member:
id: str
name: str
max_loans: int
@dataclass(eq=False)
class Loan:
copy: BookCopy
member: Member
borrowed: date
due: date
returned: Optional[date] = None
class FinePolicy(ABC): # Strategy: how much a late return costs, in cents
@abstractmethod
def fine_cents(self, loan: Loan, returned_on: date) -> int: ...
class PerDayFine(FinePolicy):
def __init__(self, cents_per_day: int, cap_cents: int):
self.per_day, self.cap = cents_per_day, cap_cents
def fine_cents(self, loan, returned_on):
late = (returned_on - loan.due).days
return 0 if late <= 0 else min(self.cap, late * self.per_day)
class LibraryListener(ABC): # Observer: e-mail, SMS or an app subscribe
@abstractmethod
def on_event(self, kind: str, member: Member, message: str) -> None: ...
class EmailNotifier(LibraryListener):
def on_event(self, kind, member, message):
print(f" [email to {member.name}] {kind}: {message}")
class LibraryError(Exception):
pass
class Library:
LOAN_DAYS, HOLD_PICKUP_DAYS = 14, 3
def __init__(self, fines: FinePolicy):
self.fines = fines
self._books: dict = {} # isbn -> Book
self._copies: dict = {} # barcode -> BookCopy
self._by_isbn: dict = {} # isbn -> [BookCopy]
self._words: dict = {} # search index: word -> {isbn}
self._members: dict = {}
self._loans: dict = {} # barcode -> active Loan
self._holds: dict = {} # isbn -> deque of member ids (FIFO)
self._fines_owed: dict = {}
self._listeners: list = []
self._lock = threading.Lock() # guards every map below; helpers assume it is held
def subscribe(self, listener: LibraryListener) -> None:
self._listeners.append(listener)
def _publish(self, kind, member, message):
for listener in self._listeners:
listener.on_event(kind, member, message)
def add_copy(self, book: Book, barcode: str) -> None:
with self._lock:
self._books.setdefault(book.isbn, book)
c = BookCopy(barcode, book)
self._copies[barcode] = c
self._by_isbn.setdefault(book.isbn, []).append(c)
for w in re.split(r"\W+", f"{book.title} {book.author}".lower()):
if w:
self._words.setdefault(w, set()).add(book.isbn)
def add_member(self, m: Member) -> None:
with self._lock:
self._members[m.id] = m
def search(self, query: str) -> list:
"""Titles matching every word of the query, with copies on the shelf."""
with self._lock:
hits = None
for w in re.split(r"\W+", query.lower()):
s = self._words.get(w, set())
hits = set(s) if hits is None else hits & s
out = []
for isbn in sorted(hits or ()):
free = sum(c.status is CopyStatus.AVAILABLE for c in self._by_isbn[isbn])
out.append(f"{self._books[isbn].title} ({free} on shelf)")
return out
def checkout(self, member_id: str, barcode: str, today: date) -> Loan:
with self._lock:
m, c = self._member(member_id), self._copy(barcode)
self._expire_holds(today)
if self._fines_owed.get(member_id, 0) > 0:
raise LibraryError(f"{m.name} has unpaid fines")
if sum(l.member == m for l in self._loans.values()) >= m.max_loans:
raise LibraryError(f"{m.name} is at the loan limit")
held_for_me = c.status is CopyStatus.ON_HOLD_SHELF and c.reserved_for == member_id
if c.status is not CopyStatus.AVAILABLE and not held_for_me:
raise LibraryError(f"{barcode} is {c.status.value}")
if held_for_me:
self._holds[c.book.isbn].remove(member_id)
c.status, c.reserved_for, c.hold_expires = CopyStatus.ON_LOAN, None, None
loan = Loan(c, m, today, today + timedelta(days=self.LOAN_DAYS))
self._loans[barcode] = loan
return loan
def return_copy(self, barcode: str, today: date) -> int:
"""Returns the fine charged. A waiting hold gets this copy before the shelf does."""
with self._lock:
loan = self._loans.pop(barcode, None)
if loan is None:
raise LibraryError(f"{barcode} is not on loan")
loan.returned = today
fine = self.fines.fine_cents(loan, today)
if fine:
self._fines_owed[loan.member.id] = self._fines_owed.get(loan.member.id, 0) + fine
self._assign_to_next_hold(loan.copy, today)
return fine
def place_hold(self, member_id: str, isbn: str, today: date) -> None:
with self._lock:
m = self._member(member_id)
if isbn not in self._books:
raise LibraryError(f"unknown book {isbn}")
q = self._holds.setdefault(isbn, deque())
if member_id in q:
raise LibraryError(f"{m.name} already holds {isbn}")
q.append(member_id)
for c in self._by_isbn[isbn]: # a copy on the shelf now? reserve it
if c.status is CopyStatus.AVAILABLE:
self._assign_to_next_hold(c, today)
break
def pay_fine(self, member_id: str, cents: int) -> None:
with self._lock:
self._fines_owed[member_id] = self._fines_owed.get(member_id, 0) - cents
def daily_run(self, today: date) -> None:
"""Daily job: lapse uncollected holds, and warn about overdue loans."""
with self._lock:
self._expire_holds(today)
for l in self._loans.values():
if today > l.due:
self._publish("OVERDUE", l.member, f"{l.copy.book.title} was due {l.due}")
def _assign_to_next_hold(self, c: BookCopy, today: date) -> None:
reserved = {o.reserved_for for o in self._by_isbn[c.book.isbn]}
nxt = next((mid for mid in self._holds.get(c.book.isbn, ()) if mid not in reserved), None)
if nxt is None: # skip members already given a copy
c.status, c.reserved_for = CopyStatus.AVAILABLE, None
return
c.status, c.reserved_for = CopyStatus.ON_HOLD_SHELF, nxt
c.hold_expires = today + timedelta(days=self.HOLD_PICKUP_DAYS)
self._publish("HOLD_READY", self._members[nxt], f"{c.book.title} is waiting until {c.hold_expires}")
def _expire_holds(self, today: date) -> None:
for c in self._copies.values():
if c.status is CopyStatus.ON_HOLD_SHELF and today > c.hold_expires:
self._holds[c.book.isbn].remove(c.reserved_for)
self._publish("HOLD_EXPIRED", self._members[c.reserved_for], c.book.title)
c.reserved_for = None
self._assign_to_next_hold(c, today)
def _member(self, mid):
if mid not in self._members:
raise LibraryError(f"no member {mid}")
return self._members[mid]
def _copy(self, bc):
if bc not in self._copies:
raise LibraryError(f"no copy {bc}")
return self._copies[bc]
def status(self, bc: str) -> CopyStatus:
with self._lock:
return self._copy(bc).status
if __name__ == "__main__":
lib = Library(PerDayFine(25, 1_000)) # 0.25 a day, capped at 10.00
lib.subscribe(EmailNotifier())
dune = Book("978-0441013593", "Dune", "Frank Herbert")
hobbit = Book("978-0547928227", "The Hobbit", "J. R. R. Tolkien")
lib.add_copy(dune, "D-1"); lib.add_copy(hobbit, "H-1"); lib.add_copy(hobbit, "H-2")
for mid, name in (("m1", "asha"), ("m2", "ben"), ("m3", "chen")):
lib.add_member(Member(mid, name, 2))
print("search 'tolkien hobbit':", lib.search("tolkien hobbit"))
d0 = date(2026, 3, 2)
loan = lib.checkout("m1", "D-1", d0)
print("asha borrows Dune, due", loan.due)
try:
lib.checkout("m2", "D-1", d0)
except LibraryError as e:
print("ben:", e)
lib.place_hold("m2", dune.isbn, d0) # ben, then chen, queue for Dune
lib.place_hold("m3", dune.isbn, d0)
fine = lib.return_copy("D-1", d0 + timedelta(days=19))
print(f"asha returns 5 days late, fine {fine} cents")
try:
lib.checkout("m3", "D-1", d0 + timedelta(days=19))
except LibraryError as e:
print("chen:", e)
lib.daily_run(d0 + timedelta(days=23)) # ben never collects: chen is next
lib.checkout("m3", "D-1", d0 + timedelta(days=24))
print("chen has D-1:", lib.status("D-1").value)
try:
lib.checkout("m1", "H-1", d0 + timedelta(days=24))
except LibraryError as e:
print("asha:", e)
lib.pay_fine("m1", 125)
lib.checkout("m1", "H-1", d0 + timedelta(days=24))
print("search 'hobbit':", lib.search("hobbit"))
lib.daily_run(d0 + timedelta(days=40))Running the Java version prints (Python prints the search results with quotes, ['The Hobbit (2 on shelf)']):
search 'tolkien hobbit': [The Hobbit (2 on shelf)]
asha borrows Dune, due 2026-03-16
ben: D-1 is ON_LOAN
[email to ben] HOLD_READY: Dune is waiting until 2026-03-24
asha returns 5 days late, fine 125 cents
chen: D-1 is ON_HOLD_SHELF
[email to ben] HOLD_EXPIRED: Dune
[email to chen] HOLD_READY: Dune is waiting until 2026-03-28
chen has D-1: ON_LOAN
asha: asha has unpaid fines
search 'hobbit': [The Hobbit (1 on shelf)]
[email to chen] OVERDUE: Dune was due 2026-04-09
[email to asha] OVERDUE: The Hobbit was due 2026-04-09
Follow the story: asha's return goes straight to ben's hold, so chen (second in the queue) is refused. Ben never collects, the daily run lapses his hold, and the copy passes to chen. Asha's 125-cent fine blocks her next checkout until she pays.
6. Concurrency: two desks, one copy
Several desks and a self-service kiosk work at the same time.
| Race | What goes wrong | Fix in the code |
|---|---|---|
| Two desks scan the same copy | Both see AVAILABLE, both create a loan | checkout checks the status and changes it under one lock (check-then-act as one step) |
| Return and checkout of a held copy | The copy is lent from the open shelf just as it should go to the hold queue | returnCopy assigns the copy to the next hold in the same critical section |
| Two holds and one return | Both waiting members are told the copy is theirs | The queue is read and the copy reserved inside the lock; a member already given a copy is skipped |
| Loan limit | A member at the limit borrows at two desks at once and ends up over it | The count and the new loan happen under the same lock |
The Java version uses synchronized methods on Library; Python uses one threading.Lock. A library has a few desks, so one lock is plenty.
7. Options and trade-offs
| Decision | Option | Good at | Weak at |
|---|---|---|---|
| Hold queue | FIFO per title (used here) | Fair and simple | A member far down the queue waits even if another branch has a copy |
| Priority (staff, accessibility needs) | Honours policy | Needs a clear rule, or it feels unfair | |
| Overdue checks | Daily batch job (used here) | Cheap, one place | Up to a day late |
| A timer per loan | Exact | Thousands of timers; lost on restart unless stored | |
| Fines | Computed on return (used here) | Simple, final amount | Members cannot see a running fine until they return |
| Accrued daily | Visible balance | More writes; must stop at the cap |
8. Extensions the interviewer will ask for
- Several branches: a copy gets a
branchfield; a hold may be filled by any branch, with a transfer state (IN_TRANSIT) betweenON_LOANandON_HOLD_SHELF. - Renewals: extend
dueby 14 days if nobody is queued for the title; at most 2 renewals. - Different loan periods (7 days for new releases): a
LoanPolicystrategy besideFinePolicy, chosen by book category or member type. - Lost copies: mark
LOST, charge the replacement price, and remove the copy from the counts. - Librarian versus member permissions: an authorisation check in the facade (only librarians add copies or waive fines).
When not to over-design
- A small club library with one copy per title and an honour system:
Bookwith a borrower field is enough. - No holds: drop the queue and the
ON_HOLD_SHELFstate, and returns go straight to the shelf. - One notification channel forever: a direct call is fine; introduce listeners when a second channel appears.
In the interview
A candidate's return method passes the basic test but breaks the hold queue. Find the bugs and fix them.
synchronized long returnCopy(String barcode, LocalDate today) {
Loan loan = activeLoans.remove(barcode);
loan.copy.status = CopyStatus.AVAILABLE;
Deque<String> q = holds.get(loan.copy.book.isbn());
if (!q.isEmpty()) publish("HOLD_READY", members.get(q.peek()), "your book is in");
return fines.fineCents(loan, today);
}Compare with our answer
The bugs: (1) the copy is set to AVAILABLE and only a message is sent, so anyone at the desk can borrow it before the person who was told it's theirs arrives. (2) No pickup deadline, so a member who never comes keeps the queue blocked. (3) The fine is computed but never recorded against the member. (4) A null loan (an unknown barcode) or a null queue (nobody ever held this title) throws a NullPointerException.
synchronized long returnCopy(String barcode, LocalDate today) {
Loan loan = activeLoans.remove(barcode);
if (loan == null) throw new LibraryException(barcode + " is not on loan");
loan.returned = today;
long fine = fines.fineCents(loan, today);
if (fine > 0) finesOwed.merge(loan.member.id(), fine, Long::sum);
Deque<String> q = holds.getOrDefault(loan.copy.book.isbn(), new ArrayDeque<>());
BookCopy c = loan.copy;
if (q.isEmpty()) { c.status = CopyStatus.AVAILABLE; return fine; }
c.status = CopyStatus.ON_HOLD_SHELF; // reserved: not lendable to others
c.reservedFor = q.peek();
c.holdExpires = today.plusDays(HOLD_PICKUP_DAYS);
publish("HOLD_READY", members.get(c.reservedFor), c.book.title() + " until " + c.holdExpires);
return fine;
}def return_copy(self, barcode, today):
with self._lock:
loan = self._loans.pop(barcode, None)
if loan is None:
raise LibraryError(f"{barcode} is not on loan")
loan.returned = today
fine = self.fines.fine_cents(loan, today)
if fine:
self._fines_owed[loan.member.id] = self._fines_owed.get(loan.member.id, 0) + fine
q, c = self._holds.get(loan.copy.book.isbn, deque()), loan.copy
if not q:
c.status = CopyStatus.AVAILABLE
return fine
c.status = CopyStatus.ON_HOLD_SHELF # reserved: not lendable to others
c.reserved_for = q[0]
c.hold_expires = today + timedelta(days=self.HOLD_PICKUP_DAYS)
self._publish("HOLD_READY", self._members[c.reserved_for],
f"{c.book.title} until {c.hold_expires}")
return fineA strong answer mentions: reserving the copy (a hold-shelf state) rather than only notifying · a pickup deadline and what happens after it · recording the fine · handling an unknown barcode and an empty queue · doing it all under the same lock as checkout.
The library adds a children's membership: no fines at all, and new releases may be borrowed for only 7 days by everyone. What changes, and what stays the same?
Compare with our answer
A strong answer mentions:
Membergets a type (ADULT,CHILD) andBookgets a category (NEW_RELEASE,STANDARD); both are data, not subclasses.- A new fine strategy, or a small composite:
NoFineForChildren(inner)returns 0 for child members and otherwise delegates to the existing per-day rule. - A
LoanPolicystrategy (loanDays(member, book)) replaces theLOAN_DAYSconstant incheckout. Library, the hold queue, the copy states and the listeners do not change.- Existing loans keep the due date they were given; policies apply at checkout time, which is worth confirming with the interviewer.
- Book vs copy:
Book= title (ISBN),BookCopy= physical item (barcode, status). Loans on copies, holds on titles. - States:
AVAILABLE→ON_LOAN→ (AVAILABLE|ON_HOLD_SHELFif queued) ; hold shelf →ON_LOANby the reserved member, or lapses to the next in the queue;LOST. - Checkout rules: member under the loan limit, no unpaid fines, copy available or reserved for this member.
- Holds: FIFO queue per ISBN; a returned copy is reserved for the first waiting member with a 3-day pickup window.
- Fines:
FinePolicystrategy in integer cents, with a cap; computed on return. - Notifications: Observer;
HOLD_READY,HOLD_EXPIRED,OVERDUE; publish after the lock or via a queue/outbox. - Search: word index with set intersection; full-text index in production.
- Concurrency: one lock in memory;
UPDATE … WHERE status = 'AVAILABLE'and a unique active loan per copy in the database. - Time passed in (
today) for testable due dates, fines and hold expiry.
1. A library owns three copies of The Hobbit. A candidate models one Book object per ISBN with an available flag. What breaks first?
One object per title has one flag for all its copies. The other answers describe a model with one object per copy, which has the opposite problem: the title data and hold queue are duplicated.
2. Ben is first in the hold queue for Dune. Asha returns the only copy. What should the system do?
Reserving the copy guarantees ben gets it; the deadline stops the queue stalling if he never comes. Open-shelf plus e-mail is a race, and starting a loan he never collected would charge him fines for a book he does not have.
3. Why are holds placed on the Book (title) rather than on a BookCopy?
With three copies on loan, the first one returned should serve the first person waiting. A hold on one specific copy would make the member wait for that item even if another copy is returned sooner.
4. Children must not pay fines. Which change touches the least existing code?
A strategy wrapping the existing one keeps the rule in one new class. The branch in returnCopy mixes pricing into the facade; the subclass and the extra map spread one rule over several places and still compute fines.
5. Two self-service kiosks scan the same copy at the same moment. Each runs if (copy.status == AVAILABLE) { copy.status = ON_LOAN; createLoan(); }. What is the problem and the fix?
Both kiosks can read AVAILABLE and both create loans. volatile makes the write visible but does not stop both reads happening first. A lock around the check and update, or a conditional UPDATE … WHERE status = 'AVAILABLE', lets only one win.
6. returnCopy sends the "hold ready" e-mail directly while holding the library lock. On a busy afternoon, what goes wrong?
A slow network call inside a critical section blocks everyone waiting for that lock. Collect events inside the lock and publish them afterwards, or put them on a queue. The first option describes a real problem with databases, solved by an outbox, but not this one.
7. The fine rule is 25 cents a day, capped at 10.00 per loan. A book due on 1 March is returned on 15 April. What is the fine?
March 1 to April 15 is 45 days, which is 1,125 cents before the cap; min(1000, 1125) is 1,000 cents. A lost-item rule could exist, but it is not part of this policy.
Score 60% or more and the lesson is marked complete.