4 Hours

2. Redis Data Structures & Commands Deep Dive

Data Structures

Mastering Redis Data Structures

Redis is more than a key-value store — it's a data structure server. Redis supports a rich set of data structures, each optimized for specific use cases. Understanding these structures and their internal implementations is essential for building efficient applications.

The key to Redis mastery is choosing the right data structure for your use case. Strings are the simplest and most versatile — they store text, numbers, and binary data. Hashes store objects as field-value pairs, perfect for user profiles. Lists are ordered collections, ideal for queues. Sets are unordered collections with uniqueness, perfect for tags. Sorted Sets are ordered collections with scores, essential for leaderboards. Streams provide durable messaging. Bitmaps enable efficient boolean flags. HyperLogLogs provide cardinality estimation. Geospatial indexes support location-based queries.

Each data structure in Redis is implemented with careful attention to memory efficiency and performance. For example, lists are implemented as linked lists for small sizes and compact arrays for larger sizes. Hashes use zip lists for small fields and hash tables for larger ones. Understanding these internal implementations helps you predict performance and memory usage. This module covers each data structure in depth with practical examples and performance considerations.

Strings: The Foundation of Redis

Strings are the simplest Redis data type, but they're also the most versatile. A Redis string can store text, numbers, JSON, binary data, and even images. Strings support a wide range of operations including SET, GET, INCR, DECR, APPEND, and more. Strings are atomic — operations like INCR are safe for counters without race conditions.

Strings have a maximum size of 512MB, though typical usage is much smaller. For large binary data, consider using Redis Streams or external storage. Strings support TTL (Time-To-Live) for automatic expiration. SETEX combines SET and EXPIRE in one atomic operation. MSET and MGET support batch operations. Strings are the foundation of Redis and are used in most applications.

JavaScript
// Basic string operations
SET name "Alice"           // Set a key
GET name                   // Get a key
SET counter 0              // Set a counter
INCR counter               // Increment by 1 (returns 1)
INCRBY counter 10          // Increment by 10
DECR counter               // Decrement by 1
GET counter                // Get the value (returns 10)
APPEND name " Smith"       // Append to a string
GET name                   // Returns "Alice Smith"

// Set with expiration (1 hour)
SETEX session:123 3600 "user_data"

// Set only if key doesn't exist
SETNX unique_key "value"

// Batch operations
MSET key1 "value1" key2 "value2"
MGET key1 key2

// String information
STRLEN name                // Get string length
GETRANGE name 0 4          // Get substring

Hashes: Objects Made Simple

Hashes store objects as field-value pairs, making them perfect for storing structured data like user profiles, product information, and configuration settings. Hashes are more memory-efficient than storing JSON in strings because Redis can optimize the storage for small fields. Hashes support HSET, HGET, HMSET, HMGET, and HGETALL. They also support HINCRBY for atomic increments on numeric fields.

Hashes are ideal for objects with many fields that are accessed individually. For example, a user profile with name, email, age, and preferences. Hashes allow you to update individual fields without rewriting the entire object. This is more efficient and avoids race conditions. Hashes support up to 2^32-1 fields, though practical limits are much lower.

JavaScript
// Hash operations
HSET user:1 name "Alice" age 30 email "alice@example.com"
HGET user:1 name            // Returns "Alice"
HGETALL user:1              // Returns all fields
HMSET user:2 name "Bob" age 25
HMGET user:1 name email     // Returns ["Alice", "alice@example.com"]
HINCRBY user:1 age 1        // Increment age by 1
HKEYS user:1                // Get all field names
HVALS user:1                // Get all field values
HLEN user:1                 // Get number of fields
HEXISTS user:1 age          // Check if field exists (returns 1)
HDEL user:1 age             // Delete a field

// Bulk operations
HMSET product:1 name "Widget" price 19.99 stock 100

Lists: Ordered Collections

Lists are ordered collections of strings. They support push and pop operations from both ends, making them ideal for queues, stacks, and activity feeds. Lists are implemented as linked lists for small sizes and compact arrays for larger sizes, optimizing for different access patterns.

Lists support LPUSH, RPUSH, LPOP, RPOP, LRANGE, and LTRIM. They're efficient for append and prepend operations. LRANGE is efficient for accessing ranges near the ends. For large lists, avoid LRANGE on large ranges as it can be slow. Lists are ideal for implementing queues with RPUSH and LPOP, or stacks with LPUSH and LPOP. Lists can store up to 2^32-1 elements.

