How to Use BRPOP in Redis: Syntax, Example, and Tips
Use the
BRPOP command in Redis to remove and return the last element of one or more lists, blocking the connection until an element is available or a timeout occurs. The syntax is BRPOP key [key ...] timeout, where timeout is the number of seconds to wait.Syntax
The BRPOP command syntax is:
BRPOP key [key ...] timeout
Here:
key: One or more list keys to check.timeout: Number of seconds to block if all lists are empty. Use 0 to block indefinitely.
The command returns the key and the popped value from the first non-empty list found.
redis
BRPOP mylist 5Example
This example shows how BRPOP waits for an element to be available in the list tasks. If the list is empty, it blocks for up to 10 seconds.
redis
127.0.0.1:6379> LPUSH tasks "task1" (integer) 1 127.0.0.1:6379> BRPOP tasks 10 1) "tasks" 2) "task1" 127.0.0.1:6379> BRPOP tasks 3 (nil)
Output
1) "tasks"
2) "task1"
(nil)
Common Pitfalls
Common mistakes when using BRPOP include:
- Setting
timeouttoo low, causing the command to return(nil)before data arrives. - Using
BRPOPon keys that are not lists, which causes errors. - Expecting
BRPOPto return immediately when lists are empty without blocking.
Always ensure the keys are lists and choose an appropriate timeout.
redis
127.0.0.1:6379> BRPOP notalist 5 (error) WRONGTYPE Operation against a key holding the wrong kind of value # Correct usage: 127.0.0.1:6379> LPUSH mylist "item" (integer) 1 127.0.0.1:6379> BRPOP mylist 5 1) "mylist" 2) "item"
Quick Reference
| Parameter | Description |
|---|---|
| key | One or more list keys to pop from |
| timeout | Seconds to block if lists are empty (0 = block forever) |
| Return | Array with key and popped value, or nil if timeout reached |
Key Takeaways
BRPOP removes and returns the last element of the first non-empty list among given keys.
It blocks the connection up to the specified timeout if all lists are empty.
Use a timeout of 0 to block indefinitely until an element is available.
Ensure the keys are lists to avoid errors.
BRPOP returns nil if the timeout expires without any element becoming available.