I’ve been wanting to make use of Redis Lua scripting for a long time for some projects at work. I’ve read Redis Lua scripting, and found that I can use it to solve a few common issues we’ve been dealing with, one being ensuring redis hashes have an expiry. We have a lot of services at my job which use Redis as a centralized state database, allowing services to share knowledge in a common place, without having to know if or what else may need the data. All information written to this DB requires an expiry value to be assigned. In our old data model, we had done this by using the SETEX [key] [ttl] [value]
or SET [key] [value] EX [ttl]
commands. This is great, as we can set the key and the expiry at the same time atomically and ensure that every key will expire. In our new data model, we are switching from keys to hashes, but unfortunately, there is not an HSETEX
command built in. Instead, we have to rely on pairing HSET
and EXPIRE
commands manually, which of course doubles the “ops” per item being set, but also ads the possibility of something breaking and a hash lacking expiry.
I found Redis Lua scripting to be a big help here to ensure that every hash gets an expiry set while setting fields/values on the hash. I also added logic to conditionally skip setting EXPIRE. The response of HSET
will tell us how many new fields have been created, which would only be 0
if the hash already existed and already had an expiry.
1 | -- Set EXPIRE on hash after HSET if new fields added |
So, all of this sounds great, I can just make use of Lua scripts for anything that needs to do multiple actions, saving my code round trips to the DB. Obvious win, right? I wasn’t totally sure. When searching for Redis Lua performance, I kept finding articles where someone was mis-using Redis Lua, calling EVAL
every time they want to call Redis Lua, or generating dynamically generated Lua script, both of which are entirely incorrect uses of Redis Lua.
I wanted to know was what is the actual cost was to use a Lua script compared to standard Redis commands? Literally, apples-to-(lua-scripted)-apples.