Databases 7 min read

Implementing Online User Counting with Redis Sorted Sets (ZSET)

This article explains how to track online users by storing their identifiers in a Redis sorted set, using expiration timestamps as scores, and demonstrates adding, querying, and cleaning up entries with ZADD, ZRANGEBYSCORE, ZREMRANGEBYSCORE, and ZREM commands in both Java and JavaScript.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Implementing Online User Counting with Redis Sorted Sets (ZSET)

1. Introduction

Online user statistics is a common requirement; this article shows how to implement it using Redis sorted sets (ZSET).

2. Core Redis Commands

The four essential commands are zadd , zrangeByScore , zremrangeByScore , and zrem .

3. Determining Whether a User Is Online

For authenticated sites, token validity is used; for public sites, a unique identifier can be generated via browser fingerprinting (e.g., FingerprintJS or ClientJS). Example JavaScript code is provided.

// 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);
  });
});

4. Adding an Online User

Use zadd with the key (e.g., "user.active"), a score representing the expiration timestamp, and the user token as the member. Java example shown.

LocalDateTime expireTime = LocalDateTime.now().plusSeconds(expireTimeout);
String expireTimeStr = DateUtil.formatFullTime(expireTime);
redisService.zadd("user.active", Double.parseDouble(expireTimeStr), userToken);

5. Querying Online Users

Use zrangeByScore with a minimum of the current time and a maximum of +inf to retrieve all active members; the set size equals the online count.

String now = DateUtil.formatFullTime(LocalDateTime.now());
Set
userOnlineStringSet = redisService.zrangeByScore("user.active", now, "+inf");

6. Removing Expired Users

Schedule a task that calls zremrangeByScore with a range from -inf to the current time to delete stale entries.

String now = DateUtil.formatFullTime(LocalDateTime.now());
redisService.zremrangeByScore("user.active", "-inf", now);

7. Removing a User on Logout

When a user logs out, call zrem to delete the member from the set.

redisService.zrem("user.active", "xxx");

Conclusion

The approach creates a ZSET where the key is the online‑user set, members are user identifiers, and scores are expiration timestamps, enabling simple add, query, and cleanup operations.

JavaJavaScriptBackend DevelopmentRedissorted setOnline Users
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login 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.