More interview problems · Chapter 29

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.

IntermediateInterview priority: Medium50 min
On this page
  1. The problem: one class called Book that does everything
  2. 1. Clarify the requirements
  3. 2. Entities: the book-versus-copy split
  4. 3. What varies: fines and notifications
  5. 4. The copy lifecycle
  6. 5. The code
  7. 6. Concurrency: two desks, one copy
  8. 7. Options and trade-offs
  9. 8. Extensions the interviewer will ask for
  10. When not to over-design
  11. In the interview
  12. 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 Book object per ISBN there is one available flag, so either all three are out or none are. With one Book object 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 borrowedBy is 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

Your turn: scope it

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:

RequirementDetail
CatalogueA book (title) has an ISBN, title and author; the library owns one or more copies of it, each with a barcode
MembersHave an id and a loan limit (say 2 or 5 books)
CheckoutA member borrows a specific copy for 14 days; refused if over the limit or with unpaid fines
ReturnEnds the loan; a late return adds a fine
HoldsA member can queue for a title. When a copy comes back, it is kept for the first person in the queue for 3 days
Fines0.25 a day late, capped at 10.00 per loan; the rule will change
SearchBy 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 / typeKindResponsibility
Bookvalue objectISBN, title, author. One per title
BookCopyentityBarcode, the book it is a copy of, its CopyStatus, and who it is reserved for while on the hold shelf
CopyStatusenumAVAILABLE, ON_LOAN, ON_HOLD_SHELF, LOST
Membervalue objectId, name, loan limit
LoanentityCopy, member, borrowed date, due date, returned date. Kept as history after the return
FinePolicyinterface (Strategy)fineCents(loan, returnedOn)
LibraryListenerinterface (Observer)onEvent(type, member, message)
LibraryfacadeThe 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; Library asks the policy and never changes. Money is in integer cents, never double.
  • Notifications use the Observer pattern. The library publishes events (HOLD_READY, HOLD_EXPIRED, OVERDUE) to a list of listeners. An EmailNotifier subscribes today; an SmsNotifier is 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

FromEventTo
AVAILABLEcheckoutON_LOAN
ON_LOANreturn, nobody queuedAVAILABLE
ON_LOANreturn, queue waitingON_HOLD_SHELF, reserved for the first member in the queue who does not already have a copy reserved
ON_HOLD_SHELFthe reserved member checks outON_LOAN
ON_HOLD_SHELFpickup window passesnext member in the queue, or AVAILABLE
ON_LOANdeclared lostLOST

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));
    }
}

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.

RaceWhat goes wrongFix in the code
Two desks scan the same copyBoth see AVAILABLE, both create a loancheckout checks the status and changes it under one lock (check-then-act as one step)
Return and checkout of a held copyThe copy is lent from the open shelf just as it should go to the hold queuereturnCopy assigns the copy to the next hold in the same critical section
Two holds and one returnBoth waiting members are told the copy is theirsThe queue is read and the copy reserved inside the lock; a member already given a copy is skipped
Loan limitA member at the limit borrows at two desks at once and ends up over itThe 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

DecisionOptionGood atWeak at
Hold queueFIFO per title (used here)Fair and simpleA member far down the queue waits even if another branch has a copy
Priority (staff, accessibility needs)Honours policyNeeds a clear rule, or it feels unfair
Overdue checksDaily batch job (used here)Cheap, one placeUp to a day late
A timer per loanExactThousands of timers; lost on restart unless stored
FinesComputed on return (used here)Simple, final amountMembers cannot see a running fine until they return
Accrued dailyVisible balanceMore writes; must stop at the cap

8. Extensions the interviewer will ask for

  • Several branches: a copy gets a branch field; a hold may be filled by any branch, with a transfer state (IN_TRANSIT) between ON_LOAN and ON_HOLD_SHELF.
  • Renewals: extend due by 14 days if nobody is queued for the title; at most 2 renewals.
  • Different loan periods (7 days for new releases): a LoanPolicy strategy beside FinePolicy, 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: Book with a borrower field is enough.
  • No holds: drop the queue and the ON_HOLD_SHELF state, 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

Your turn: spot the bug

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;
}

A 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.

Your turn: the requirement changes

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:

  • Member gets a type (ADULT, CHILD) and Book gets 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 LoanPolicy strategy (loanDays(member, book)) replaces the LOAN_DAYS constant in checkout.
  • 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.
Library management on one page
  • Book vs copy: Book = title (ISBN), BookCopy = physical item (barcode, status). Loans on copies, holds on titles.
  • States: AVAILABLE → ON_LOAN → (AVAILABLE | ON_HOLD_SHELF if queued) ; hold shelf → ON_LOAN by 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: FinePolicy strategy 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.
Check what stuck

1. A library owns three copies of The Hobbit. A candidate models one Book object per ISBN with an available flag. What breaks first?

2. Ben is first in the hold queue for Dune. Asha returns the only copy. What should the system do?

3. Why are holds placed on the Book (title) rather than on a BookCopy?

4. Children must not pay fines. Which change touches the least existing code?

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?

6. returnCopy sends the "hold ready" e-mail directly while holding the library lock. On a busy afternoon, what goes wrong?

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?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.