Mastering Redis BitMap for Efficient Sign‑In and Statistics in Spring Boot

This article explains how to implement a memory‑efficient sign‑in feature and continuous‑sign‑in statistics using Redis BitMap, covering basic commands, Spring Boot integration, key design, code examples, and advanced use cases such as cache‑penetration mitigation, providing step‑by‑step guidance for backend developers.

Architect
Architect
Architect
Mastering Redis BitMap for Efficient Sign‑In and Statistics in Spring Boot

Introduction

In many projects we need sign‑in and statistics functions. After signing in users receive gifts to encourage activity.

1. Redis BitMap Basic Usage

BitMap syntax and commands

Sign‑in data stored in a relational table consumes large memory; each record may use 22 bytes, leading to huge storage for millions of users.

Using Redis BitMap, each sign‑in is represented by a single bit (0 or 1), reducing storage to 2 bytes for 31 bits.

BitMap commands:

SETBIT : set a bit at a given offset to 0 or 1

GETBIT : get the bit value at a given offset

BITCOUNT : count bits set to 1

BITFIELD : query/modify/increment bits

BITFIELD_RO : read bitfield as unsigned decimal

BITOP : perform bitwise operations on multiple bitmaps

BITPOS : find first occurrence of 0 or 1 in a range

Implementing sign‑in with BitMap

Redis version 6.2. Example commands are shown with screenshots.

Key creation and SETBIT usage.

GETBIT query.

Check sign‑in status.

BITFIELD query.

BITPOS query for first 0 or 1.

2. Spring Boot Integration

Requirement

Use BitMap to implement a sign‑in API that stores today’s sign‑in information in Redis.

Idea: Use year and month as the BitMap key; each day corresponds to a bit. Setting the bit to 1 marks a sign‑in.

Core source code

UserController

@PostMapping("sign")
public Result sign() {
    return userService.sign();
}

UserServiceImpl

public Result sign() {
    // 1. Get logged‑in user
    Long userId = UserHolder.getUser().getId();
    // 2. Get current date
    LocalDateTime now = LocalDateTime.now();
    // 3. Build key: USER_SIGN_KEY + userId + yyyyMM
    String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
    String key = RedisConstants.USER_SIGN_KEY + userId + keySuffix;
    // 4. Day of month (offset)
    int dayOfMonth = now.getDayOfMonth();
    // 5. Set bit to 1
    stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
    return Result.ok();
}

Testing with ApiFox and viewing Redis data (screenshots).

3. Sign‑in Statistics

What is continuous sign‑in days?

Count days from the latest sign‑in backwards until the first missed day.

How to get all sign‑in data up to today?

BITFIELD key GET u[dayOfMonth] 0

For example, on the 7th day retrieve the first 7 bits and count the ones.

How to traverse bits from right to left?

BitMap returns a decimal number; use bitwise AND with 1 and right‑shift to examine each bit sequentially.

API to get continuous sign‑in count:

@GetMapping("/signCount")
public Result signCount() {
    // similar key construction
    // retrieve bitfield as unsigned integer
    // iterate bits, counting consecutive ones
    // return count
}

Test results show correct continuous sign‑in count.

4. Using BitMap to Prevent Cache Penetration

Cache penetration occurs when requests query non‑existent data, causing repeated database hits.

Solution: store the existence of IDs in a BitMap using a hash function (id % bitmapSize) to set a bit. Checking the bit quickly determines if the ID likely exists, reducing database load. Note the false‑positive rate due to hash collisions.

Conclusion

The article demonstrates how to use Redis BitMap with Spring Boot to implement efficient sign‑in and statistical features, and how BitMap can also help mitigate cache‑penetration problems.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentredisSpring BootBitmapcache-penetrationSign-in
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.