How to Track Online Users with Redis ZSET: A Step‑by‑Step Guide

This article explains how to implement an online‑user counting feature using Redis sorted sets (zset) by leveraging the four core commands zadd, zrangeByScore, zremrangeByScore, and zrem, with Java/Spring code examples and optional browser‑fingerprinting for unauthenticated visitors.

Java Backend Technology
Java Backend Technology
Java Backend Technology
How to Track Online Users with Redis ZSET: A Step‑by‑Step Guide

1. Introduction

Online user counting is a common requirement; this article shows how to implement it using Redis sorted sets (zset) with four core commands: zadd, zrangeByScore, zremrangeByScore, and zrem.

2. Implementation Steps

2.1 How to determine if a user is online?

For authenticated sites, online status can be inferred from the validity of the user's token. For public sites, a rule such as browser fingerprinting (User‑Agent, headers, screen resolution, etc.) can be used, with libraries like FingerprintJS or ClientJS.

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

Store the visitorId in a cookie or header and pass it to the backend.

2.2 zadd – add online user

zadd takes three arguments: key, score, member. Example:

ZADD myzset 1 "one"

In the Java example, the score is the expiration timestamp, ensuring each user has only one entry.

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

2.3 zrangeByScore – query online users

zrangeByScore retrieves members whose scores fall within a range. Example:

ZRANGEBYSCORE myzset 1 3

To get current online users:

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

The size of the returned set equals the number of online users.

2.4 zremrangeByScore – periodic cleanup

zremrangeByScore removes members whose scores fall within a range. Example:

ZREMRANGEBYSCORE myzset 1 3

Scheduled task to delete expired entries:

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

2.5 zrem – delete on logout

zrem removes a specific member:

ZREM myzset "xxx"

When a user logs out:

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

3. Summary

The approach creates a Redis sorted set where each online user is a member, the expiration timestamp is the score, and standard ZSET commands provide add, query, and cleanup operations, offering a simple yet effective online‑user counting solution.

JavaRedisSpringZSETOnline Users
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

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.