In Redis, the BRPOP command is the blocking variant of the RPOP command. It blocks the connection when there are no elements to pop from any of the given lists.
The way the command works is that an element is popped from the tail of the first list that is non-empty, with the given keys being checked in the order that they are given. When there are no elements to pop from any of the lists, it blocks the connection.
Although BRPOP is considered the blocking variant of RPOP, the two commands actually accept different arguments and function slightly differently. As of this writing, BRPOP accepts multiple keys, whereas RPOP doesn’t. Also, RPOP allows us to specify how many list elements to pop whereas PRPOP doesn’t.
Syntax
The syntax for BRPOP goes like this:
BRPOP key [key ...] timeout
When a non-zero timeout is specified, the client will unblock returning a nil multi-bulk value when the specified timeout has expired without a push operation against at least one of the specified keys.
Prior to Redis 6.0.0 timeout was interpreted as an integer. However, from 6.0.0 timeout is interpreted as a double.
Example
Suppose we create a list like this:
RPUSH scores 1 2 3 4 5 6 7 8 9 10
Result:
(integer) 10
Let’s look at its contents:
LRANGE scores 0 -1
Result:
1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6" 7) "7" 8) "8" 9) "9" 10) "10"
We can use BRPOP to pop the last element like this:
BRPOP scores 0
Result:
1) "scores" 2) "10"
The first value returned is the key, and the second is the value of the element that was popped. In this case I specified a timeout of zero, which is used to block indefinitely. A value was popped however, and so the connection wasn’t blocked.
Now when we return all elements in the list, we see that the last element is no longer there:
LRANGE scores 0 -1
Result:
1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6" 7) "7" 8) "8" 9) "9"
Multiple Lists
We can specify multiple lists. As mentioned, BRPOP pops the element from the head of the first list that is non-empty list:
BRPOP emptylist scores 0
Result:
1) "scores" 2) "9"
In this case, the emptylist key is an empty list, and so the operation was performed on the scores key.
Wrong Type
If the key is the wrong type, an error is returned:
BRPOP customer 0
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
We can use the TYPE command to check the key’s type:
TYPE customer
Result:
hash
In this case it’s a hash.
Non-Existent Key
If the key doesn’t exist, nil is returned after the timeout period has elapsed:
BRPOP nonexistentkey 7
Result:
(nil) (7.07s)
When I ran that example in my Redis client, there was a seven second pause before the result was returned.
More Information
For more information, see the Redis documentation for the BRPOP command. Also see the Redis documentation for the BLPOP command (that page contains more detail that’s applicable to both commands).