Learn Redis · 8/15

Beyond Basics: Specialized Data Structures

8 min read

Beyond Basics: Specialized Data Structures in Redis

Welcome back! You've mastered the basic Redis data structures like Strings, Lists, Hashes, Sets, and Sorted Sets. Now, it's time to venture into the more specialized, and frankly, quite magical, data structures that Redis offers. These tools are designed to solve very specific, yet common, problems with incredible efficiency. Let's dive in! 🚀


1. Bitmaps: Ultra-efficient Boolean Storage 📊

The Problem: Tracking Daily Active Users

Imagine you're running a popular application and you want to track which users are active each day. A straightforward approach would be to store each active user's ID in a Set for each day. For example, for 2026-02-25, you might have a Set containing {'user:1', 'user:305', 'user:876'}.

This works, but think about the scale. If you have millions of users, these Sets can consume a significant amount of memory, especially over a long period. What if you only need to know if a user was active (a yes/no or 1/0 question), not the list of all active users for that day?

The Solution: Bitmaps

This is where Bitmaps come to the rescue. A Bitmap isn't a new data type in Redis; it's a set of bit-oriented operations on the String type. You can think of a String in Redis as an array of bits.

A Bitmap allows you to set and get the value of individual bits. This is incredibly memory-efficient for storing boolean (true/false) information.

How it works under the hood:

At its core, a Bitmap is just a sequence of bits, like 01101001. You can set the bit at a specific position (offset) to either 0 or 1.

For our daily active users problem, you can have a Bitmap for each day. The user's ID can be the offset in the Bitmap. If user with ID 5 is active on a particular day, you set the bit at offset 5 to 1. If they are not active, it remains 0.

Let's Get Practical with Examples:

Assume we are tracking active users for February 25th, 2026.

  • SETBIT: This command sets the bit at a specific offset to 1 or 0.

    Let's say user with ID 100, 250, and 1000 logged in today.

    bash
    # SETBIT key offset value
    SETBIT active_users:2026-02-25 100 1
    # Output: 0 (the original value of the bit)
    
    SETBIT active_users:2026-02-25 250 1
    # Output: 0
    
    SETBIT active_users:2026-02-25 1000 1
    # Output: 0
  • GETBIT: This checks if a user was active.

    bash
    # GETBIT key offset
    GETBIT active_users:2026-02-25 100
    # Output: 1 (meaning, yes, they were active)
    
    GETBIT active_users:2026-02-25 500
    # Output: 0 (nope, not active)
  • BITCOUNT: This is where the magic happens for analytics. It counts the number of set bits (bits with value 1).

    bash
    # BITCOUNT key [start end]
    BITCOUNT active_users:2026-02-25
    # Output: 3 (our three active users)

    This is incredibly fast and efficient for calculating things like daily active users.

  • BITOP: You can perform bitwise operations (AND, OR, XOR, NOT) between multiple Bitmaps.

    For example, to find out how many users were active on both February 24th and 25th, you would use BITOP AND.

    bash
    # Let's assume we have another bitmap for the previous day
    # BITOP operation destkey key [key ...]
    BITOP AND active_both_days active_users:2026-02-24 active_users:2026-02-25
    
    BITCOUNT active_both_days
    # This will give you the count of users active on both days.

Interesting Fact: 🧐
Bitmaps are so memory efficient that you can store information about over 4 billion users (the number of possible 32-bit unsigned integers) in just 512 MB of RAM.


2. HyperLogLog: Approximating Unique Items with Tiny Memory 🔬

The Problem: Counting Unique Visitors

Let's stick with our popular application. Now, you want to count the number of unique visitors to your website in a day. A Set is a good way to do this; you just add each user's ID to a Set, and the SCARD command gives you the count of unique users.

But what if you have tens of millions of unique visitors daily? Storing each unique user ID in a Set will consume a large amount of memory. Do you really need the exact number, or is a very, very good approximation acceptable?

The Solution: HyperLogLog

HyperLogLog (HLL) is a probabilistic data structure used to estimate the cardinality (the number of unique elements) of a set. The trade-off is that you get an approximate count, but with an incredibly small and constant amount of memory.

How it works under the hood (the simple version):

Imagine you have a bunch of people flipping coins and you want to estimate how many unique people there are. If someone tells you they got a run of 8 heads in a row, it's more likely that many people were flipping coins than if the longest run was just 2 heads. HyperLogLog works on a similar principle but with hashing. It hashes each element you add, and looks at the pattern of leading zeros in the binary representation of the hash. The more leading zeros it observes, the larger the estimated number of unique items.

Let's Get Practical with Examples:

  • PFADD: Adds one or more elements to a HyperLogLog.

    bash
    # PFADD key element [element ...]
    PFADD unique_visitors:2026-02-25 user:1 user:2 user:3 user:4
    # Output: 1 (indicates the estimate was changed)
    
    PFADD unique_visitors:2026-02-25 user:1 user:5 user:6
    # Output: 1

    Notice we added user:1 twice, but it will only be counted once.

  • PFCOUNT: Returns the approximate count of unique items.

    bash
    # PFCOUNT key [key ...]
    PFCOUNT unique_visitors:2026-02-25
    # Output: 6
  • PFMERGE: Merges multiple HyperLogLog structures into one. This is useful for calculating unique visitors over a week or a month.

    bash
    # PFMERGE destkey sourcekey [sourcekey ...]
    PFMERGE unique_visitors:week5 2026-02-24 2026-02-25
    # Now `unique_visitors:week5` contains the estimated unique visitors for those two days.
    
    PFCOUNT unique_visitors:week5

Interesting Fact: 🤯
A Redis HyperLogLog requires only about 12 KB of memory to estimate the cardinality of a set with billions of elements, and it does so with a standard error of just 0.81%. It's like having a statistical superpower!


