0
0
Redisquery~5 mins

Priority queue pattern in Redis

Choose your learning style9 modes available
Introduction

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.

You want to process urgent customer support tickets before others.
You need to run jobs where some have deadlines sooner than others.
You want to manage tasks in a game where some actions have higher priority.
You want to schedule messages to be sent based on importance.
You want to handle events where some must happen before others.
Syntax
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.

Examples
Adds tasks with different priorities (1 is highest priority).
Redis
ZADD tasks 1 "task1" 5 "task2" 3 "task3"
Removes and returns the task with the highest priority (lowest score).
Redis
ZPOPMIN tasks
Shows the highest priority task without removing it.
Redis
ZRANGE tasks 0 0 WITHSCORES
Sample Program

This example adds three tasks with different priorities. Then it shows the highest priority task, removes it, and finally shows the remaining tasks.

Redis
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
OutputSuccess
Important Notes

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.

Summary

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.