4. Advanced Data Structures: Streams, Bitmaps, HyperLogLog & Geospatial
Advanced Redis Data Structures
Beyond the basic data structures, Redis offers advanced structures for specific use cases. Streams provide a log data structure for messaging and event sourcing. Bitmaps enable efficient bit-level operations for boolean flags and analytics. HyperLogLog provides cardinality estimation with minimal memory. Geospatial indexes support location-based queries. These structures extend Redis's capabilities to cover a wide range of modern application needs.
Streams are perfect for event sourcing and messaging, providing durable, ordered logs with consumer groups for parallel processing. Bitmaps are efficient for boolean flags and analytics, using one bit per flag. HyperLogLog estimates unique counts with very low memory (12KB for 2^64 elements). Geospatial indexes support near-by queries with longitude/latitude coordinates. Understanding these structures unlocks advanced use cases and makes Redis a complete data platform.
Streams: Event Logs and Durable Messaging
Streams are a log data structure for messaging and event sourcing. They're similar to Kafka topics, providing durable, ordered logs. Each entry has a unique ID (timestamp-based or custom). Entries are ordered by time. Streams support consumer groups for parallel processing. Streams are ideal for event-driven architectures, real-time analytics, and message queuing with persistence.
Streams are implemented as a radix tree of entries, making them efficient for appending and range queries. Each entry can contain multiple fields. Streams support XADD, XREAD, XRANGE, XREVRANGE, and consumer group operations. Consumer groups enable parallel processing with message acknowledgment and retry. Streams are the foundation of Redis-based messaging systems.
Use streams for event sourcing, real-time analytics, and message queuing. Streams provide durability, ordering, and consumer groups that make them suitable for production messaging. Unlike Pub/Sub, streams persist messages, so consumers can process messages even if they're offline temporarily.
// Stream operations XADD events * type "user_login" user_id "123" timestamp "2024-01-01" // Add entry to stream "events" with auto-generated ID XLEN events // Get stream length XRANGE events - + // Get all entries XREVRANGE events + - // Get entries in reverse order // Read new entries XREAD COUNT 10 STREAMS events 0 // Read from beginning XREAD COUNT 10 STREAMS events $ // Read new entries only // Consumer groups XGROUP CREATE events mygroup 0 // Create consumer group from beginning XGROUP CREATE events mygroup $ // Create consumer group from end XREADGROUP GROUP mygroup consumer1 COUNT 10 STREAMS events > XACK events mygroup 1-0 // Acknowledge message XCLAIM events mygroup consumer2 3600000 1-0 // Claim pending message XPENDING events mygroup // View pending messages
Bitmaps: Efficient Boolean Flags
Bitmaps are arrays of bits for efficient boolean operations. They're perfect for tracking user states, feature flags, and analytics. Bitmaps use minimal memory — one bit per user. They support SETBIT, GETBIT, BITCOUNT, and BITOP. Bitmaps are efficient for large-scale analytics because they use only 1 bit per user.
Bitmaps are implemented as Redis strings, so they can be up to 512MB. Each bit represents a boolean state. BITCOUNT counts the number of set bits. BITOP performs bitwise operations (AND, OR, XOR, NOT) across multiple bitmaps. This enables complex analytics like computing daily active users, weekly active users, and retention rates.
Use bitmaps for tracking daily active users, feature flags, and any boolean state. For example, you can track which users logged in on each day, then compute DAU, WAU, and MAU with bit operations. Bitmaps are extremely memory-efficient and fast.
// Bitmap operations SETBIT users:daily:2024-01-01 100 1 // Set bit 100 (user 100 was active) GETBIT users:daily:2024-01-01 100 // Check if user 100 was active BITCOUNT users:daily:2024-01-01 // Count active users today // Multiple days - compute DAU, WAU SETBIT users:daily:2024-01-01 100 1 SETBIT users:daily:2024-01-02 100 1 BITOP AND users:both users:daily:2024-01-01 users:daily:2024-01-02 BITCOUNT users:both // Count users active both days // Feature flags SETBIT features:new_ui 0 1 // Enable feature for user 0 SETBIT features:new_ui 1 0 // Disable for user 1 GETBIT features:new_ui 0 // Check if user 0 has feature
HyperLogLog: Cardinality Estimation
HyperLogLog estimates the number of unique items in a set with minimal memory. It uses very little memory (12KB for 2^64 elements). It's perfect for unique visitor counting. HyperLogLog is probabilistic with a small error margin (typically 0.81%). Use it for approximate counting where exact counts aren't critical.
HyperLogLog is implemented as a probabilistic data structure that provides cardinality estimation with constant memory. PFADD adds elements. PFCOUNT returns the estimated cardinality. PFMERGE combines multiple HyperLogLogs. HyperLogLog is ideal for counting unique visitors, unique search terms, and any cardinality estimation.
// HyperLogLog operations PFADD visitors:day1 "user1" "user2" "user3" PFCOUNT visitors:day1 // Returns 3 (estimated unique count) // Multiple days PFADD visitors:day2 "user2" "user3" "user4" PFCOUNT visitors:day1 visitors:day2 // Returns 4 (combined unique count) // Merge PFMERGE visitors:all visitors:day1 visitors:day2 PFCOUNT visitors:all // Returns 4 (unique visitors across days) // Use case: daily active users PFADD daily:active:2024-01-01 "user1" "user2" PFADD daily:active:2024-01-02 "user2" "user3" PFCOUNT daily:active:2024-01-01 // DAU estimate
Geospatial Indexes: Location-Based Queries
Geospatial indexes support location-based queries. You can store longitude/latitude pairs and query nearby points. Geospatial indexes use a 2D sphere index. They support GEOADD, GEODIST, GEORADIUS, and GEOSEARCH. Use them for location-based applications.
Geospatial indexes are implemented using a geohash approach, storing locations in a sorted set. This enables efficient proximity searches. GEODIST calculates distance between points. GEORADIUS finds points within a radius. GEOSEARCH provides more flexible search options. Geospatial is essential for location-based applications.
// Geospatial operations GEOADD locations 13.361389 38.115556 "Palermo" GEOADD locations 15.087269 37.502669 "Catania" GEOADD locations 13.2 38.1 "Naples" GEODIST locations "Palermo" "Catania" km // Distance: 137.2 km GEODIST locations "Palermo" "Catania" m // Distance in meters // Find locations within 50km GEOSEARCH locations FROMLONLAT 13.3 38.1 BYRADIUS 50 km // Find locations within a bounding box GEOSEARCH locations FROMLONLAT 13.3 38.1 BYBOX 50 50 km // Get all locations with distance GEORADIUS locations 13.3 38.1 100 km WITHCOORD WITHDIST
Knowledge Check
Ready to test your understanding of 4. Advanced Data Structures: Streams, Bitmaps, HyperLogLog & Geospatial?