← All notes

Field notes

Why Was Lua Running Inside My Redis Backend?

I came across Lua while exploring Python backend code. Here's what I learned about the language and why Redis uses it for atomic operations.

3 min read
  • lua
  • redis
  • backend
  • learning

Recently, while exploring Python backend code, I noticed Lua scripts embedded inside Python strings. The application used FastAPI and Redis, but some Redis operations were written in another language.

Why introduce Lua when Python could already talk to Redis? That question led me to look closer.

What Is Lua?

Lua is a lightweight scripting language designed to be embedded in other software. Applications use it for scripting and customization without requiring everything to be written in Lua.

Its small syntax felt approachable. Here's a conditional:

local count = 5

if count < 10 then
    print("Allowed")
else
    print("Blocked")
end

local defines a local variable, and end closes the conditional block.

I'd mostly associated Lua with game scripting and Neovim configuration and plugins. It's also used for web-server scripting in OpenResty and server-side scripting in Redis.

Why Lua in Redis?

Imagine a backend counter that allows ten requests. Python could read the counter, check whether it's below ten, then increment it.

The problem is the gap between those commands. If the count is nine, two simultaneous requests could both read nine and both decide they're allowed. That's a race condition.

A Lua script combines the check and update into one atomic operation: Redis runs the script without executing another Redis command in the middle of it.

local count = tonumber(redis.call("GET", KEYS[1]) or "0")

if count < 10 then
    redis.call("INCR", KEYS[1])
    return 1
end

return 0

redis.call() executes Redis commands. KEYS[1] is the first key passed into the script. GET reads its value; a missing counter starts at zero, and tonumber() converts the value to a number. INCR increases it by one. The script returns 1 for allowed or 0 for rejected.

This assumes the key contains an integer counter. It's a simplified example, not a complete rate limiter: production use also needs proper time-window and expiration management.

How Python Executes Lua

Python doesn't execute the Lua code itself. With an asynchronous Redis client, it sends the script to Redis using EVAL:

result = await redis.eval(
    lua_script,
    1,
    "request:counter"
)

lua_script contains the code above. The 1 means one Redis key follows, and "request:counter" is that key. Redis executes the script and returns its result to Python.

Python Backend
      |
      v
  Redis EVAL
      |
      v
  Lua Script
      |
      |-- Read counter
      |-- Check limit
      |-- Update counter
      |
      v
 Return Result

Is Lua Always Necessary?

Individual Redis commands are already atomic. Lua helps when a decision depends on stored data and several related reads and writes must run without interference.

That guarantee has a cost: Redis blocks other commands while the script executes. Long-running scripts can hurt performance, so I'd keep them short and focused.

Simple operations often need no Lua. Transactions can coordinate commands too, with WATCH for optimistic checks. Redis Functions offer another way to deploy server-side logic, including Lua; they're not a reason to move all application logic into Redis.

What I Took Away

What interested me was the design decision more than the syntax: moving a small, dependent operation closer to its data.

Python still handles the API and business logic. Redis stores the data. Lua handles a small piece that benefits from atomic execution.

The takeaway isn't that every backend needs Lua. Understanding where it fits can make a particular operation simpler and safer.

References