Mastering Redis Sorted Sets: Build High‑Performance Leaderboards with Spring Boot

Redis Sorted Sets, powered by skip lists, provide O(log n) operations for ranking and range queries; this article explains their internal structure, core commands, and demonstrates how to implement a real‑time leaderboard in Spring Boot using Redis, complete with configuration, entity design, and service methods.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Redis Sorted Sets: Build High‑Performance Leaderboards with Spring Boot

Redis Sorted Set (Sorted Set) is a data structure that orders elements by a numeric score, making it ideal for leaderboards, approximate counters, and similar use cases.

Internally, Redis implements Sorted Sets using a skip list, a layered linked‑list structure where each node holds an element value and an array of forward pointers. Skip lists provide average O(log n) time complexity for insertion, deletion, and search, offering a simpler alternative to balanced trees.

The underlying storage combines a hash table (to map elements to their scores) with the skip list (to maintain order). When an operation is performed, Redis first looks up the element in the hash to obtain its score, then navigates the skip list to locate or modify the element’s position.

Core Sorted Set commands include:

ZADD : Add an element with a score.

ZRANGE / ZREVRANGE : Retrieve elements in score order (ascending or descending).

ZREM : Remove an element.

ZINCRBY : Increment an element’s score.

ZCARD : Get the number of elements.

ZRANDMEMBER : Return a random element.

Practical Example: Leaderboard with Spring Boot and Redis

1. Add the Redis starter dependency to pom.xml:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>

2. Configure the Redis connection in application.properties or application.yml:

# application.properties
spring.redis.host=localhost
spring.redis.port=6379
# application.yml
spring:
  redis:
    host: localhost
    port: 6379

3. Create a RedisTemplate bean:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }
}

4. Define a simple entity to hold ranking information:

import java.io.Serializable;

public class RankingEntity implements Serializable {
    private String userId;
    private double score;
    // constructors, getters, setters omitted for brevity
}

5. Implement a service that provides leaderboard operations:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class RankingService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final String RANKING_KEY = "ranking_list";

    /** Add a score for a user */
    public void addScore(String userId, double score) {
        ValueOperations<String, RankingEntity> ops = redisTemplate.opsForValue();
        ops.set(RANKING_KEY + ":" + userId, score, 60, TimeUnit.SECONDS);
    }

    /** Get the full ranking list */
    public List<Object> getRankingList() {
        return redisTemplate.opsForList().range(RANKING_KEY, 0, -1);
    }

    /** Get a specific user's rank */
    public int getUserRanking(String userId) {
        List<Object> list = getRankingList();
        Object userScore = getUserScore(userId);
        if (userScore == null) return -1;
        int rank = 0;
        for (Object score : list) {
            if (score.equals(userScore)) break;
            rank++;
        }
        return rank;
    }

    /** Retrieve a user's score */
    public Object getUserScore(String userId) {
        ValueOperations<String, RankingEntity> ops = redisTemplate.opsForValue();
        return ops.get(RANKING_KEY + ":" + userId);
    }

    /** Update a user's score */
    public void updateUserScore(String userId, double score) {
        ValueOperations<String, RankingEntity> ops = redisTemplate.opsForValue();
        ops.set(RANKING_KEY + ":" + userId, score, 60, TimeUnit.SECONDS);
    }

    /** Delete a user's score */
    public void deleteUserScore(String userId) {
        ValueOperations<String, RankingEntity> ops = redisTemplate.opsForValue();
        ops.delete(RANKING_KEY + ":" + userId);
    }

    /** Clear all ranking data */
    public void clearAllUserRankingData() {
        redisTemplate.delete(RANKING_KEY);
    }
}

These components together enable a Spring Boot application to store, update, and query a high‑performance leaderboard using Redis Sorted Sets.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentRedisSpring BootSorted Setleaderboard
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.