A priority queue helps you manage tasks or items where some are more important than others. It lets you always get the highest priority item first.
Priority queue pattern in Redis
ZADD key [NX|XX] [CH] [INCR] score member [score member ...] ZPOPMIN key [count] ZRANGE key start stop [WITHSCORES]
Redis uses sorted sets (ZSET) to implement priority queues.
Scores represent priority: lower score means higher priority.
ZADD tasks 1 "task1" 5 "task2" 3 "task3"
ZPOPMIN tasks
ZRANGE tasks 0 0 WITHSCORES
This example adds three tasks with different priorities. Then it shows the highest priority task, removes it, and finally shows the remaining tasks.
ZADD priority_queue 10 "low_priority_task" 1 "high_priority_task" 5 "medium_priority_task" ZRANGE priority_queue 0 0 WITHSCORES ZPOPMIN priority_queue ZRANGE priority_queue 0 -1 WITHSCORES
Adding items (ZADD) and removing the highest priority item (ZPOPMIN) both run fast, usually in O(log n) time.
Use ZPOPMIN to get and remove the highest priority item atomically.
Common mistake: Using higher scores as higher priority. In Redis sorted sets, lower scores mean higher priority.
Use this pattern when you want to process items in order of importance or urgency.
Priority queues let you handle items by importance using Redis sorted sets.
Lower scores mean higher priority in Redis.
Use ZADD to add items and ZPOPMIN to get and remove the highest priority item.