Elegant Ways to Implement Online User Counting with Redis ZSET
This article explains how to use Redis sorted sets (ZSET) together with user token or browser fingerprint identification to add, query, and clean online user entries, providing a simple yet effective method for counting active users in real time.
Introduction
Online user counting is a common requirement; many implementations exist. This article shows a practical approach using Redis sorted sets (ZSET).
Implementation Steps
1. Determining Whether a User Is Online
If the site requires login, the validity of the user's token indicates online status. For public sites, a rule such as browser fingerprint can be used. Browser fingerprint may include User-Agent, HTTP headers, screen resolution, timezone, language, plugins, etc. Libraries like FingerprintJS or ClientJS simplify generating a unique identifier.
import FingerprintJS from '@fingerprintjs/fingerprintjs';
// Initialize
FingerprintJS.load().then(fp => {
// Get visitor ID
fp.get().then(result => {
const visitorId = result.visitorId;
console.log(visitorId);
});
});The identifier is stored in a cookie or header and sent to the backend, where it serves as the member of the ZSET.
2. Adding an Online User with ZADD
The ZADD command takes three arguments: key, score, member. Example:
ZADD myzset 1 "one"In the implementation, the score is the expiration timestamp (current time plus a timeout). Adding a token:
// expireTime = now + expireTimeout seconds
String expireTimeStr = DateUtil.formatFullTime(expireTime);
redisService.zadd("user.active", Double.parseDouble(expireTimeStr), userToken);Because the score is unique per login, repeated logins replace the previous entry, ensuring a single latest record per user.
3. Querying Online Users with ZRANGEBYSCORE
ZRANGEBYSCORE retrieves members whose scores fall within a range. Example:
ZRANGEBYSCORE myzset 1 3To get all currently online users, query from the current timestamp to +inf:
String now = DateUtil.formatFullTime(LocalDateTime.now());
Set<String> userOnlineStringSet = redisService.zrangeByScore("user.active", now, "+inf");
int onlineCount = userOnlineStringSet.size();4. Periodic Cleanup with ZREMRANGEBYSCORE
ZREMRANGEBYSCORE removes members whose scores lie in a given range. Example:
ZREMRANGEBYSCORE myzset 1 3A scheduled task deletes entries whose expiration time is earlier than now:
String now = DateUtil.formatFullTime(LocalDateTime.now());
// Remove entries with score between -inf and now
redisService.zremrangeByScore("user.active", "-inf", now);5. Removing a User on Logout with ZREM
ZREM deletes specific members from the ZSET. Example:
ZREM myzset "xxx"When a user logs out, the backend calls:
redisService.zrem("user.active", "xxx");Conclusion
The core idea is to maintain a ZSET where the key represents the online‑user set, each member is a unique user identifier, and the score is the expiration timestamp. Adding, querying, and cleaning the set provides a simple yet effective online‑user counter.
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.
Programmer XiaoFu
xiaofucode.com – a programmer learning guide driven by the pursuit of profit
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.
