LOW LEVEL DESIGN · MACHINE CODING · EASY · 15 OF 42

Design a Library Management System: LLD in Java

A library system designed and coded: books versus physical copies, members with plans and limits, borrow, return and a FIFO hold queue per title, fines as a Strategy, keyword search with an inverted index, Observer notifications, lock ordering so borrowing never deadlocks, a race for the last copies, and the follow-ups, with a full Java 17 solution.

Patterns usedObserverStrategy

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 19

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 283 lines, with a small main() demo. Save it as LibraryManagement.java, then run javac LibraryManagement.java && java LibraryManagement.

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/** A library: titles and copies, members with plans, loans, a hold queue per title, fines, search. */
public class LibraryManagement {

    // ---------- the model ----------
    /** The catalogue entry. Many physical copies share one Book. */
    record Book(String isbn, String title, String author, int year) {}

    enum CopyStatus { AVAILABLE, BORROWED, ON_HOLD, LOST }

    static final class Copy {
        final String barcode;
        final Book book;
        CopyStatus status = CopyStatus.AVAILABLE; // guarded by the Title lock
        Member heldFor;

        Copy(String barcode, Book book) {
            this.barcode = barcode;
            this.book = book;
        }
    }

    /** Membership rules live in data, not in if statements: a new plan is a new constant. */
    enum Plan {
        STUDENT(2, 14), FACULTY(10, 60);

        final int maxLoans;
        final int loanDays;

        Plan(int maxLoans, int loanDays) {
            this.maxLoans = maxLoans;
            this.loanDays = loanDays;
        }
    }

    static final class Member {
        final String id;
        final String name;
        final Plan plan;
        int activeLoans;   // guarded by this member's lock
        long unpaidFines;  // guarded by this member's lock

        Member(String id, String name, Plan plan) {
            this.id = id;
            this.name = name;
            this.plan = plan;
        }
    }

    record Loan(String id, Copy copy, Member member, Instant borrowed, Instant due) {}

    record ReturnResult(String barcode, long lateDays, long fineCents, String nextHolder) {}

    /** Everything about one title, behind one lock: its copies and its FIFO hold queue. */
    static final class Title {
        final Book book;
        final List<Copy> copies = new ArrayList<>();
        final Deque<Member> holds = new ArrayDeque<>();

        Title(Book book) { this.book = book; }

        long available() { return copies.stream().filter(c -> c.status == CopyStatus.AVAILABLE).count(); }
    }

    // ---------- strategies and observers ----------
    interface FinePolicy { long fine(long lateDays); }

    /** A fixed amount per late day, capped. */
    record PerDayFine(long centsPerDay, long capCents) implements FinePolicy {
        public long fine(long lateDays) { return Math.min(lateDays * centsPerDay, capCents); }
    }

    interface LibraryListener { void onHoldReady(Member m, Copy c); }

    // ---------- the library ----------
    private final Map<String, Title> titles = new ConcurrentHashMap<>();
    private final Map<String, Set<String>> wordIndex = new ConcurrentHashMap<>(); // word -> isbns
    private final Map<String, Loan> loansByBarcode = new ConcurrentHashMap<>();
    private final List<LibraryListener> listeners = new CopyOnWriteArrayList<>();
    private final AtomicLong seq = new AtomicLong();
    private final FinePolicy fines;
    private final Supplier<Instant> clock;

    LibraryManagement(FinePolicy fines, Supplier<Instant> clock) {
        this.fines = fines;
        this.clock = clock;
    }

    void subscribe(LibraryListener l) { listeners.add(l); }

    void addCopy(Book b, String barcode) {
        Title t = titles.computeIfAbsent(b.isbn(), k -> new Title(b));
        synchronized (t) {
            t.copies.add(new Copy(barcode, b));
        }
        for (String w : (b.title() + " " + b.author()).toLowerCase(Locale.ROOT).split("\\W+"))
            wordIndex.computeIfAbsent(w, k -> ConcurrentHashMap.newKeySet()).add(b.isbn());
    }

    /** Search: every word must match (title or author); results show how many copies are on the shelf. */
    List<String> search(String query) {
        Set<String> hits = null;
        for (String w : query.toLowerCase(Locale.ROOT).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) {
            Title t = titles.get(isbn);
            synchronized (t) {
                out.add(t.book.title() + " (" + t.available() + "/" + t.copies.size() + " on shelf)");
            }
        }
        return out;
    }

