Library Loan Alert Engine: Holds, Checkouts, and Due Reminders
Data Structure DesignModel answerLast updated
Design a notification manager for a book lending system that handles hold queues, checkout allocation, and idempotent due-date alerts.
Library Loan Alert Engine
A digital lending platform tracks physical book copies, patron loans, and waiting lists. Your job is to build the LendingAlertManager class that processes lending events and time-based polling to send patrons the right notification at the right time — and never twice.
What to implement
add_to_waitlist(patron_id: str, book_id: str, timestamp: int) -> bool
Registers a patron as waiting for any available copy of book_id.
- A patron may only appear once on a book's waitlist at a time. Return
Trueon success,Falseif they are already waiting (or already have a pickup ready).
process_return(copy_id: str, book_id: str, timestamp: int) -> dict | None
Records that a copy has come back.
- If anyone is on the waitlist for
book_id, assign the copy to the patron who has been waiting the longest (earliesttimestamp). Mark it READY with a 48-hour pickup window:expires_at = timestamp + 172800. Return a notification:
{
"type": "HOLD_AVAILABLE",
"patron_id": str,
"book_id": str,
"copy_id": str,
"expires_at": int,
"timestamp": int # the return timestamp
}
- If the waitlist is empty, park the copy in general inventory and return
None.
borrow(patron_id: str, copy_id: str, book_id: str, timestamp: int, loan_days: int = 14) -> bool
Lends a copy to a patron.
- Succeeds in exactly two situations:
- The copy is currently held READY specifically for this patron (consuming that reservation).
- The copy is sitting freely in general inventory under the same
book_id.
- On success, record a loan with
due_date = timestamp + loan_days * 86400. - Return
Falsein all other cases (copy on loan, reserved for someone else, unknown copy, mismatched book).
poll_reminders(current_time: int) -> list[dict]
Scans every active loan and returns applicable alerts.
Due Soon — emit once per loan when: 0 < due_date - current_time <= 86400
Overdue — once the loan is past due (current_time > due_date), emit one alert per 86,400-second window. The first overdue alert fires as soon as current_time > due_date. Each subsequent alert requires at least 86,400 seconds to have elapsed since the previous one was sent for that loan.
Notification format for both types:
{
"type": "LOAN_DUE_SOON" | "LOAN_OVERDUE",
"patron_id": str,
"copy_id": str,
"due_date": int,
"timestamp": current_time
}
Idempotency: calling poll_reminders twice with the same current_time must produce an empty list on the second call.
Constraints
- All timestamps are Unix epoch seconds (integers).
- At most 10,000 total method calls.
- A copy belongs to exactly one patron at a time.
- Tie-breaking on the waitlist: when two patrons joined at the same timestamp, the one who called
add_to_waitlistfirst wins.
Example
mgr = LendingAlertManager()
mgr.add_to_waitlist("p1", "book_A", 1000)
mgr.add_to_waitlist("p2", "book_A", 1050)
notif = mgr.process_return("copy_1", "book_A", 2000)
# notif == {
# "type": "HOLD_AVAILABLE",
# "patron_id": "p1",
# "book_id": "book_A",
# "copy_id": "copy_1",
# "expires_at": 174800, # 2000 + 172800
# "timestamp": 2000
# }
assert mgr.borrow("p1", "copy_1", "book_A", 2500, loan_days=2)
# due_date = 2500 + 2 * 86400 = 175300
# 30 hours after checkout: current_time = 2500 + 108000 = 110500
# time until due: 175300 - 110500 = 64800 seconds (~18 h) → DUE SOON
reminders = mgr.poll_reminders(110500)
assert len(reminders) == 1 and reminders[0]["type"] == "LOAN_DUE_SOON"
# Same timestamp → idempotent, no duplicates
assert mgr.poll_reminders(110500) == []
Follow-up questions to consider:
- How would you handle a patron who never picks up their reserved copy, freeing it for the next person in line?
- How would you scale this to millions of active loans without scanning every loan on every
poll_reminderscall?
Hints
Hint 1
There are four distinct places a copy can live: general inventory, a named reservation, an active loan, or nowhere yet. Model each as a separate data structure and make sure a copy is in exactly one at any given moment.
Hint 2
The waitlist needs earliest-first ordering with arrival-order tie-breaking. A min-heap of (timestamp, sequence_number, patron_id) gives you both properties in O(log n) per push/pop.
Hint 3
For idempotent reminders, track two things per loan: a boolean that flips once when the due-soon alert fires, and the timestamp of the last overdue alert sent. A second call at the same time produces a difference of zero, which fails the ≥ 86400 check automatically.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is keeping copy state consistent across four operations while making poll_reminders idempotent. Break the problem into three concerns: waitlist ordering, copy ownership tracking, and notification deduplication.
State model
A copy is in exactly one of three places at any time:
| Structure | Key | Value |
|---|---|---|
inventory | copy_id | book_id |
reservations | copy_id | {patron_id, book_id, expires_at} |
loans | copy_id | {patron_id, due_date, due_soon_sent, last_overdue_at} |
The waitlist is per-book: waitlists[book_id] holds a min-heap of (timestamp, seq, patron_id). A global seq counter breaks ties so that patrons who joined at the same second are served in call order. An active_set of (patron_id, book_id) pairs enforces the one-hold-per-patron-per-book rule in O(1).
Expired reservations
If a patron never picks up their copy, it should cascade to the next person in line. Handle this lazily with a secondary min-heap expiry_heap of (expires_at, copy_id). Every public method calls _expire(now) first, which pops stale reservations and re-runs _allocate for each freed copy. This keeps the per-call cost amortized O(log R) across the entire run rather than requiring a background thread.
Idempotent reminders
Two rules keep poll_reminders side-effect-free on repeated calls at the same time:
- Due soon: a one-shot
due_soon_sentflag. Once set, this loan never produces anotherLOAN_DUE_SOON. - Overdue: store
last_overdue_at(initially-∞). Only emit ifcurrent_time - last_overdue_at >= 86400. A repeat call at the samecurrent_timegives a difference of 0, which fails the check.
Complexity
| Method | Time |
|---|---|
add_to_waitlist | O(log H) |
process_return | O(log H) |
borrow | O(1) |
poll_reminders | O(L) per call; O(log R) amortized for expiry |
Space: O(H + R + L + inventory).
Common mistakes
- Forgetting expiry cascades. When a reservation times out, the copy doesn't vanish — it should go to the next waiting patron or back to inventory.
- Heap staleness. After a copy is consumed by
borrow, its entry may still sit inexpiry_heap. Guard against this by validating thatreservations[copy_id].expires_atstill matches the heap entry before acting on it. - Overdue window boundary. The first overdue alert should fire as soon as
current_time > due_date, not 24 hours later. Initializelast_overdue_at = -infinity(ordue_date - DAY) to make the first check pass immediately. - Mismatched book on borrow. A copy sitting in inventory under
book_Amust not be loanable whenborrowpassesbook_B. Check thebook_idmatches. - Skipping the due-soon window. If no poll happens while the book is in the 0–24 h window, the loan moves straight to overdue without ever triggering
LOAN_DUE_SOON. That's correct — don't retroactively emit it.
Solution
import heapq
PICKUP_WINDOW = 172800 # 48 hours in seconds
DAY = 86400
class LendingAlertManager:
def __init__(self):
self.waitlists = {} # book_id -> min-heap[(ts, seq, patron_id)]
self.active_set = set() # (patron_id, book_id): waiting or ready
self.reservations = {} # copy_id -> {patron_id, book_id, expires_at}
self.expiry_heap = [] # (expires_at, copy_id)
self.inventory = {} # copy_id -> book_id
self.loans = {} # copy_id -> loan record
self._seq = 0 # tie-breaker for simultaneous holds
# ── internal ──────────────────────────────────────────────
def _allocate(self, copy_id: str, book_id: str, ts: int):
"""Assign copy to the next waiting patron, or park in inventory."""
heap = self.waitlists.get(book_id)
if heap:
_, _, patron_id = heapq.heappop(heap)
expires_at = ts + PICKUP_WINDOW
self.reservations[copy_id] = {
"patron_id": patron_id,
"book_id": book_id,
"expires_at": expires_at,
}
heapq.heappush(self.expiry_heap, (expires_at, copy_id))
return {
"type": "HOLD_AVAILABLE",
"patron_id": patron_id,
"book_id": book_id,
"copy_id": copy_id,
"expires_at": expires_at,
"timestamp": ts,
}
self.inventory[copy_id] = book_id
return None
def _expire(self, now: int):
"""Lazily expire reservations whose pickup window has closed."""
while self.expiry_heap and self.expiry_heap[0][0] < now:
exp, copy_id = heapq.heappop(self.expiry_heap)
res = self.reservations.get(copy_id)
# Skip stale heap entries (already consumed or reassigned)
if res is None or res["expires_at"] != exp:
continue
del self.reservations[copy_id]
self.active_set.discard((res["patron_id"], res["book_id"]))
# Cascade: try to give the freed copy to the next patron
self._allocate(copy_id, res["book_id"], exp)
# ── public API ────────────────────────────────────────────
def add_to_waitlist(self, patron_id: str, book_id: str, timestamp: int) -> bool:
self._expire(timestamp)
key = (patron_id, book_id)
if key in self.active_set:
return False
self.active_set.add(key)
self._seq += 1
heapq.heappush(
self.waitlists.setdefault(book_id, []),
(timestamp, self._seq, patron_id),
)
return True
def process_return(self, copy_id: str, book_id: str, timestamp: int):
self._expire(timestamp)
# Clear any previous state for this copy
self.loans.pop(copy_id, None)
self.inventory.pop(copy_id, None)
return self._allocate(copy_id, book_id, timestamp)
def borrow(self, patron_id: str, copy_id: str, book_id: str,
timestamp: int, loan_days: int = 14) -> bool:
self._expire(timestamp)
if copy_id in self.loans:
return False
res = self.reservations.get(copy_id)
if res is not None:
# Copy is reserved — only the intended patron may take it
if res["patron_id"] != patron_id or res["book_id"] != book_id:
return False
del self.reservations[copy_id]
self.active_set.discard((patron_id, book_id))
elif self.inventory.get(copy_id) == book_id:
del self.inventory[copy_id]
else:
return False # unknown copy, wrong book, or already on loan
self.loans[copy_id] = {
"patron_id": patron_id,
"due_date": timestamp + loan_days * DAY,
"due_soon_sent": False,
# Initialise so first overdue check fires immediately
"last_overdue_at": timestamp + loan_days * DAY - DAY,
}
return True
def poll_reminders(self, current_time: int) -> list:
self._expire(current_time)
alerts = []
for copy_id, loan in self.loans.items():
due = loan["due_date"]
gap = due - current_time
if 0 < gap <= DAY:
# Due within the next 24 hours and not yet past due
if not loan["due_soon_sent"]:
loan["due_soon_sent"] = True
alerts.append({
"type": "LOAN_DUE_SOON",
"patron_id": loan["patron_id"],
"copy_id": copy_id,
"due_date": due,
"timestamp": current_time,
})
elif current_time > due:
# Past due — emit at most one alert per 86,400-second window
if current_time - loan["last_overdue_at"] >= DAY:
loan["last_overdue_at"] = current_time
alerts.append({
"type": "LOAN_OVERDUE",
"patron_id": loan["patron_id"],
"copy_id": copy_id,
"due_date": due,
"timestamp": current_time,
})
return alerts
Key design decisions worth mentioning
Lazy expiry vs. a scheduled job. Lazy expiry keeps the implementation self-contained and correct for a single-process simulation. In production you'd replace this with a scheduled worker and a database index on expires_at, but the correctness invariants are identical.
Why last_overdue_at = due_date - DAY at loan creation. Setting it one full day before due_date means the first overdue alert fires as soon as current_time > due_date (difference immediately ≥ DAY), without any special-case logic for the first alert.
Scaling poll_reminders. The O(L) scan is fine for 10^4 calls but breaks at millions of loans. The fix is a sorted structure (e.g., a min-heap or database index) keyed on due_date, so only loans near the threshold are examined. That's a natural follow-up discussion.