3. Geospatial Indexes: Storing and Querying Coordinates 🌍

The Problem: Finding Nearby Points of Interest

Imagine you're building a "Find a coffee shop near me" feature. You have the latitude and longitude of thousands of coffee shops. A user provides their current location, and you need to quickly find all the coffee shops within a certain radius.

Doing this with a traditional database can be complex and slow, often requiring specialized and computationally expensive queries.

The Solution: Geospatial Indexes

Redis provides a set of commands to store and query geospatial data efficiently. It uses a Sorted Set as the underlying data structure, with a clever encoding technique called Geohash.

How it works under the hood:

Redis takes the longitude and latitude and encodes them into a single value using Geohash. This Geohash value is then stored as the score in a Sorted Set. The magic of Geohash is that locations that are close to each other have similar prefixes in their Geohash strings. This allows Redis to perform efficient radius queries.

Let's Get Practical with Examples:

  • GEOADD: Adds one or more geospatial items (longitude, latitude, name) to a key.

    bash
    # GEOADD key [NX|XX] [CH] longitude latitude member [longitude latitude member ...]
    GEOADD coffee_shops:sf -122.4194 37.7749 "Blue Bottle"
    # Output: 1
    
    GEOADD coffee_shops:sf -122.408 37.785 "Philz Coffee" -122.432 37.781 "Four Barrel"
    # Output: 2
  • GEOPOS: Returns the longitude and latitude of one or more members.

    bash
    # GEOPOS key member [member ...]
    GEOPOS coffee_shops:sf "Blue Bottle"
    # Output: 1) 1) "-122.41940103769302368"
    #          2) "37.77490056213697925"
  • GEODIST: Returns the distance between two members.

    bash
    # GEODIST key member1 member2 [unit]
    GEODIST coffee_shops:sf "Blue Bottle" "Philz Coffee" km
    # Output: "1.4646" (The distance in kilometers)

4. Finding Nearby Locations using GEOSEARCH 🗺️

While the older GEORADIUS command exists, the more powerful and flexible command for finding nearby locations is GEOSEARCH.

The Problem: Advanced Geospatial Queries

Simple radius searches are great, but what if you want to find all coffee shops within a 5x5 km bounding box around a user? Or what if you want to limit the results to the top 10 closest? This is where GEOSEARCH shines.

Let's Get Practical with Examples:

  • Finding locations within a certain radius:

    Let's find all coffee shops within a 2 km radius of a user located at longitude -122.41 and latitude 37.78.

    bash
    # GEOSEARCH key FROMLONLAT longitude latitude BYRADIUS radius m|km|ft|mi [ASC|DESC] [COUNT count [ANY]] [WITHCOORD] [WITHDIST] [WITHHASH]
    GEOSEARCH coffee_shops:sf FROMLONLAT -122.41 37.78 BYRADIUS 2 km WITHDIST
    # Output:
    # 1) 1) "Philz Coffee"
    #    2) "0.7833"
    # 2) 1) "Blue Bottle"
    #    2) "1.1915"

    The WITHDIST option also returns the distance from the center point.

  • Finding locations within a bounding box:

    Let's find all coffee shops within a 3km by 3km box.

    bash
    # GEOSEARCH key FROMLONLAT longitude latitude BYBOX width height m|km|ft|mi ...
    GEOSEARCH coffee_shops:sf FROMLONLAT -122.41 37.78 BYBOX 3 3 km
  • Sorting and limiting results:

    You can use ASC (ascending) to get the closest locations first and COUNT to limit the number of results.

    bash
    GEOSEARCH coffee_shops:sf FROMLONLAT -122.41 37.78 BYRADIUS 5 km ASC COUNT 1
    # This will return the single closest coffee shop within a 5km radius.

Real-world simulation:
Imagine a ride-sharing app. When you request a ride, the app needs to find the nearest drivers. The drivers' locations are constantly being updated in a Geospatial Index using GEOADD. When you make a request, a GEOSEARCH command is executed with your location to find the closest drivers.


Further Reading and References

Challenge

Challenge: Find Nearby Delivery Drivers

You are building a feature for a food delivery app. The real-time locations of all available drivers are stored in a Redis Geospatial index under the key drivers:available.

A new order has been placed at a restaurant located at longitude -73.9857 and latitude 40.7484.

Your task is to write a single Redis command to find the three closest available drivers within a 5-kilometer radius of the restaurant.

Requirements:

  1. The search must be centered on the restaurant's coordinates.
  2. The search area must be a circle defined by a radius.
  3. The results must be sorted by distance from the restaurant in ascending order.
  4. The query must be limited to return a maximum of three drivers.
  5. In addition to the driver's name (the member), the command's output must also include their distance from the restaurant and their specific coordinates.

Expected result

The correct command uses GEOSEARCH with several options to meet all requirements.

redis
GEOSEARCH drivers:available FROMLONLAT -73.9857 40.7484 BYRADIUS 5 km ASC COUNT 3 WITHDIST WITHCOORD

Breakdown of the Command:

  • GEOSEARCH drivers:available: Specifies the command and the target key containing the geospatial data.
  • FROMLONLAT -73.9857 40.7484: Sets the central point for the search using the provided longitude and latitude.
  • BYRADIUS 5 km: Defines the search shape as a circle with a radius of 5 kilometers.
  • ASC: Sorts the results by distance in ascending order, ensuring the closest drivers are returned first.
  • COUNT 3: Limits the result set to the top 3 matches.
  • WITHDIST: An option to include the calculated distance from the center point in the results.
  • WITHCOORD: An option to include the longitude and latitude of each matching member in the results.
redis

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.