Redis › Redis as a Message Queue

How would you implement a delayed task queue in Redis, where a task should only become available for processing after a specific future time?

Advanced

Answer

You use a sorted set where the score represents the timestamp at which each task should become due, with a background process periodically checking for and moving any tasks whose due timestamp has already passed into an actual processing queue, effectively implementing scheduled, delayed task execution using Redis's native data structures.
ZADD delayed_tasks 1725800000 'send_reminder_email'
-- A background process periodically checks:
ZRANGEBYSCORE delayed_tasks 0 <current_timestamp>
Real-world example A reminder notification system schedules emails to be sent at a specific future time using a sorted set keyed by timestamp, with a background worker checking every few seconds for any reminders that have become due and moving them into the active processing queue.

Common follow-ups: How frequently should the background process check for due tasks?;How do you handle a task that needs to be cancelled before its scheduled time arrives?