Redis Lists
7. Redis Lists
Section titled “7. Redis Lists”What is a Redis List?
Section titled “What is a Redis List?”A Redis List is an ordered collection of strings. You can add elements to the left (head) or right (tail) of the list. It is essentially a doubly linked list internally.
Analogy: A ticket queue at a counter. New people join at the back (right), and the counter serves from the front (left).
Queue vs Stack Patterns
Section titled “Queue vs Stack Patterns”flowchart LR subgraph Queue[Queue — FIFO First In, First Out] Q1["RPUSH task1..task3"] --> Q2["✅ queue: [task1, task2, task3]"] Q2 --> Q3["LPOP → task1"] Q3 --> Q4["Remaining: [task2, task3]"] end
subgraph Stack[Stack — LIFO Last In, First Out] S1["LPUSH action1..action3"] --> S2["✅ stack: [action3, action2, action1]"] S2 --> S3["LPOP → action3"] S3 --> S4["Remaining: [action2, action1]"] end
style Queue fill:#7c3aed,color:#fff style Stack fill:#3b82f6,color:#fff style Q3 fill:#059669,color:#fff style S3 fill:#f59e0b,color:#fffCore Commands
Section titled “Core Commands”# Push to the RIGHT end (tail) — queue-likeRPUSH tasks "send-email" "process-payment" "generate-report"
# Push to the LEFT end (head)LPUSH tasks "urgent-task"
# List all items (0 = first, -1 = last/end)LRANGE tasks 0 -1# Output:# 1) "urgent-task"# 2) "send-email"# 3) "process-payment"# 4) "generate-report"
# Get length of listLLEN tasks# Output: (integer) 4
# Pop from the LEFT (dequeue)LPOP tasks# Output: "urgent-task"
# Pop from the RIGHT (stack pop)RPOP tasks# Output: "generate-report"
# Peek at specific index (0-based)LINDEX tasks 0# Output: "send-email"Queue vs Stack Implementation
Section titled “Queue vs Stack Implementation”| Pattern | Push | Pop | Use Case |
|---|---|---|---|
| Queue (FIFO) | RPUSH | LPOP | Task queue, job processing |
| Stack (LIFO) | LPUSH | LPOP | Browser history, undo operations |
Real-World Examples
Section titled “Real-World Examples”Example 1: Notification Queue
# Producer: add notificationsRPUSH notifications:user:42 "You have a new message"RPUSH notifications:user:42 "Your order has shipped"
# Consumer: process notifications one by oneLPOP notifications:user:42# Output: "You have a new message"Example 2: Recent Activity Feed
# Add recent actions (trim to last 10 items)LPUSH feed:user:42 "Liked post #101"LTRIM feed:user:42 0 9 # Keep only last 10
# Get activity feedLRANGE feed:user:42 0 -1Example 3: Background Job Queue
# Worker 1 adds a jobRPUSH job:queue '{"type":"email","to":"user@example.com"}'
# Worker 2 picks up the job (blocks if empty — BLPOP)BLPOP job:queue 30# Blocks for up to 30 seconds waiting for a new job