Back to results for “Redis as a Message Queue”
Redis › Redis as a Message Queue

How do you implement a priority queue pattern using Redis, where certain tasks should be processed before others?

Intermediate

Answer

You can use a sorted set instead of a plain list, storing each task with a score representing its priority, and have workers retrieve the highest or lowest priority task using ZPOPMIN or ZPOPMAX, ensuring that more urgent tasks are always processed ahead of lower priority ones regardless of the order they were originally added.
ZADD priority_queue 1 'urgent_task'
ZADD priority_queue 5 'normal_task'
ZPOPMIN priority_queue
Real-world example A customer support ticketing system uses a sorted set based priority queue, ensuring tickets marked as urgent are always processed by available agents before lower priority tickets, regardless of when each ticket was originally submitted.

Common follow-ups: How do you handle two tasks that happen to have the exact same priority score?;Is ZPOPMIN an atomic operation safe for multiple concurrent workers?