Consider an application that has several million registered users. The application needs to track whether each user has completed registration, enabled two-factor authentication, subscribed to a newsletter, accepted a new policy, or received a particular notification.
Each of these conditions has only two possible values: true or false. A user either completed the activity or did not. A feature is either enabled or disabled.
One straightforward implementation is to store each value as a separate Redis key or as a field in a Redis hash. This works well when the application needs to store additional information alongside the state. However, when the application only needs to remember a large number of true-or-false values, storing a complete key, field, or member for every record can introduce unnecessary storage overhead.
Redis bitmaps provide another option. They allow an application to store many Boolean values inside a single Redis string. Instead of storing a complete value for every user, Redis uses individual bits to represent their states.
This approach is particularly useful for tracking user activity, feature availability, notification delivery, subscription status, and other large collections of binary information.
In this article, we will explore how Redis bitmaps work, how to use their commands, how to integrate them into a C# application, how to perform aggregate operations, and what needs to be considered before using them in production.
Understanding Redis Bitmaps
A bitmap is a collection of individual bits. Each bit can contain only one of two values:
0 represents false, disabled, or not completed.
1 represents true, enabled, or completed.
Redis does not store a bitmap as a separate data type. It uses its existing string data type and provides commands that allow applications to read and modify individual bits within that string.
This is an important distinction. A Redis string normally stores text or binary data, but bitmap commands allow the application to treat the contents as a sequence of bits.
For example, imagine an application assigns every user a numeric identifier. The application can use that identifier as the position of the user's registration flag.
If user 125 completes registration, the application sets bit 125 to 1. If user 126 has not completed registration, the corresponding bit remains 0.
The following commands demonstrate this operation:
SETBIT users:registration 125 1
GETBIT users:registration 125
GETBIT users:registration 126
The first command sets the bit at offset 125 to 1. The second command reads the same bit and returns 1. The third command reads offset 126 and returns 0 if that position has not previously been set.
The offset is zero-based. This means the first bit has offset 0, the second bit has offset 1, and the 126th bit has offset 125.
Redis automatically extends the string when an application writes to an offset beyond its current length. Any intermediate bits that were not previously initialized are treated as zero.
This behavior makes it possible to start with an empty bitmap and gradually add flags without creating a separate record for every user.
How Bitmap Storage Reduces Memory Usage
The main advantage of bitmaps is that each Boolean value requires only one bit.
A bit is the smallest unit of information in computer storage. Eight bits make one byte. Therefore, a bitmap can represent eight independent Boolean values in a single byte.
Consider an application that needs to track the registration status of one million users.
If the application stores one flag per user, the bitmap requires:
1,000,000 bits / 8 = 125,000 bytes
This is approximately 122.07 KiB of raw bitmap data.
The following table shows the approximate storage required for different numbers of flags.
Number of flags | Raw bitmap storage |
|---|
10,000 | 1.22 KiB |
100,000 | 12.21 KiB |
1,000,000 | 122.07 KiB |
10,000,000 | 1.19 MiB |
100,000,000 | 11.92 MiB |
These calculations describe the bitmap data itself. They do not include the Redis key, object metadata, allocator overhead, replication, or other memory used by the Redis deployment.
To understand the difference, compare a bitmap with a Redis hash.
A hash might store the user ID as a field and a Boolean value as the field's content. This is convenient because the application can retrieve individual fields by their names. However, every field requires a representation of its identifier and value, along with the internal storage overhead associated with the hash.
A bitmap does not need to store the identifier repeatedly when the identifier can be used directly as the bit offset. The position itself identifies which user the flag belongs to.
This is why bitmaps can be significantly more memory-efficient for dense collections of Boolean states.
However, memory savings depend on the distribution of identifiers. A bitmap containing a few flags at very large offsets can consume more memory than expected. The application must consider how densely its offsets are populated before choosing this approach.
Designing a Bitmap Key Structure
A bitmap implementation should begin with a clear mapping between business entities and bit positions.
Suppose an application needs to track three independent user properties:
Whether the user has completed identity verification.
Whether the user has subscribed to a newsletter.
Whether the user has access to a beta feature.
One possible key structure is:
users:identity-verified
users:newsletter-subscribed
users:beta-access
Each Redis key represents one type of Boolean state. The bit offset represents the user.
For example, user 125 can have different values in all three bitmaps:
SETBIT users:identity-verified 125 1
SETBIT users:newsletter-subscribed 125 1
SETBIT users:beta-access 125 0
The application can read the values independently:
GETBIT users:identity-verified 125
GETBIT users:newsletter-subscribed 125
GETBIT users:beta-access 125
This design is easy to understand because each bitmap has one responsibility. It also makes it possible to perform aggregate operations on a particular property without processing unrelated user information.
The identifier mapping is especially important.
If user IDs are sequential integers, using them as offsets may be practical. However, if user identifiers are UUIDs or random strings, the application cannot use those values directly as bit positions. It would need a separate mapping that assigns each user a compact numeric identifier.
For example, an application could maintain a database table that maps a UUID to an internal integer ID. The integer ID can then be used as the bitmap offset.
This mapping must remain stable. If an identifier is reassigned to another user, the new user could inherit the previous user's bitmap state. A reliable mapping strategy is therefore part of the bitmap design, not just an implementation detail.
Working With Redis Bitmaps in C#
The StackExchange.Redis library provides methods for accessing Redis bitmap operations through its string commands.
First, install the package in your .NET project:
dotnet add package StackExchange.Redis
The application needs a Redis connection before it can perform bitmap operations. In an ASP.NET Core application, the connection multiplexer should normally be registered as a singleton because it is designed to be shared across the application.
For example, add the Redis connection string to the application configuration:
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}
Register the connection through dependency injection:
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IConnectionMultiplexer>(serviceProvider =>
{
var configuration =
builder.Configuration.GetConnectionString("Redis");
if (string.IsNullOrWhiteSpace(configuration))
{
throw new InvalidOperationException(
"Redis connection string is missing.");
}
return ConnectionMultiplexer.Connect(configuration);
});
builder.Services.AddScoped<UserRegistrationBitmap>();
var app = builder.Build();
app.Run();
The connection multiplexer manages connections to Redis and can be reused by multiple application services. Creating a new multiplexer for every request is generally unnecessary and can introduce connection-management overhead.
Now create a service that manages registration flags.
using StackExchange.Redis;
public class UserRegistrationBitmap
{
private readonly IDatabase _database;
private const string BitmapKey = "users:registration";
public UserRegistrationBitmap(
IConnectionMultiplexer redis)
{
_database = redis.GetDatabase();
}
public async Task<bool> SetRegistrationStatusAsync(
long userId,
bool isRegistered)
{
return await _database.StringSetBitAsync(
BitmapKey,
userId,
isRegistered);
}
public async Task<bool> IsRegisteredAsync(long userId)
{
return await _database.StringGetBitAsync(
BitmapKey,
userId);
}
}
The service uses the user ID as the bit offset. When SetRegistrationStatusAsync receives true, Redis sets the corresponding bit to 1. When it receives false, Redis clears that bit and sets it to 0.
The IsRegisteredAsync method reads the bit and returns its Boolean value. If the bit has never been written, Redis returns false because an unset bit is treated as zero.
There is one important detail about StringSetBitAsync: its return value represents the previous value of the bit, not whether the command executed successfully. For example, if the bit was already 1 and the application sets it to 1 again, the method returns true because the previous value was true.
This behavior can be useful when the application needs to determine whether a flag changed.
The service can now be used by another application component:
public class RegistrationService
{
private readonly UserRegistrationBitmap _bitmap;
public RegistrationService(
UserRegistrationBitmap bitmap)
{
_bitmap = bitmap;
}
public async Task RegisterUserAsync(long userId)
{
await _bitmap.SetRegistrationStatusAsync(
userId,
true);
}
public async Task<bool> IsUserRegisteredAsync(long userId)
{
return await _bitmap.IsRegisteredAsync(userId);
}
}
This separation keeps Redis-specific operations inside the bitmap service. The registration service can focus on business rules without needing to know how the state is physically represented in Redis.
For a production application, the service should also validate that the supplied identifier is non-negative and within the application's supported range. It should use the correct Redis database, connection configuration, and error-handling strategy for the deployment.
Counting Flags With BITCOUNT
Reading individual bits is useful when an application needs to check one user's state. However, many applications also need aggregate information.
For example, an administrator may want to know how many users have completed registration. One option would be to retrieve all user records and count the registered users in the application. That approach transfers data from Redis to the application and requires additional processing.
Redis provides the BITCOUNT command to count the number of bits set to 1 in a bitmap.
BITCOUNT users:registration
If the bitmap contains 750,000 set bits, the command returns 750,000.
The application can perform this calculation directly in Redis through StackExchange.Redis:
public async Task<long> GetRegisteredUserCountAsync()
{
return await _database.StringBitCountAsync(
BitmapKey);
}
The method returns a long because the number of set bits can be much larger than the range of a 32-bit integer.
BITCOUNT also supports counting bits within a specified byte range. This can be useful when an application divides users into known ranges and needs a count for only one part of the bitmap.
It is important to understand that the range refers to bytes, not individual bit offsets. When calculating a range, the application must convert the relevant bit positions into byte positions.
For example, if the application needs to inspect the first 8,000 bits, those bits occupy the first 1,000 bytes. The corresponding byte range is from 0 to 999.
For very large bitmaps, counting the entire structure may require processing a significant amount of data. If the application performs this operation frequently, it should measure its effect on Redis and consider maintaining aggregate counts separately when the business requirements justify the added complexity.
Finding the First Set or Unset Bit With BITPOS
Sometimes an application needs to find the first position that matches a particular state.
For example, a notification system may need to identify the first user who has not yet received a notification. Reading every bit individually would require many Redis requests.
Redis provides BITPOS for this purpose.
The command searches for the first occurrence of the specified bit value:
BITPOS users:notification-sent 0
This searches for the first zero bit.
To find the first set bit, use:
BITPOS users:notification-sent 1
The command can also accept a byte range, allowing the application to search within a selected portion of the bitmap.
A C# implementation can use the corresponding StackExchange.Redis string operation:
public async Task<long> FindFirstUnnotifiedUserAsync()
{
return await _database.StringBitPositionAsync(
"users:notification-sent",
false);
}
The result is the bit offset where the requested value first appears. If no matching bit is found within the searched range, Redis returns -1.
An application should not assume that the first zero bit always represents an active user who needs a notification. The bitmap only represents the state associated with each position. If some user IDs are unused, deleted, or reserved, the application must check those conditions separately.
This is an important distinction between finding a bit and identifying a valid business entity.
Combining Multiple Conditions With BITOP
A bitmap becomes more powerful when the application needs to combine several Boolean conditions.
Consider a feature rollout system. The application wants to enable a feature only for users who satisfy two conditions:
The application maintains two separate bitmaps:
users:beta-access
users:identity-verified
It can combine these bitmaps using the AND operation.
BITOP AND users:eligible users:beta-access users:identity-verified
Redis creates the destination bitmap named users:eligible. A bit is set in the destination only when the corresponding bit is set in both source bitmaps.
For example, if user 125 has beta access and has completed identity verification, the resulting bit at offset 125 is 1. If either condition is false, the resulting bit is 0.
Redis supports several bitwise operations:
Operation | What it does | Example use |
|---|
AND | Sets a result bit only when all corresponding source bits are 1 | Users who satisfy every required condition |
OR | Sets a result bit when at least one corresponding source bit is 1 | Users who belong to one or more groups |
XOR | Sets a result bit when the corresponding source bits are different | Finding differences between two states |
NOT | Inverts the bits in the source bitmap | Producing the opposite binary state |
For example, OR can combine two notification groups:
BITOP OR users:notification-targets users:group-a users:group-b
The resulting bitmap identifies users who belong to either group.
XOR can help identify positions where two bitmaps differ:
BITOP XOR users:changed users:previous-status users:current-status
A set bit in the result indicates that the corresponding position has different values in the two source bitmaps.
These operations can reduce the amount of data that needs to be transferred to the application. However, they should be used with care because Redis must process the source bitmap data and write the result to a destination key.
For large datasets, these operations can consume noticeable server resources. Also, the destination key is overwritten by the result, so it should not be one of the source keys unless that behavior is specifically intended.
In Redis Cluster, all keys used by a multi-key operation must be accessible on the same node. Applications should plan key names and hash tags accordingly if they need to perform BITOP across multiple related keys.
Managing Large and Sparse Bitmaps
One of the most important bitmap design decisions is how the application assigns offsets.
A bitmap is efficient when the positions are reasonably dense. It can become wasteful when the application sets only a few bits at very large offsets.
Imagine that an application has one million users, but their external identifiers are randomly generated numbers. One user might have ID 125, while another might have ID 900,000,000.
If the application uses those identifiers directly as bit offsets, setting the second user's flag requires Redis to allocate enough string space to reach that position.
Even if only two bits are set, the bitmap must contain all the bytes between the beginning and the highest offset.
This is known as a sparse bitmap problem.
Redis strings support a maximum size of 512 MB, corresponding to 2^32 bits. That is a technical limit, not a recommendation to store every application flag in one enormous bitmap.
For larger applications, dividing the bitmap into smaller segments can provide better control over memory allocation and key distribution.
Suppose the application assigns one million bit positions to each segment. The segment number and position within the segment can be calculated from the user ID.
public static class BitmapAddress
{
public const long BitsPerSegment = 1_000_000;
public static long GetSegmentNumber(long userId)
{
return userId / BitsPerSegment;
}
public static long GetBitOffset(long userId)
{
return userId % BitsPerSegment;
}
public static string GetKey(long userId)
{
long segment = GetSegmentNumber(userId);
return $"users:registration:{segment}";
}
}
Consider user ID 2,500,123.
The segment number is 2, and the offset within that segment is 500,123.
The application therefore stores the flag in:
users:registration:2
at bit offset 500,123.
The Redis operation can be implemented as follows:
public async Task SetRegistrationStatusAsync(
long userId,
bool isRegistered)
{
if (userId < 0)
{
throw new ArgumentOutOfRangeException(
nameof(userId));
}
string key = BitmapAddress.GetKey(userId);
long offset = BitmapAddress.GetBitOffset(userId);
await _database.StringSetBitAsync(
key,
offset,
isRegistered);
}
This example assumes that user IDs are non-negative and that the application uses the same segment calculation whenever it reads or writes a user's state.
Segmentation does not eliminate the need for careful identifier design. It simply divides a large logical bitmap into multiple Redis keys. The application must still ensure that IDs map consistently to the same segment and offset.
For Redis Cluster, segmentation can also help distribute keys across nodes. However, if an operation needs to combine multiple segments, the application must account for the fact that multi-key commands cannot freely operate across different cluster nodes.
Handling Multiple Updates Efficiently
An application may need to update bitmap flags for many users at once. Sending one Redis request for every user can introduce unnecessary network overhead.
For example, imagine a background job that imports 50,000 user registration records. It needs to update the registration bitmap based on the imported data.
Instead of waiting for every Redis operation to complete individually, the application can use pipelining through StackExchange.Redis.
public async Task UpdateRegistrationStatusesAsync(
IEnumerable<(long UserId, bool IsRegistered)> users)
{
var tasks = users.Select(user =>
_database.StringSetBitAsync(
BitmapKey,
user.UserId,
user.IsRegistered));
await Task.WhenAll(tasks);
}
This example starts multiple asynchronous operations and waits for their completion. StackExchange.Redis can send queued commands efficiently, reducing the need for the application to wait for each individual round trip.
However, this approach should not be used without considering batch size. Creating hundreds of thousands of outstanding tasks at once can increase application memory usage and place unnecessary pressure on Redis.
For large imports, process records in controlled batches. For example, the application could process a few hundred or a few thousand updates at a time, depending on command size, network latency, Redis capacity, and application memory.
It is also important to understand that pipelining does not make the entire batch a single atomic operation. If one command fails while others succeed, the application must handle the partial result according to its business requirements.
Choosing Between Bitmaps, Hashes, and Sets
Bitmaps are useful for binary information, but they are not suitable for every kind of Redis data.
The correct structure depends on how the application accesses its data and how identifiers are distributed.
Requirement | Recommended structure | Reason |
|---|
Track Boolean states for dense numeric identifiers | Bitmap | Uses one bit per state |
Store several properties for each user | Hash | Supports multiple fields and values |
Store arbitrary identifiers without numeric mapping | Set | Stores members directly |
Maintain an ordered activity history | Stream or sorted set | Supports event or ordering requirements |
Calculate intersections between binary groups | Bitmap | Supports bitwise operations |
Store detailed user activity records | Database or stream | Preserves individual events and additional information |
For example, a bitmap can tell an application whether a user completed registration. It cannot tell the application when registration happened, which verification method was used, or why registration failed.
If the application needs those details, it should store them in a database or another appropriate structure. The bitmap can still be used as a compact lookup or aggregate representation.
This is often a useful production design: keep detailed business records in the primary database and use Redis bitmaps for fast binary checks where their compact representation provides a measurable benefit.
Production Considerations
Before introducing bitmaps into a production system, developers should evaluate more than the raw memory calculation.
Identifier stability
The bit offset must consistently represent the same entity. If user IDs can be reused, the application must clear or replace the previous state before assigning that position to another user.
Sparse identifier ranges
A bitmap is not automatically memory-efficient when identifiers are widely distributed. A few high offsets can require a large amount of allocated string space. Measure the distribution of identifiers before deciding to use them directly as offsets.
Key organization
Use meaningful key names that identify the business property being stored. Separate independent flags into separate bitmaps so that updates and aggregate operations remain understandable.
Data durability
A bitmap stored in Redis is still Redis data. If the flags represent important business state, configure persistence, replication, backups, and recovery procedures according to the application's requirements.
For critical information, do not make Redis the only place where the business state exists unless the architecture explicitly supports that decision.
Concurrent updates
Individual Redis bit operations are atomic. Two clients updating different bit positions do not need to retrieve and rewrite the entire bitmap. However, a larger workflow involving multiple bitmaps, database records, or external services is not automatically atomic.
If the application needs several updates to succeed together, use an appropriate transaction or application-level consistency strategy.
Monitoring and performance
Monitor actual memory usage, command latency, CPU utilization, and the size of bitmap keys. BITCOUNT and BITOP are useful operations, but repeatedly processing very large bitmaps can affect Redis performance.
Benchmark with realistic data distributions and workloads rather than relying only on theoretical storage calculations.
Data cleanup
If users are deleted or become inactive, decide what should happen to their bitmap positions. Clearing a bit does not necessarily reduce the size of the Redis string. If a bitmap has grown to a large offset, clearing individual bits will not automatically shrink it.
For segmented bitmaps, the application can remove an entire segment when it is no longer required, provided no valid user data remains in that segment.
Conclusion
Redis bitmaps provide a compact way to represent large collections of Boolean states. By storing each state as one bit inside a Redis string, an application can avoid the overhead of maintaining a separate key or field for every flag.
Commands such as SETBIT and GETBIT support individual updates and checks. BITCOUNT can count enabled flags without transferring the entire bitmap to the application, while BITPOS can locate a particular bit value. BITOP allows applications to combine multiple conditions directly within Redis.
The biggest design consideration is the relationship between business identifiers and bit offsets. Dense, stable numeric identifiers are a good fit for bitmaps. Random or widely distributed identifiers may create sparse bitmaps that consume more memory than expected.
For production applications, use bitmaps when the data is genuinely binary, keep the identifier mapping stable, segment large collections when appropriate, and measure actual Redis memory and command performance. When the application needs detailed records, arbitrary identifiers, or rich user attributes, hashes, sets, streams, or a database may be a better choice.
Join the conversation! Your thoughts help the community grow.