Build a Retry-Safe Task Scheduler for Event Notifications
System DesignModel answerLast updated
Design an async notification system for item availability and due-date reminders with durable idempotency and crash recovery.
You're building a notification subsystem for an existing web platform. The system needs to send two kinds of alerts through the application's internal notification feed:
- Availability alerts: when a previously unavailable item becomes available
- Due-date reminders: alerts sent before an item's deadline
The platform already has items, users, and a subscription mechanism. Your task is to design the notification layer using Celery for task execution and Redis for coordination.
What You Need to Address
- How do you model subscriptions, notification state, and scheduled work?
- How do you ensure exactly-once delivery when workers crash and retry?
- How do you handle due-date changes after a reminder is already scheduled?
- How do you prevent stale or duplicate notifications?
Platform Assumptions
- Users can subscribe to items
- You can detect when an item transitions from unavailable to available
- Due dates can be updated or removed after being set
- Celery workers may crash, restart, or execute the same task multiple times
Questions to Explore Before Designing
Before presenting your design, clarify:
- Should every availability transition trigger a new notification, or only the first one per subscription?
- What offset should reminders use (e.g., 24 hours before due date)? Which timezone applies?
- If a due date changes after scheduling a reminder, should the old reminder be canceled?
- When a user unsubscribes, should pending notifications be canceled? Should delivered ones remain visible?
- Is a late reminder (delivered after its target time or after the due date) still valuable?
Present a design that includes the data model, the task execution flow, idempotency enforcement, and how you handle the edge cases above. Explain how you would test crash scenarios and concurrent task execution.
Hints
Hint 1
Think about how to uniquely identify each notification intent so duplicates can be detected
Hint 2
Consider versioning due dates so you can detect when a scheduled reminder is based on stale information
Hint 3
Design the idempotency check as a database constraint or atomic operation, not just application logic
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
High-Level Approach
The core challenge is building a durable, exactly-once notification system on top of a best-effort task queue. The solution uses database-backed idempotency tokens, versioned scheduling for due-date changes, and revalidation at execution time.
Requirements Clarification
Before designing, I would confirm:
- Availability semantics: Only the first unavailable→available transition per subscription generates a notification (not every transition)
- Reminder timing: 24-hour advance notice, using the item's configured timezone or UTC
- Due-date changes: If the due date changes, cancel the old reminder and schedule a new one
- Unsubscribe behavior: Cancel pending reminders; keep already-delivered notifications visible
- Late delivery: Reminders delivered after the due date are dropped; reminders a few hours late but before the due date are still sent
Data Model
Subscriptions table
subscription_id (PK)
user_id (FK)
item_id (FK)
created_at
first_availability_notified (boolean, default false)
Items table (existing, augmented)
item_id (PK)
is_available (boolean)
due_date (timestamp, nullable)
due_date_version (integer, default 0, incremented on every change)
timezone (string, e.g., 'America/New_York')
Notifications table
notification_id (PK)
user_id (FK)
item_id (FK)
notification_type (enum: 'availability', 'due_date_reminder')
idempotency_key (text, unique index)
created_at
delivered (boolean)
Scheduled tasks table (optional, for observability)
task_id (PK)
item_id (FK)
task_type (enum: 'availability_check', 'due_date_reminder')
due_date_version (integer, nullable, for reminders)
scheduled_for (timestamp)
celery_task_id (text)
status (enum: 'pending', 'completed', 'canceled')
Idempotency Key Design
The idempotency_key ensures exactly-once notification delivery:
- Availability:
f"avail:{subscription_id}:first"(only one per subscription lifetime) - Due-date reminder:
f"reminder:{item_id}:{due_date_version}"(one per version)
The unique constraint on idempotency_key prevents duplicate inserts even if multiple workers execute the same task.
Execution Flow
Availability Notification
-
Trigger: When
item.is_availablechanges fromfalsetotrue, enqueuenotify_availability(item_id)in a Celery task -
Task execution:
- Fetch all active subscriptions for
item_idwherefirst_availability_notified == false - For each subscription:
- Construct idempotency key:
f"avail:{subscription_id}:first" - Insert into
notificationstable with this key - If insert succeeds: mark
subscription.first_availability_notified = true - If insert fails (duplicate key): skip (already delivered by a previous worker)
- Construct idempotency key:
- Transaction commit
- Fetch all active subscriptions for
-
Revalidation: Before inserting, re-check that
item.is_available == trueto avoid notifying stale transitions
Due-Date Reminder
-
Scheduling: When an item's
due_dateis set or updated:- Increment
due_date_version - Cancel any pending reminder tasks for the old version (via task ID or scheduled tasks table)
- Schedule
send_due_date_reminder(item_id, due_date_version)fordue_date - 24 hours
- Increment
-
Task execution:
- Fetch the item and check
item.due_date_version == task_due_date_version - If versions don't match: this task is stale, exit silently
- If
due_dateis in the past or removed: exit (no longer relevant) - For each active subscription to this item:
- Construct idempotency key:
f"reminder:{item_id}:{due_date_version}" - Insert into
notificationswith this key - If insert fails: skip (duplicate worker)
- Construct idempotency key:
- Transaction commit
- Fetch the item and check
-
Late delivery: If the task runs after
due_date, check elapsed time; drop if more than 1 hour late, deliver otherwise
Handling Edge Cases
Worker crashes: Celery retries the task. The idempotency key prevents duplicate notifications even if the task runs 10 times.
Concurrent workers: Database-level unique constraint on idempotency_key serializes duplicate inserts. One worker succeeds, others get a constraint violation.
Due-date changes: Versioning ensures old reminder tasks become no-ops. The new task references the updated version.
Unsubscribe:
- Delete the subscription record
- Query
scheduled_tasksfor pending reminders linked to(user_id, item_id), revoke Celery tasks - Delivered notifications remain in the feed
Availability flapping: If an item toggles availability repeatedly, only the first transition per subscription sends a notification (first_availability_notified flag).
Testing Strategy
- Duplicate delivery test: Execute the same Celery task twice manually; verify only one notification appears
- Crash recovery test: Kill the worker mid-task (before transaction commit); restart and verify task completes without duplicates
- Stale reminder test: Schedule a reminder, update the due date, let both tasks run; verify only the new version delivers
- Race condition test: Run two workers executing the same task concurrently; verify exactly one notification is created
- Late delivery test: Simulate a delayed task (e.g., using
countdownoverride); verify reminders past the due date are dropped
Complexity & Trade-offs
Time Complexity: O(n) per task, where n = number of active subscriptions for an item (typically small, ~10–1000).
Storage: Each notification is one row; idempotency_key index adds ~50 bytes per notification.
Trade-offs:
- Versioning adds complexity but is necessary to avoid cancellation races (trying to revoke a task that already started)
- Storing scheduled tasks separately improves debuggability but adds write overhead
- Revalidation at execution time (checking
is_available,due_date_version) adds a DB read but prevents stale notifications
Common Mistakes:
- Relying on Celery's
task.apply_async(task_id=...)for idempotency (not durable across crashes) - Using application-level "check then insert" instead of a database constraint (race conditions)
- Forgetting to revalidate item state at execution time (delivering stale notifications)
- Not versioning due dates (unable to detect stale reminders)
Code Sketch (Availability Notification)
@celery_app.task(bind=True, max_retries=3)
def notify_availability(self, item_id):
with transaction.atomic():
item = Item.objects.select_for_update().get(id=item_id)
if not item.is_available:
return # stale task, item no longer available
subscriptions = Subscription.objects.filter(
item_id=item_id,
first_availability_notified=False
).select_for_update()
for sub in subscriptions:
idempotency_key = f"avail:{sub.id}:first"
try:
Notification.objects.create(
user_id=sub.user_id,
item_id=item_id,
notification_type='availability',
idempotency_key=idempotency_key,
delivered=True
)
sub.first_availability_notified = True
sub.save()
except IntegrityError:
# Duplicate, already delivered by another worker
continue
This design ensures reliable, exactly-once delivery even in the presence of retries, crashes, and concurrent execution.