8. Lists: Queues & FIFO Patterns
Quicklists and Double-Ended Queueing
Redis Lists are ordered sequences of strings, implemented using a hybrid data structure called a Quicklist. A Quicklist is a doubly linked list where each node contains a ZipList. This structure balances the trade-offs of linked lists (which suffer from memory fragmentation and pointer overhead) and arrays (which require expensive memory reallocations during insertions). By chaining ZipLists together, Quicklists allow O(1) pushes and pops at the head or tail of the list while maintaining high memory density.
Lists are ideal for building First-In-First-Out (FIFO) job queues or Last-In-First-Out (LIFO) stacks. By using commands like LPUSH (left push) and RPOP (right pop), applications can push tasks to one end of a list and consume them from the other. This provides a simple, high-throughput message broker pattern suitable for processing background jobs, distributing emails, or sequencing application events.
In addition to queues, lists are used to store chronological feeds, such as a user's recent activity stream. Because lists maintain order, appending events is fast. When querying, applications can retrieve subsets of the list using the LRANGE command, making it easy to implement paginated timeline feeds.
Reliable Queueing & Blocking Operations
In standard queue architectures, worker processes continuously loop and execute RPOP commands to poll the queue for work. If the queue is empty, the worker receives a null response. This polling loop creates a bottleneck: workers consume CPU cycles and flood Redis with requests, degrading performance. To solve this, Redis provides blocking list pops: BLPOP and BRPOP.
A blocking pop takes a timeout parameter. When a worker calls BRPOP queue 5, it instructs Redis: 'If the queue contains elements, pop one immediately. If it is empty, suspend my connection and block until an element is pushed, or until 5 seconds pass.' This suspends the client socket on the server. The moment another client pushes an element to the list, Redis awakens the blocked client and delivers the item. This eliminates polling latency, reduces CPU usage, and ensures instant task delivery.
To prevent lists from growing indefinitely and exhausting memory, developers must use the LTRIM command. LTRIM trims a list, keeping only elements within a specified range and deleting the rest. For instance, after pushing a new activity log entry to a list, the application can call LTRIM log_key 0 99 to cap the list size at 100 entries. This ensures the list remains small and avoids memory leaks.
// Reliable Background Job Worker using Blocking Pops const Redis = require('ioredis'); const client = new Redis({ host: '127.0.0.1', port: 6379 }); async function startWorker(queueName) { console.log(`Worker listening on queue: ${queueName}...`); while (true) { try { // Block connection until a job is pushed, timeout after 10s // BRPOP returns [key, value] or null on timeout const job = await client.brpop(queueName, 10); if (job) { const [_, payload] = job; console.log('Processing job payload:', JSON.parse(payload)); // Execute background work here... } } catch (error) { console.error('Worker loop encountered error:', error); // Wait before retrying to prevent rapid error looping await new Promise(resolve => setTimeout(resolve, 5000)); } } }
Knowledge Check
Ready to test your understanding of 8. Lists: Queues & FIFO Patterns?