How to Track Online Users with Redis Sorted Sets (zset)
This article explains how to implement an online user counting feature using Redis sorted sets, covering user identification methods, the essential zadd, zrangeByScore, zremrangeByScore, and zrem commands, along with code examples for both Java and JavaScript.
Online user counting can be efficiently implemented with Redis sorted sets (zset). The core Redis commands used are zadd, zrangeByScore, zremrangeByScore, and zrem.
1. Determine if a user is online
If the site requires login, user online status can be judged by the validity of the token. For public sites, a rule such as browser fingerprinting can be used, which combines User-Agent, HTTP headers, screen resolution, timezone, language, and plugins. Libraries like FingerprintJS or ClientJS simplify this process.
// Install: npm install @fingerprintjs/fingerprintjs
// Usage example:
import FingerprintJS from '@fingerprintjs/fingerprintjs';
FingerprintJS.load().then(fp => {
fp.get().then(result => {
const visitorId = result.visitorId;
console.log(visitorId);
});
});The obtained unique ID can be stored in a cookie or header and sent to the backend.
2. Add online user with zadd
zadd command introduction
The command takes three parameters:
key – the name of the sorted set.
score – a numeric value (integer or double) representing the expiration timestamp.
member – the identifier of the user (e.g., token or fingerprint).
Example: ZADD myzset 1 "one" In Java, adding a user token with an expiration score can be done as follows:
LocalDateTime expireTime = LocalDateTime.now().plusSeconds(expireTimeout);
String expireTimeStr = DateUtil.formatFullTime(expireTime);
redisService.zadd("user.active", Double.parseDouble(expireTimeStr), userToken);This ensures each user has only one latest entry.
3. Query online users with zrangeByScore
zrangeByScore command introduction
key – the sorted set name.
min and max – the score range (can use -inf and +inf).
Example to get members with scores between 1 and 3: ZRANGEBYSCORE myzset 1 3 To obtain the current online users:
String now = DateUtil.formatFullTime(LocalDateTime.now());
Set<String> userOnlineStringSet = redisService.zrangeByScore("user.active", now, "+inf");
// The size of userOnlineStringSet is the online count.4. Periodically clean expired users with zremrangeByScore
zremrangeByScore command introduction
key – the sorted set name.
min and max – the score range to delete.
Example to delete members with scores between 1 and 3: ZREMRANGEBYSCORE myzset 1 3 Scheduled task example:
String now = DateUtil.formatFullTime(LocalDateTime.now());
redisService.zremrangeByScore("user.active", "-inf", now);5. Remove user on logout with zrem
zrem command introduction
key – the sorted set name.
members – the members to delete.
Example:
ZREM myzset "xxx" redisService.zrem("user.active", "xxx");Conclusion
The core idea is to create a sorted set where the member is the user identifier and the score is the expiration timestamp. Adding, querying, and cleaning this set with the four Redis commands provides a simple yet effective way to track online users.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
