Thuta Learning
Redis
AdvancedData & Databasesbeginner

Lua Scripts and Redis Functions

What you'll walk away with

  • Explain the core ideas behind Lua Scripts and Redis Functions
  • Run the sample Redis command or code and verify its output
  • Apply the technique correctly to the Tutorial Platform and production scenarios

Build the mental model

A Lua script runs multiple commands as one atomic server-side unit. Pass keys through KEYS and values through ARGV; declare every accessed key for cluster routing. Long scripts can block the server, so keep work bounded. Redis Functions package logic into named, persisted libraries.

Connect it to a real scenario

Implement a limited coupon claim that checks remaining stock, decrements it, and records the user in a claim set. Duplicate claims are no-ops and zero stock is rejected. On NOSCRIPT, load and retry, and record business outcome codes in metrics.

Try the working example

lua
if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then return 2 end
local remaining = tonumber(redis.call('GET', KEYS[1]) or '0')
if remaining <= 0 then return 0 end
redis.call('DECR', KEYS[1])
redis.call('SADD', KEYS[2], ARGV[1])
return 1

-- KEYS: coupon:{42}:remaining, coupon:{42}:claims
You should see
The script atomically returns 0 for sold out, 1 for claimed, or 2 for duplicate.

5-minute try-it

Add success, blocked, and error outcome codes plus test cases to the rate-limit script.

One important caution

Do not run unbounded scans, loops, or external calls in Lua; the server event loop can be blocked.

Redis — Scripting with LuaRedis

Easy traps

  • Do not run unbounded scans, loops, or external calls in Lua; the server event loop can be blocked.
  • Validate sample commands on a local or test instance with recoverable data before applying them to production Redis.

Exercise

Add success, blocked, and error outcome codes plus test cases to the rate-limit script.

You'll know it worked when: The script atomically returns 0 for sold out, 1 for claimed, or 2 for duplicate.

Lua Scripts and Redis Functions | Thuta Learning