JavaScript
// List operations
LPUSH queue "task1"        // Add to left (front)
LPUSH queue "task2"
RPUSH queue "task3"         // Add to right (back)
LRANGE queue 0 -1          // Get all elements: ["task2", "task1", "task3"]
LPOP queue                 // Remove from left: returns "task2"
RPOP queue                 // Remove from right: returns "task3"
LLEN queue                 // Get list length
LINDEX queue 0             // Get element at index 0
LTRIM queue 0 10           // Keep only first 10 elements

// Blocking operations
BRPOP queue 5              // Blocking pop from right (timeout 5s)
BLPOP queue 5              // Blocking pop from left (timeout 5s)

// Use as a queue: producer adds, worker processes
RPUSH tasks "job1" "job2" "job3"
LPOP tasks                  // Process job1

// Use as a stack
LPUSH stack "item1" "item2"
LPOP stack                  // Returns "item2" (LIFO)

Sets: Uniqueness Guaranteed

Sets are unordered collections of unique strings. They support add, remove, and membership operations. Sets also support set operations like union, intersection, and difference. Sets are perfect for tags, unique visitors, and relationships. Sets are implemented using hash tables for O(1) membership tests.

Sets are ideal for tracking unique items like visited users, tags on a post, or friendships. SADD adds members, SREM removes them, and SISMEMBER checks existence. SCARD returns the set size. SUNION, SINTER, and SDIFF perform set operations. SRANDMEMBER gets random members. SPOP removes and returns random members. Sets can store up to 2^32-1 members.

JavaScript
// Set operations
SADD tags "redis" "database" "cache"   // Add members
SMEMBERS tags               // Get all members
SISMEMBER tags "redis"      // Check if member exists (returns 1)
SREM tags "cache"           // Remove a member
SCARD tags                  // Get set size

// Set operations
SUNION tags1 tags2          // Union of sets
SINTER tags1 tags2          // Intersection of sets
SDIFF tags1 tags2           // Difference of sets

// Random operations
SRANDMEMBER tags 2          // Get 2 random members
SPOP tags 1                 // Pop a random member

// Use cases: unique visitors
SADD visitors:day1 "user1" "user2" "user3"
SCARD visitors:day1         // Count unique visitors: 3

// Use cases: tags
SADD post:1:tags "redis" "database"
SADD post:2:tags "redis" "cache"
SINTER post:1:tags post:2:tags  // Posts with both "redis" and "database"

Sorted Sets: Ordered by Score

Sorted sets are ordered collections of unique strings, each with a score. They support ZADD, ZRANK, ZREVRANK, ZRANGE, and ZREVRANGE. Sorted sets are perfect for leaderboards, priority queues, and time-series data. They're implemented using a skiplist and hash table for efficient access.

Sorted sets are ideal for any use case requiring ordering by a numeric value. Leaderboards use scores for ranking. Priority queues use scores as priorities. Time-series data uses timestamps as scores. ZRANK returns the rank (0-based) of a member. ZREVRANK returns the reverse rank. ZRANGE returns members by score. ZREMRANGEBYRANK removes by rank. ZINCRBY increments scores atomically.

JavaScript
// Sorted set operations
ZADD leaderboard 100 "Alice" 50 "Bob" 75 "Charlie"
ZRANK leaderboard "Alice"    // Rank (0-based) returns 2
ZREVRANK leaderboard "Alice" // Reverse rank returns 0
ZRANGE leaderboard 0 -1      // All members by score
ZREVRANGE leaderboard 0 -1   // All members by score descending
ZSCORE leaderboard "Alice"   // Get score (returns 100)
ZINCRBY leaderboard 10 "Alice" // Increment score by 10
ZCOUNT leaderboard 50 100    // Count members with scores in range
ZREMRANGEBYRANK leaderboard 0 0  // Remove lowest ranked member
ZREVRANGE leaderboard 0 9 WITHSCORES  // Top 10 with scores

// Use cases: leaderboards
// Add player scores
ZADD game:scores 1500 "player1" 2300 "player2" 1800 "player3"
// Get top 3 players
ZREVRANGE game:scores 0 2 WITHSCORES
// Increment score
ZINCRBY game:scores 100 "player1"

Knowledge Check

Ready to test your understanding of 2. Redis Data Structures & Commands Deep Dive?

Back