Idempotent Reminder and Queue-Based Availability Notifications
System DesignModel answerLast updated
Design a backend notification system for item-due reminders and FIFO waitlist alerts that survives retries, crashes, and mutable state without sending duplicates.
Reminder and Waitlist Notification System
You are extending a digital lending platform — think libraries, equipment rentals, or media borrowing — with two automated notification workflows.
Workflow A — Loan reminders Each borrower should receive a reminder 24 hours before their item is due, and a second notification exactly when it becomes due. Both must fire exactly once per loan-due event, regardless of worker restarts or delivery-provider retries.
Workflow B — Waitlist availability
Borrowers can join a waitlist for an unavailable item. When N copies are returned or unlocked, the system should notify the first N eligible borrowers in the order they joined the waitlist. Being notified does not by itself reserve a copy; the borrower must act on the notification within some window.
What to Design
- Data models for loans, inventory, waitlist entries, notification records, and delivery attempts.
- A scheduling and dispatch strategy that guarantees at-most-once (or exactly-once) delivery per logical event.
- How concurrent returns or due-date changes are handled safely.
- The set of states a borrower-facing UI should surface, and the transitions between them.
- An outline of the unit and integration tests that give you confidence the system is correct.
Constraints
- A single borrower has at most one active waitlist entry per item.
- Due dates and waitlist positions can change while work is already queued.
- The notification delivery provider may time out, deliver duplicates, or return ambiguous status codes.
Ncopies becoming available andNwaitlist notifications should be matched atomically — no borrower should be skipped or double-notified.- Specifics such as notification channel, time-zone handling, and offer-expiry duration are left open intentionally; identify and resolve these ambiguities as part of your answer.
Clarifying Questions Worth Raising
- What delivery channels are in scope (email, SMS, push), and what guarantees does each provider offer?
- Whose time zone governs "24 hours before due" — the borrower's, the branch's, or UTC?
- Does a waitlist notification create a soft reservation? If so, for how long?
- What makes a borrower ineligible at dispatch time (account suspension, another active copy, etc.)?
- Can a due date be extended, and should an extension generate a new reminder identity or update the existing one?
Hints
Hint 1
Derive each notification's identity from the business event itself — e.g., a hash of (loan_id, event_type) — and enforce uniqueness in the database. This is cheaper than any deduplication layer you add later.
Hint 2
Claim waitlist slots and available copies in a single atomic transaction before any message leaves the system. If the claim fails, no notification should be sent for that attempt.
Hint 3
Never trust the state you read when the job was scheduled; re-read loan status, due date, and borrower eligibility at the moment the worker actually executes. A due date can move between enqueue and dispatch.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifications to Settle First
Before writing a single line of schema, pin down the open questions. Channel choice affects delivery guarantees: email is fire-and-forget with delayed feedback; SMS and push providers often give synchronous success/failure. Time-zone policy changes the scheduler: storing due dates in UTC and converting at dispatch time is simpler than storing local times. Offer expiry (typically 24–72 hours) must exist before building waitlist logic, because expiry is what unblocks the next person in line when someone ignores a notification.
Assume for this answer: multi-channel (email + push), UTC throughout, 48-hour offer window, and ineligibility defined as an account suspension or an already-active copy of the same item.
Data Model
loans (id, borrower_id, item_id, copy_id, due_at, returned_at, status)
waitlist (id, borrower_id, item_id, joined_at, status) -- status: waiting | offered | expired | fulfilled
inventory (copy_id, item_id, status) -- status: available | on_loan | reserved
notifications (id, idempotency_key, type, recipient_id, payload, status, created_at)
-- status: pending | sent | failed | canceled
delivery_log (id, notification_id, provider, sent_at, provider_response, outcome)
The idempotency_key column on notifications has a unique constraint. For loan reminders, the key is sha256(loan_id || event_type) where event_type is due_minus_24h or due_now. For waitlist offers, it is sha256(waitlist_id || offer_round), where offer_round increments each time an offer expires and the slot is re-offered to the next person.
Workflow A: Loan Reminders
Use a transactional outbox pattern. When a loan is created or a due date changes, the same database transaction that writes the loan also upserts two rows in notifications with status pending. A separate scheduler (cron or a delay queue) polls for pending notifications whose fire_at has passed.
When the worker picks up a row it:
- Re-reads the loan. If the due date has moved, the old idempotency key no longer matches the new event; cancel the stale notification and let the upsert triggered by the due-date change create a fresh one.
- Re-checks that the item has not already been returned (
returned_at IS NOT NULL→ cancel). - Attempts delivery. On provider timeout, leave status as
pendingand rely on the next polling cycle. On confirmed success, marksent. On unambiguous failure, markfailedand schedule a retry with backoff up to a configurable limit.
Because the unique constraint prevents two rows with the same key, concurrent workers that both try to insert will see a conflict; one wins, the other skips. Workers that both try to deliver the same existing row should use a SELECT ... FOR UPDATE SKIP LOCKED pattern so only one proceeds.
Workflow B: Waitlist Offers
When copies are returned, a return handler fires. The critical invariant: the number of notifications sent must never exceed the number of copies actually made available. Violating this would mean borrowers get offered a copy that does not exist.
Atomic claim procedure (inside a single transaction):
- Lock the
Nreturned copies and set their status toreserved. - Select the first
Neligible borrowers fromwaitlistordered byjoined_at, skipping suspended accounts or anyone who already holds a copy of the same item. - For each matched pair
(copy_id, waitlist_id), insert a notification row with a unique idempotency key and advance the waitlist entry tooffered. - Commit. Only after commit does the dispatcher pick up those notification rows.
If fewer than N eligible borrowers exist, reserve only as many copies as there are candidates and leave the rest available.
Offer expiry: a background job checks waitlist rows in offered state whose offered_at + 48h has passed. It releases the associated copy back to available, marks the waitlist entry expired, and re-runs the matching procedure for the next eligible borrower. The new offer gets a new idempotency key (offer_round + 1), so there is no collision with the expired notification.
Retries and Reconciliation
Provider callbacks can arrive out of order or be duplicates. Write delivery_log rows with the provider's own message ID and a unique constraint on it. A duplicate callback is a no-op rather than a double-update.
A reconciliation job runs hourly. It finds notifications stuck in pending beyond a threshold, re-attempts delivery, and pages an on-call engineer if the failure rate exceeds a set threshold. This catches silent failures where the worker crashed after claiming a row but before dispatching.
Frontend States
| State | Meaning |
|---|---|
| On waitlist | Borrower is in waiting status; no copy is reserved. |
| Offer pending | Borrower is in offered status; a copy is soft-reserved, offer expires in X hours. |
| Checked out | Borrower claimed the offer; copy is on_loan. |
| Reminder sent | Due date is within 24 hours; no action required unless borrower wants to renew. |
| Item overdue | Due date has passed; copy is still on_loan. |
Transitions from "Offer pending" branch: the borrower claims the copy (→ Checked out) or the timer expires (→ back to On waitlist, lower priority, or fully removed depending on policy).
Tests Worth Writing
- Time boundary: a loan due exactly at midnight fires
due_minus_24hat the right UTC second and not twice. - Due date change: moving a due date cancels the stale reminder and creates a new one with a new key.
- Concurrent returns: two workers simultaneously returning copies of the same item should collectively notify exactly
Nborrowers, not2N. - Expired offer: after 48 hours the copy is released and the next borrower is notified, not the original one again.
- Provider duplicate callback: delivering the same provider message ID twice leaves the notification in
sentwith onedelivery_logrow. - Ineligible borrower: a suspended account mid-queue is skipped and the slot falls to the next eligible person.
Common Mistakes
- Generating idempotency keys at dispatch time rather than at write time — this makes it impossible to deduplicate across worker restarts.
- Sending notifications outside the transaction that claims the copies, which creates a window where a crash results in reserved copies with no notification sent (or the reverse).
- Trusting the state from when the job was enqueued without re-reading at execution time — changed due dates or returned items cause ghost notifications.
- Forgetting that offer expiry must also release the inventory reservation, not just update the waitlist row.