Backend Development 8 min read

Implementing Online User Count with Redis Sorted Sets in Java

This article explains how to build an online user counting feature by leveraging Redis sorted sets (zset) in Java, covering user identification, the core Redis commands (zadd, zrangeByScore, zremrangeByScore, zrem), code examples, and periodic cleanup logic.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Implementing Online User Count with Redis Sorted Sets in Java

1. Introduction

Online user counting is a common requirement, and it can be implemented in many ways; this guide focuses on using Redis sorted sets (zset). The core Redis commands involved are zadd , zrangeByScore , zremrangeByScore , and zrem .

2. Implementation Steps

1. How to determine if a user is online?

If the site requires login, online status can be judged by the validity of the user's token. For public sites without login, a custom rule such as IP, deviceId, or browser fingerprint is needed; using a browser fingerprint is recommended.

A browser fingerprint may combine information like the User-Agent string, HTTP headers, screen resolution, color depth, timezone, language settings, and installed plugins. JavaScript libraries such as FingerprintJS or ClientJS simplify the collection and generation of a unique identifier.

Typical usage example:

// install
// npm install @fingerprintjs/fingerprintjs

// usage example
import FingerprintJS from '@fingerprintjs/fingerprintjs';

// initialize the library
FingerprintJS.load().then(fp => {
  // get visitor ID
  fp.get().then(result => {
    const visitorId = result.visitorId;
    console.log(visitorId);
  });
});

The obtained visitor ID can be stored in a cookie or request header and sent to the backend, where the service uses it to identify the user.

2. zadd command to add an online user

1) zadd command description

key: name of the sorted set.

score: a numeric value (integer or double) representing the expiration timestamp.

member: the element to add to the set (e.g., a user token).

Example: add a member to a set named myzset . ZADD myzset 1 "one"

2) Add online user identifier to the sorted set

// expireTime gives the token an expiration time
LocalDateTime expireTime = LocalDateTime.now().plusSeconds(expireTimeout);
String expireTimeStr = DateUtil.formatFullTime(expireTime);
// add user token to the sorted set
redisService.zadd("user.active", Double.parseDouble(expireTimeStr), userToken);

If a user logs in multiple times, the same userToken may appear repeatedly, but the score (expiration time) ensures that only the latest login is counted.

The logic is to use the current time plus a timeout as the score, guaranteeing that each user has at most one latest entry.

3. zrangeByScore command to query online users

1) zrangeByScore description

key: name of the sorted set.

min and max: score range to query; can use -inf and +inf for unbounded ranges.

Example: retrieve members with scores between 1 and 3. ZRANGEBYSCORE myzset 1 3

2) Query all currently online users

// get current timestamp
String now = DateUtil.formatFullTime(LocalDateTime.now());
// query all members with score from now to +inf
Set
userOnlineStringSet = redisService.zrangeByScore("user.active", now, "+inf");

The size of userOnlineStringSet equals the number of online users.

4. zremrangeByScore command to periodically clean offline users

1) zremrangeByScore description

key: name of the sorted set.

min and max: score range to remove; can use -inf and +inf .

Example: delete members with scores between 1 and 3. ZREMRANGEBYSCORE myzset 1 3

2) Periodic cleanup implementation

// get current timestamp
String now = DateUtil.formatFullTime(LocalDateTime.now());
// remove all members with score from -inf up to now
redisService.zremrangeByScore("user.active", "-inf", now);

A scheduled task is needed because sorted sets do not automatically purge expired entries.

5. zrem command to delete a member when a user logs out

1) zrem command description

key: name of the sorted set.

members: one or more members to remove.

Example: delete a member named xxx . ZREM myzset "xxx"

2) Delete on logout

// remove the member when the user logs out
redisService.zrem("user.active", "xxx");

Removing the entry ensures that the user is no longer counted as online.

3. Summary

The core idea is to create a sorted set keyed by online users, store each user identifier as a member, use the expiration timestamp as the score, and perform add, query, and delete operations to maintain an accurate online user count.

JavaBackend DevelopmentRedisZsetOnline Users
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

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.