Rankings and UV counters with Redis Sorted Set, HLL, and Lua
Building weekly rankings and daily UV counters with Redis Sorted Set, HyperLogLog, and Lua, with memory, accuracy, and concurrency measurements.
While adding weekly leaderboards and daily unique visitor (UV) counts to an algorithm study site, I picked three Redis primitives for the job: Sorted Set, HyperLogLog, and Lua scripts. Here are the local benchmarks comparing Set vs. HyperLogLog memory at one million users, real HLL error rates, and lost updates under concurrent
GET+SET.
Tested with Spring Boot 3.5.5, Kotlin 2.2.10, Java 21, Spring Data Redis 3.5.3 (Lettuce 6.6.0), and Redis 8.2.1 (Docker). Both the Spring app and Redis ran on the same local PC (12 cores, 32GB RAM, Windows with Docker Desktop/WSL2).
Background
On our club’s algorithm study site, members earn points for each solved problem, and the home page displays the weekly top 10 alongside today’s unique visitor count. Originally, both came straight from PostgreSQL via ORDER BY score DESC LIMIT 10 and COUNT(DISTINCT user_id). Because every visitor hits the home page, those aggregation queries ran on every request while the visit log table kept growing.
I had already used Redis for deduplicating view counts with Redis SETNX, so Redis was the natural next step. This time, the real decision was picking the right data structure for each workload: Sorted Set for rankings, HyperLogLog for unique visitors, and Lua scripts whenever multiple commands must execute atomically.
How each data structure works
Sorted Set starts out as a compact contiguous array called listpack when the member count is small. Once it crosses zset-max-listpack-entries (default 128), Redis switches it to a skiplist paired with a hash table. Checking OBJECT ENCODING confirmed listpack at 100 members and skiplist from 10,000 members onward. Thanks to the skiplist, score updates (ZINCRBY) and rank lookups (ZREVRANK) run in O(log N), and fetching the top K entries runs in O(log N + K).
HyperLogLog (HLL) never stores the actual elements. It hashes each input into 64 bits, uses the first 14 bits to pick one of 16,384 registers, and tracks only the maximum count of leading zeros in the remaining bits. In its dense representation, memory stays fixed at 16,384 registers × 6 bits = 12KB regardless of cardinality, with a documented standard error of 0.81%. For small cardinalities, Redis uses a run-length encoded sparse format before promoting the key to dense.
Lua scripts run inside Redis’s single-threaded command loop as a single atomic unit. No other client command can interleave while a script is executing, which makes read-modify-write sequences safe without client-side locks.
Benchmark results
I inserted identical string members into a Redis Set and a HyperLogLog and measured per-key memory with MEMORY USAGE key SAMPLES 0.
| Unique members | Set memory | HLL memory | HLL error |
|---|---|---|---|
| 1,000 | 47,464 B | 2,576 B (sparse) | -0.20% |
| 10,000 | 530,344 B | 14,352 B (dense) | -0.29% |
| 100,000 | 5,047,848 B | 14,352 B | +0.70% |
| 1,000,000 | 48,387,880 B | 14,352 B | -2.11% |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"type": "bar",
"data": {
"labels": ["1K", "10K", "100K", "1M"],
"datasets": [
{ "label": "Set (KB)", "data": [46.4, 517.9, 4929.5, 47253.8], "backgroundColor": "#f7768e" },
{ "label": "HyperLogLog (KB)", "data": [2.5, 14.0, 14.0, 14.0], "backgroundColor": "#7aa2f7" }
]
},
"options": {
"scales": { "y": { "type": "logarithmic", "title": { "display": true, "text": "KB (log scale)" } } },
"plugins": { "title": { "display": true, "text": "Set vs. HyperLogLog memory by unique member count" } }
}
}
At one million members, Set consumed roughly 46MB while HyperLogLog stayed at 14KB—about 3,370× smaller. Because the -2.11% error in that single run stood out, I repeated the 1M-member experiment 10 more times with distinct member sets. Mean absolute error was 0.44% and max error was 1.08%. Most trials stay well within the 0.81% standard error, but occasional ~2% outliers do happen. Merging seven daily HLL keys with PFMERGE for a weekly UV returned 165,566 against an exact count of 165,112 (+0.28%).
Leaderboard query latency barely moved as the set grew. Fetching the top 10 (ZREVRANGE 0 9 WITHSCORES) had a p50 of 567µs at 100 members and 561µs at 1,000,000 members. Nearly all of that time is local TCP round-trip overhead to Docker, masking skiplist traversal completely. Memory hits a ceiling long before latency does: a 1M-member Sorted Set took about 82MB (86,227,216 bytes).
Finally, I ran 64 threads incrementing the same counter 10,000 times total.
| Approach | Final value (3 runs) | Lost updates | Median duration |
|---|---|---|---|
GET then SET | 300 / 302 / 301 | ~97% | 420ms |
INCR | 10,000 × 3 | 0 | 168ms |
| Lua script | 10,000 × 3 | 0 | 213ms |
Lettuce shares a single connection across threads by default, so all 64 threads read the same value with GET almost simultaneously and overwrite each other with +1. Out of 10,000 increments, only about 300 survived.
Implementation
1
2
3
4
5
6
7
8
9
10
11
12
// build.gradle.kts
plugins {
kotlin("jvm") version "2.2.10"
kotlin("plugin.spring") version "2.2.10"
id("org.springframework.boot") version "3.5.5"
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-redis")
implementation("org.jetbrains.kotlin:kotlin-reflect")
}
1
2
3
4
5
6
# src/main/resources/application.yml
spring:
data:
redis:
host: localhost
port: 6379
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// src/main/kotlin/com/example/club/stat/StatRedisRepository.kt
package com.example.club.stat
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.core.ZSetOperations
import org.springframework.data.redis.core.script.RedisScript
import org.springframework.stereotype.Repository
import java.time.LocalDate
@Repository
class StatRedisRepository(private val redis: StringRedisTemplate) {
private val incrScript = RedisScript.of(
"""
local v = tonumber(redis.call('GET', KEYS[1]) or '0') + 1
redis.call('SET', KEYS[1], v)
return v
""".trimIndent(), Long::class.java
)
private val memoryScript = RedisScript.of(
"return redis.call('MEMORY', 'USAGE', KEYS[1], 'SAMPLES', '0')", Long::class.java
)
// Ranking: accumulate score and fetch top 10
fun addScore(week: String, userId: Long, delta: Double): Double? =
redis.opsForZSet().incrementScore("rank:$week", "user:$userId", delta)
fun top10(week: String): Set<ZSetOperations.TypedTuple<String>> =
redis.opsForZSet().reverseRangeWithScores("rank:$week", 0, 9) ?: emptySet()
fun myRank(week: String, userId: Long): Long? =
redis.opsForZSet().reverseRank("rank:$week", "user:$userId")?.plus(1)
// UV: daily HyperLogLog and weekly merge
fun visit(date: LocalDate, userId: Long) {
redis.opsForHyperLogLog().add("uv:$date", userId.toString())
}
fun weeklyUv(days: List<LocalDate>): Long =
redis.opsForHyperLogLog().union("uv:week:${days.first()}", *days.map { "uv:$it" }.toTypedArray())
// Atomic read-modify-write via Lua
fun incrementByScript(key: String): Long = redis.execute(incrScript, listOf(key))!!
fun memoryUsage(key: String): Long = redis.execute(memoryScript, listOf(key))!!
}
I wrapped MEMORY USAGE in a one-line Lua script for a practical reason: calling arbitrary commands through RedisConnection.execute() made Lettuce 6.6.0 expect a byte array and throw UnsupportedOperationException: ByteArrayOutput does not support set(long) on an integer reply. Declaring Long::class.java on RedisScript decodes the integer response cleanly.
Decision matrix and when not to use them
| Requirement | Redis structure | Reason |
|---|---|---|
| Top K leaderboard and user rank | Sorted Set | O(log N) score updates and rank queries |
| Unique visitor count (approximate OK) | HyperLogLog | Fixed 12KB max per key, supports PFMERGE |
| Exact unique count or member list | Set or relational DB | Requires exact membership and lookup |
| Simple counter | INCR / INCRBY | Atomic in a single built-in command |
| Conditional or multi-key atomic update | Lua script | Executes the entire sequence atomically |
Knowing when not to use these structures is just as important. Never use HyperLogLog for billing, coupon quotas, or any metric where being off by even one user breaks business logic—my own test hit a 2% error. You also can’t ask HLL who visited. For Lua, remember that a running script blocks the entire Redis event loop, so avoid loops over tens of thousands of keys or KEYS scans. And if all you need is a plain increment, built-in INCR is shorter and faster than Lua.
Production pitfalls and checklist
Sorted Set breaks ties lexicographically by member name. Inserting
alice,bob, andcharlieall with score100returned[charlie, bob, alice]fromZREVRANGE. If you try to rank earlier achievers higher by encoding a composite score likescore * 10^10 + (constant - timestamp), watch out for IEEE 754doubleprecision: above2^53(9,007,199,254,740,992), lower bits round off. In my test,10,000,008,242,999,999was stored as10,000,008,243,000,000.
- Have all
GET-then-SETcounter updates been replaced withINCRor a Lua script? - Is HyperLogLog restricted to approximate display metrics, with exact counts computed from raw logs?
- Do weekly and daily ranking keys have an
EXPIRETTL so old Sorted Sets don’t pile up in memory? - Have you verified tie-breaking order and
doubleprecision limits if using composite scores? - Does every Lua script touch a small, fixed set of keys and finish quickly?