0
0
Redisquery~5 mins

BLPOP and BRPOP for blocking pop in Redis

Choose your learning style9 modes available
Introduction
BLPOP and BRPOP let you wait for items to appear in a list and remove them immediately. This helps when you want to get data as soon as it is available without checking repeatedly.
You have a task queue and want workers to wait for new tasks without wasting CPU.
You want to process messages as soon as they arrive in a list.
You need to coordinate multiple clients where one waits for data from another.
You want to avoid polling a list repeatedly to check for new items.
You want to build a simple chat system where clients wait for new messages.
Syntax
Redis
BLPOP key [key ...] timeout
BRPOP key [key ...] timeout
BLPOP removes and returns the first element (left) from the first non-empty list among the given keys.
BRPOP removes and returns the last element (right) from the first non-empty list among the given keys.
timeout is the number of seconds to wait if all lists are empty. Use 0 to wait forever.
Examples
Waits up to 5 seconds for an item from 'mylist' and removes it from the left.
Redis
BLPOP mylist 5
Waits forever for an item from 'queue1' or 'queue2' and removes it from the right of the first non-empty list.
Redis
BRPOP queue1 queue2 0
Waits forever for an item from 'tasks' list and removes it from the left.
Redis
BLPOP tasks 0
Sample Program
First, we add 'apple' and 'banana' to 'mylist'. Then BLPOP removes and returns 'apple' from the left immediately.
Redis
RPUSH mylist "apple"
RPUSH mylist "banana"
BLPOP mylist 1
OutputSuccess
Important Notes
If all lists are empty and timeout expires, BLPOP/BRPOP return nil.
You can pass multiple keys to wait on several lists at once.
BLPOP and BRPOP block the client connection until an element is available or timeout happens.
Summary
BLPOP and BRPOP wait for and remove items from lists, blocking if empty.
BLPOP removes from the left; BRPOP removes from the right.
They help build efficient waiting queues without polling.