    /** Borrow: member lock, then title lock, always in that order, so two locks never deadlock. */
    Loan borrow(Member m, String isbn) {
        Title t = titles.get(isbn);
        synchronized (m) {
            if (m.unpaidFines > 0) throw new IllegalStateException(m.name + " has unpaid fines");
            if (m.activeLoans >= m.plan.maxLoans)
                throw new IllegalStateException(m.name + " reached the limit of " + m.plan.maxLoans);
            synchronized (t) {
                Copy c = pickCopy(t, m);
                c.status = CopyStatus.BORROWED;
                c.heldFor = null;
                m.activeLoans++;
                Instant now = clock.get();
                Loan loan = new Loan("L" + seq.incrementAndGet(), c, m, now,
                        now.plus(Duration.ofDays(m.plan.loanDays)));
                loansByBarcode.put(c.barcode, loan);
                return loan;
            }
        }
    }

    /** A copy on hold for this member wins; otherwise any shelf copy, unless others are queued ahead. */
    private Copy pickCopy(Title t, Member m) {
        for (Copy c : t.copies) if (c.status == CopyStatus.ON_HOLD && c.heldFor == m) return c;
        if (!t.holds.isEmpty() && !t.holds.contains(m))
            throw new IllegalStateException("others are waiting for " + t.book.title());
        for (Copy c : t.copies) if (c.status == CopyStatus.AVAILABLE) return c;
        throw new IllegalStateException("no copy of " + t.book.title() + " for " + m.name);
    }

    /** Reserve: join the FIFO queue only when nothing is on the shelf. */
    int reserve(Member m, String isbn) {
        Title t = titles.get(isbn);
        synchronized (t) {
            if (t.available() > 0) throw new IllegalStateException("a copy is on the shelf, just borrow it");
            if (!t.holds.contains(m)) t.holds.addLast(m);
            return t.holds.size();
        }
    }

    /** Return: work out the fine, then hand the copy to the next person in the queue or back to the shelf. */
    ReturnResult giveBack(String barcode) {
        Loan loan = loansByBarcode.remove(barcode);
        if (loan == null) throw new IllegalArgumentException("no active loan for " + barcode);
        Member m = loan.member();
        Title t = titles.get(loan.copy().book.isbn());
        long late = Math.max(0, Duration.between(loan.due(), clock.get()).toDays());
        long fine = fines.fine(late);
        Member next;
        synchronized (m) {
            m.activeLoans--;
            m.unpaidFines += fine;
            synchronized (t) {
                next = t.holds.pollFirst();
                loan.copy().status = next == null ? CopyStatus.AVAILABLE : CopyStatus.ON_HOLD;
                loan.copy().heldFor = next;
            }
        }
        if (next != null) for (LibraryListener l : listeners) l.onHoldReady(next, loan.copy());
        return new ReturnResult(barcode, late, fine, next == null ? "shelf" : next.name);
    }

    void payFine(Member m, long cents) {
        synchronized (m) {
            m.unpaidFines = Math.max(0, m.unpaidFines - cents);
        }
    }

