0
0
RedisComparisonBeginner · 3 min read

LPUSH vs RPUSH in Redis: Key Differences and Usage

In Redis, LPUSH adds elements to the start (left) of a list, while RPUSH adds elements to the end (right). Both commands insert values but differ in the position where the new elements appear in the list.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of LPUSH and RPUSH commands in Redis.

FactorLPUSHRPUSH
Insertion PositionStart (left) of the listEnd (right) of the list
Order of New ElementsNew elements appear in reverse orderNew elements appear in the same order
Use Case ExampleAdd recent items to frontAdd items to queue end
List Growth DirectionList grows leftwardsList grows rightwards
Command SyntaxLPUSH key value [value ...]RPUSH key value [value ...]
⚖️

Key Differences

The main difference between LPUSH and RPUSH lies in where they add new elements in a Redis list. LPUSH inserts elements at the beginning (left side), so the newest elements become the first items in the list. This is useful when you want to treat the list like a stack or keep the most recent items at the front.

On the other hand, RPUSH adds elements at the end (right side) of the list. This behavior is typical for queue-like structures where new items join at the back and older items are processed from the front.

Another subtle difference is how multiple elements are added: LPUSH inserts them in reverse order, so the last element in the command becomes the first in the list, while RPUSH preserves the order of the elements as given.

💻

LPUSH Code Example

redis
LPUSH mylist "apple" "banana" "cherry"
LRANGE mylist 0 -1
Output
1) "cherry" 2) "banana" 3) "apple"
↔️

RPUSH Equivalent

redis
RPUSH mylist "apple" "banana" "cherry"
LRANGE mylist 0 -1
Output
1) "apple" 2) "banana" 3) "cherry"
🎯

When to Use Which

Choose LPUSH when you want to add new items to the front of a list, such as implementing a stack or keeping the most recent entries easily accessible. Use RPUSH when you want to add items to the end, like building a queue where items are processed in the order they arrive. Your choice depends on whether you want the list to grow from the left or right side based on your application's logic.

Key Takeaways

LPUSH adds elements to the start (left) of a Redis list, RPUSH adds to the end (right).
LPUSH reverses the order of multiple inserted elements, RPUSH preserves it.
Use LPUSH for stack-like behavior and RPUSH for queue-like behavior.
Both commands grow the list but differ in insertion position and element order.
Choose based on whether you want new items at the front or back of your list.