Databases 8 min read

How to Build a Lottery System with Lua Scripts in Redis and Spring Data Redis

This tutorial demonstrates how to use Redis SET operations and a Lua script to implement a lottery mechanism, and shows how to integrate the script into a Java Spring application using Spring Data Redis's RedisTemplate for atomic execution.

Programmer DD
Programmer DD
Programmer DD
How to Build a Lottery System with Lua Scripts in Redis and Spring Data Redis

Introduction

In the previous article we introduced basic Lua syntax and its usage in Redis. This article continues by applying Lua scripts to a real‑world lottery scenario using the Spring Data Redis component commonly used in Java development.

Lua Lottery Implementation

The lottery rules are:

Winners are drawn only from the prize pool.

Each person can win only once.

The total number of winners cannot exceed the configured prize count.

A list of winners is generated.

Redis SET collections are ideal for this because they store unique, unordered elements. The following Redis commands are demonstrated:

SET Operations

Adding elements (SADD)

Use SADD to add multiple users to the lottery set, creating the key if it does not exist.

127.0.0.1:6379> sadd lottery u1 u2 u3 u4 u5 u6 u7
(integer) 7
127.0.0.1:6379> sadd lottery u1
(integer) 0

Querying elements (SMEMBERS)

Retrieve all members with SMEMBERS:

127.0.0.1:6379> smembers lottery
1) "u2"
2) "u7"
3) "u6"
4) "u4"
5) "u1"
6) "u3"
7) "u5"

Randomly selecting N elements

Use SPOP (removes selected elements) or SRANDMEMBER (keeps them) to draw participants. Example drawing two elements:

127.0.0.1:6379> srandmember lottery 2
1) "u2"
2) "u4"
127.0.0.1:6379> smembers lottery
... (unchanged)
127.0.0.1:6379> spop lottery 2
1) "u3"
2) "u5"

Choose SPOP when the prize pool is static; use SRANDMEMBER for dynamic pools to avoid re‑selecting winners.

Lottery Lua Script

The script draw.lua extracts a specified number of winners from the lottery set and stores them in a chosen set:

--- Simple lottery script, returns result to Java
-- prize pool key
local lottery_key = KEYS[1]
-- winner list key
local chosen_key = KEYS[2]
-- number of winners to draw
local lottery_count = ARGV[1]

if tonumber(lottery_count) > 0 then
    local chosen_list = redis.call('SRANDMEMBER', lottery_key, lottery_count)
    if chosen_list then
        return redis.call('SADD', chosen_key, unpack(chosen_list))
    else
        return 0
    end
else
    return 0
end
Note: This script is for demonstration only; adapt the logic to your business requirements and refer to Lua syntax documentation.

Java Integration

Spring Data Redis provides RedisTemplate.execute to run Lua scripts. The following Java code loads the script and executes it:

@Override
public <T> T execute(RedisScript<T> script, List<K> keys, Object... args) {
    return scriptExecutor.execute(script, keys, args);
}
RedisScript

abstracts a Lua script for loading. keys correspond to KEYS in the script. args correspond to ARGV in the script.

Example execution that draws five winners:

RedisScript<Long> redisScript = RedisScript.of(new ClassPathResource("META-INF/scripts/draw.lua"), Long.class);
Long chosenCount = stringRedisTemplate.execute(redisScript, Arrays.asList("lottery", "chosen"), Collections.singletonList("5"));
When constructing a RedisScript , always specify the expected return type to avoid type‑mismatch exceptions.

Conclusion

The complete workflow shows how Lua scripts can provide atomic lottery operations in Redis, and how to invoke them from Java using Spring Data Redis. Use this approach only when atomicity under high concurrency is required, not merely for “show‑off”.

Maven project structure
Maven project structure
Additional illustration
Additional illustration
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.

JavaredisScriptingLuaLotterySpring Data Redis
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

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.