    // ---------- demo ----------
    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    static void expectFail(Runnable r, String what) {
        try {
            r.run();
            throw new AssertionError("should have failed: " + what);
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Instant> now = new AtomicReference<>(Instant.parse("2026-03-01T10:00:00Z"));
        LibraryManagement lib = new LibraryManagement(new PerDayFine(1000, 20000), now::get);
        lib.subscribe((m, c) -> System.out.println("  [notify " + m.name + "] " + c.book.title()
                + " is held for you at the desk"));
        Book design = new Book("111", "Designing Data Systems", "Author One", 2020);
        Book algo = new Book("222", "Algorithms in Practice", "Author Two", 2019);
        Book sys = new Book("333", "Systems Design Primer", "Author One", 2022);
        lib.addCopy(design, "D-1");
        lib.addCopy(design, "D-2");
        for (int i = 1; i <= 3; i++) lib.addCopy(algo, "A-" + i);
        lib.addCopy(sys, "S-1");
        System.out.println("Search 'systems': " + lib.search("systems"));
        System.out.println("Search 'author two': " + lib.search("author two"));
        check(lib.search("systems").size() == 2 && lib.search("primer systems").size() == 1, "search");

        Member reader = new Member("M1", "Student", Plan.STUDENT);
        Member second = new Member("M2", "Second student", Plan.STUDENT);
        Member prof = new Member("M3", "Faculty", Plan.FACULTY);
        Loan l1 = lib.borrow(reader, "111");
        lib.borrow(second, "111");
        expectFail(() -> lib.borrow(prof, "111"), "both copies are out");
        System.out.println("Faculty joins the queue at position " + lib.reserve(prof, "111"));

        now.set(now.get().plus(Duration.ofDays(17))); // due after 14 days: 3 days late
        ReturnResult r = lib.giveBack(l1.copy().barcode);
        System.out.printf("Returned %s: %d days late, fine %.2f, copy goes to %s%n",
                r.barcode(), r.lateDays(), r.fineCents() / 100.0, r.nextHolder());
        check(r.fineCents() == 3000 && r.nextHolder().equals("Faculty"), "fine and hold");
        expectFail(() -> lib.borrow(reader, "222"), "unpaid fine");
        lib.payFine(reader, 3000);
        Loan held = lib.borrow(prof, "111");
        System.out.println("Faculty borrows the held copy " + held.copy().barcode + ", due " + held.due());
        check(held.copy().barcode.equals("D-1"), "the held copy goes to the queue head");

        lib.borrow(reader, "222");
        lib.borrow(reader, "333");
        expectFail(() -> lib.borrow(reader, "222"), "student limit");

        // Eight members race for the last two copies of one title: exactly two loans.
        AtomicInteger got = new AtomicInteger(), missed = new AtomicInteger();
        CountDownLatch go = new CountDownLatch(1);
        ExecutorService pool = Executors.newFixedThreadPool(8);
        for (int i = 0; i < 8; i++) {
            Member m = new Member("R" + i, "Racer" + i, Plan.STUDENT);
            pool.submit(() -> {
                try {
                    go.await();
                    lib.borrow(m, "222");
                    got.incrementAndGet();
                } catch (IllegalStateException e) {
                    missed.incrementAndGet();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        go.countDown();
        pool.shutdown();
        check(pool.awaitTermination(5, TimeUnit.SECONDS), "pool did not finish");
        System.out.println("Race for 2 copies: " + got.get() + " borrowed, " + missed.get() + " missed");
        check(got.get() == 2, "a copy was lent twice");
    }
}

Notes

Requirements

The requirements. The catalogue holds books, and each book has several physical copies. Members search by words in the title or author. Members are students or faculty, each plan with its own loan limit and loan period. Members borrow and return copies, reserve a book when every copy is out, pay a fine per late day up to a cap, and cannot borrow while they owe money. They are notified when a reserved copy is ready.

Clarify holds and fines, because they carry the edge cases. A member reserves a title, not a specific copy. The queue is first come, first served. When a copy comes back and someone is waiting, it goes on hold for the first person in line, and nobody else can take it. Fines are per late day with a cap per loan, so one forgotten book does not become a fortune.

Requirements
  • catalogue of books, many copies
  • search by title or author words
  • members: student or faculty
  • with a loan limit and period
  • borrow and return copies
  • reserve when no copy is free
  • fine per late day, capped
  • no borrowing with unpaid fines
  • notify when a hold is ready
  • out of scope: e-books, payments
Clarify first
  • reserve a title or a copy?
  • a title, any copy will do
  • hold queue order?
  • first come, first served
  • returned copy with a queue?
  • held for the first in line
  • can others take a held copy?
  • no
  • fine cap?
  • yes, 200.00 per loan

Entities

The entities, and the one distinction that matters. A book is the catalogue entry: ISBN, title, author, year. A copy is a physical item with a barcode and a status. Three copies of one book share one book record. Group everything about one book, its copies and its waiting list, into a title. A loan ties one copy to one member with a due date. Mixing up book and copy is the most common modelling mistake here.

Class diagram

In code, a book and a loan are records, because they never change. A copy has a status, available, borrowed, on hold or lost, and who it is held for. A member has a plan, a count of active loans and unpaid fines. A title holds the book, its copies and a first in, first out queue of members waiting. Money is a long count of paise.

Types
record Book(isbn, title, author, year)
enum CopyStatus { AVAILABLE, BORROWED,
                  ON_HOLD, LOST }
class Copy { barcode, book, status,
             heldFor }
class Member { id, name, plan,
  activeLoans, unpaidFines }
record Loan(id, copy, member,
            borrowed, due)
class Title { book, copies, holds }

Plans as data

Membership rules are data. Each plan is an enum constant carrying its loan limit and loan period: students may hold two books for fourteen days, faculty ten for sixty. The borrow code reads the member's plan instead of asking if this is a student. Adding a staff or guest plan is one new line, and nothing else changes. Interviewers like seeing rules moved out of conditionals.

Plan
enum Plan {
  STUDENT(2, 14), FACULTY(10, 60);
  final int maxLoans;
  final int loanDays;
}

borrow: activeLoans >= maxLoans? no
due = now + plan.loanDays
new plan (staff, guest): one line

Search

Search uses an inverted index. When a copy is added, every word of its title and author maps to its ISBN. A query looks up each word and intersects the sets, so all words must match. Results show how many copies are on the shelf right now. Systems finds two books; author two finds one. For prefix or fuzzy search, use a trie, or in production a search engine, but the idea is the same.

search(query)
on addCopy: for each word in
  title + author: index[word].add(isbn)

search: hits = index[word1]
  retainAll(index[word2]) ...
show title + copies on the shelf

"systems": Designing Data Systems
  (2/2), Systems Design Primer (1/1)
prefix search: a trie or sorted map

Flow: borrow

Borrowing. Lock the member and check the rules: no unpaid fines, and under the plan's limit. Then lock the title and pick a copy: one already on hold for this member wins, otherwise any copy on the shelf, unless other people are queued ahead. Mark the copy borrowed, count the loan, and create the loan with a due date from the plan and an injected clock.

borrow(member, isbn)
synchronized (member) {
  if unpaidFines > 0: throw
  if activeLoans >= plan.max: throw
  synchronized (title) {
    copy = pickCopy(title, member)
    copy.status = BORROWED
    activeLoans++
    return new Loan(.., now + days)
  }
}

Lock ordering

Two operations need two locks each, the member and the title, and that is where deadlocks come from. If borrow took the member then the title, while return took the title then the member, each could hold one lock and wait forever for the other. The fix is a single global order: always member first, then title, in every method. With one order, a cycle of waiting is impossible. Saying this unprompted is a strong signal.

Why the order matters
  • borrow: member, then title
  • return: member, then title
  • if return took title first:
  • borrow holds M, wants T
  • return holds T, wants M
  • both wait forever
  • one global order = no cycle

Flow: reserve

Reserving. Both copies are out, so faculty joins the queue for that title. If a copy is on the shelf, reserving makes no sense, so it is refused with a hint to just borrow it. Joining twice is ignored, and the member is told their position. The queue is a double-ended queue used first in, first out. Hold expiry, say three days to collect, is a natural follow-up.

reserve(member, isbn)
synchronized (title) {
  if (available() > 0)
    throw: a copy is on the shelf
  if (!holds.contains(m))
    holds.addLast(m)
  return holds.size()
}

holds: ArrayDeque, first in first out

Flow: return

Returning. Remove the loan first, so a copy cannot be returned twice. Work out the late days and the fine. Then, under the member lock and the title lock in the same order as borrow, reduce the loan count, add the fine, and look at the queue. If someone is waiting, the copy goes on hold for them; otherwise it goes back on the shelf. Notify the next member after releasing the locks.

giveBack(barcode)
loan = loans.remove(barcode)
late = days(due, now), fine = f(late)
synchronized (member) {
  activeLoans--, unpaidFines += fine
  synchronized (title) {
    next = holds.pollFirst()
    copy: next == null ? AVAILABLE
                       : ON_HOLD(next)
  }
}
notify next, outside the locks

Strategy: fines

Fines are a strategy with one method: given late days, how much. Our default charges ten per day up to a cap of two hundred, so three days late is thirty. A grace period, skipping closed days, or a higher rate for rare books are new implementations. The member then cannot borrow until the fine is paid, which the demo checks.

FinePolicy
interface FinePolicy {
  long fine(long lateDays);
}
record PerDayFine(long perDay, long cap)
  min(lateDays x perDay, cap)

3 days late x 10.00 = 30.00
grace days, weekends free,
  rare books cost more: new classes

Observer

Notifications are observers. When a returned copy goes on hold, the library tells every listener: email, a text message, the screen at the desk. Due soon and overdue reminders come from a daily scan of loans and use the same mechanism. Listeners are called after the locks are released, so a slow email service can never hold up the circulation desk.

LibraryListener
interface LibraryListener {
  void onHoldReady(Member m, Copy c);
}

email, SMS, the desk screen
later: onDueSoon, onOverdue
  from a daily scheduled scan

called outside the locks

Concurrency

Now the race. Eight members try to borrow the last two copies of one title at the same moment. Picking a copy and marking it borrowed happen under the title lock, so exactly two succeed and six are told there is no copy, every time. Member state is guarded by the member lock, always taken first. Titles, loans and the index live in concurrent maps, and removing the loan first makes a double return impossible.

Thread safety checklist
  • member state: member lock
  • copies + holds: title lock
  • order: member, then title
  • titles, loans, index:
  • ConcurrentHashMap
  • loan removed first on return
  • listeners: CopyOnWriteArrayList
  • 8 racers, 2 copies: 2 loans

Extensibility

Extensions. A hold expires after three days and passes to the next in line. Renewal extends the due date only when nobody is waiting. A lost copy is a status plus a replacement charge. Several branches give each copy a location and allow transfers. E-books swap physical copies for a licence count. And an append-only history of loans supports reports and disputes.

Extension points
  • hold expiry: collect in 3 days
  • or pass to the next in line
  • renewals: extend due if no queue
  • lost copy: status LOST + charge
  • branches: Copy gets a location,
  • transfers between branches
  • e-books: a licence count
  • instead of physical copies
  • audit: append-only loan history

Testing

The full code is below the player. The demo searches the catalogue, lends both copies of one book, puts faculty in the queue, moves an injected clock seventeen days ahead, returns three days late for a fine of thirty and hands the copy to faculty with a notification. It blocks borrowing until the fine is paid, enforces the student limit, and races eight members for two copies.

Run it
Rejected: no copy of Designing Data
  Systems for Faculty
Faculty joins the queue at position 1
[notify Faculty] Designing Data Systems
  is held for you at the desk
Returned D-1: 3 days late, fine 30.00,
  copy goes to Faculty
Rejected: Student has unpaid fines
Rejected: Student reached the limit of 2
Race for 2 copies: 2 borrowed, 6 missed

Follow-ups

Expect follow-ups. Why separate book and copy? Search and holds are per book, but loans and status are per copy. How do you avoid deadlock? One lock order everywhere. What if a held copy is never collected? A scheduled job expires the hold and moves on. Search at scale uses a search engine with the same inverted index idea. In a database, lock the copy row and allow one active loan per copy.

Follow-ups to expect
  • why separate Book and Copy?
  • how do you avoid deadlock?
  • held copy never collected?
  • expiry job, next in line
  • search at scale?
  • a search engine, same index idea
  • in a database?
  • row lock on the copy, unique
  • active loan per copy

Say it like this

The short version. A book is the catalogue entry and a copy is the physical item. A title groups the copies and a first in, first out hold queue under one lock. Borrow and return always lock the member, then the title. Plans are data, fines are a strategy, search is an inverted index, and hold notices go to observers.

In the interview
  • "A Book is the catalogue entry,
  • a Copy is the physical item.
  • A Title groups copies and a FIFO
  • hold queue under one lock.
  • Borrow and return lock member
  • then title. Plans are data,
  • fines a strategy, search an
  • inverted index, notices
  • observers."

Interview questions

Why separate Book and BookCopy (Copy)?

A Book is catalogue information shared by every physical item; a Copy has its own barcode, status and loans. Search and reservations work per book, while borrowing, returning and losing work per copy. Merging them breaks as soon as there are two copies.

How do reservations (holds) work?

Each Title keeps a FIFO ArrayDeque of members. You can only reserve when no copy is on the shelf. On return, if the queue is not empty, the copy becomes ON_HOLD for the first member and a listener notifies them; nobody else can borrow that copy.

How do you calculate fines?

A FinePolicy strategy maps late days to an amount; PerDayFine multiplies by a daily rate and caps it. The fine is added to the member on return, and borrowing is refused while unpaid fines exist. Grace periods or rare-book rates are new implementations.

How do you enforce different limits for students and faculty?

Put the rules in data: a Plan enum whose constants carry maxLoans and loanDays. Borrow compares activeLoans with member.plan.maxLoans and sets the due date from plan.loanDays, so a new plan is one new constant.

How do you avoid deadlocks when borrow and return both take two locks?

Use one global lock order: always the member lock first, then the title lock, in every method. Deadlock needs a cycle of waits, and a single order makes a cycle impossible. Notifications run after both locks are released.

How do you stop two members borrowing the same copy?

Choosing a copy and marking it BORROWED happen together under the title lock. In the demo eight members race for two copies and exactly two loans are created. In a database, lock the copy row and keep a unique active loan per copy.

How is search implemented?

An inverted index maps each lower-case word of the title and author to a set of ISBNs. A query intersects the sets for its words and shows the available copy count. Prefix search uses a trie or sorted map; at scale, a search engine.

How would you add hold expiry and overdue reminders?

A scheduled job scans holds and loans daily: expired holds pass the copy to the next member or back to the shelf, and due-soon or overdue loans publish events to the same listeners that send hold notices.