Redis provides the ability to execute server-side programs. This is similar to the ability to execute stored procedures in relational databases that are written using SQL (Structured Query Language). However, in Redis, the scripts are executed by an embedded engine, which currently only supports the Lua interpreter. Lua is a scripting language that supports multiple programming paradigms, including procedural, functional, object-oriented, and so on. As part of a Lua script, we can write logic that uses Redis commands to read and write data.

Benefits of Lua scripting with Redis

Some of the key benefits include the following:

  • Efficiency: As the name suggests, server-side programming lets us execute logic closer to the data, and the same applies to Lua scripts as well. By executing the logic in a Redis server, we reduce the overall latency and save network bandwidth.

  • Atomicity: A Lua script is always executed atomically in Redis because the entire server is blocked during the duration of script execution. Although this is a powerful feature, it also means that we need to careful about the correctness and execution time of our Lua scripts.

  • Flexibility: Because Lua is a full-fledged programming language in itself, we can implement server-side features by combining Redis commands. This allows us to build capabilities specific to our unique requirements that might not be natively supported by Redis.

Script cache

Once a script is executed, it’s cached in Redis. The way to uniquely identify a script in the cache is by using its SHA1 digest sum. This is an important feature because script execution involves sending the entire script over the network. Needless to say, this isn’t efficient and scalable if done repeatedly. Thanks to this native script-caching ability, we can save network bandwidth and other overheads in Redis.

Lua script operations

Now that we have a theoretical background, let’s explore some of Lua’s scripting operations using the go-redis client.

The Eval and EvalRO functions

The Eval function it makes it possible to invoke a server-side Lua script. It has a variant, EvalRO, which prohibits commands that mutate data from executing in Redis.

There’s also the EvalSha function, which loads a script from the server’s cache using its SHA1 digest and executes it. From a go-redis client perspective, using this function over Eval shows no difference.

Click “Run” in the code widget below to try out these commands:

Get hands-on with 1200+ tech skills courses.