0
0
RedisHow-ToBeginner · 3 min read

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 5
💻

Example

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 timeout too low, causing the command to return (nil) before data arrives.
  • Using BRPOP on keys that are not lists, which causes errors.
  • Expecting BRPOP to 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

ParameterDescription
keyOne or more list keys to pop from
timeoutSeconds to block if lists are empty (0 = block forever)
ReturnArray 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.