Redis Transactions & Long-Running Lua Scripts
Tags: redis, database, developer, transactions
Published: 2020-07-08 16:27:24

---
title: Redis Transactions & Long-Running Lua Scripts
published: true
description: Redis Lua scripting is the recommended approach for handling transactions. Learn the common Lua Scripts error and how to handle for sentinel systems - ScaleGrid
tags: Redis, Database, Developer, Transactions,
//cover_image: https://scalegrid.io/blog/wp-content/uploads/2020/06/Redis-Transactions-and-Long-Running-Lua-Scripts-ScaleGrid-Blog.jpg
---
<link rel="canonical" href="https://scalegrid.io/blog/redis-transactions-long-running-lua-scripts/" />

<p style="text-align: justify;"><a href="https://scalegrid.io/blog/redis-transactions-long-running-lua-scripts/"><img class="alignnone size-full wp-image-5618" src="https://scalegrid.io/blog/wp-content/uploads/2020/06/Redis-Transactions-and-Long-Running-Lua-Scripts-ScaleGrid-Blog.jpg" alt="Redis Transactions & Long-Running Lua Scripts" width="100%" height="auto" /></a></p>
<p style="text-align: justify;"><a style="color: #2da964;" href="https://redis.io/" target="_blank">Redis</a> offers two mechanisms for handling transactions - <a style="color: #2da964;" href="https://redis.io/topics/transactions" target="_blank">MULTI/EXEC based transactions</a> and <a style="color: #2da964;" href="https://redis.io/commands/eval" target="_blank">Lua scripts evaluation</a>. Redis Lua scripting is the <a style="color: #2da964;" href="https://redis.io/topics/transactions#redis-scripting-and-transactions" target="_blank">recommended</a> approach and is fairly popular in usage.</p>
<p style="text-align: justify; padding-bottom: 10px;">Our <a style="color: #2da964;" href="https://scalegrid.io/redis.html" target="_blank">Redis™</a> customers who have Lua scripts deployed often report this error - “<tt>BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE</tt>”. In this post, <a style="color: #2da964;" href="https://scalegrid.io/blog/redis-transactions-long-running-lua-scripts/">Redis Transactions & Long-Running Lua Scripts</a>, we will explain the Redis transactional property of scripts, what this error is about, and why we must be extra careful about it on Sentinel-managed systems that can failover.</p>
<p style="text-align: justify;"><a href="https://scalegrid.io/blog/redis-transactions-long-running-lua-scripts/"><img class="alignnone size-full wp-image-5618" src="https://scalegrid.io/blog/wp-content/uploads/2020/06/Redis-Lua-Scripts-Diagram.jpg" alt="Redis Lua Scripts Diagram - ScaleGrid Blog" width="100%" height="auto" /></a></p>

<h2 style="padding-top: 15px;">Transactional Nature of Redis Lua Scripts</h2>
<p style="text-align: justify;">Redis “transactions” aren’t really transactions as understood conventionally - in case of errors, there is <a style="color: #2da964;" href="https://redis.io/topics/transactions#why-redis-does-not-support-roll-backs" target="_blank">no rollback</a> of writes made by the script.</p>
<p style="text-align: justify;">“<a style="color: #2da964;" href="https://redis.io/commands/eval#atomicity-of-scripts" target="_blank">Atomicity</a>” of Redis scripts is guaranteed in the following manner:</p>

<ul style="text-align: justify;">
	<li>Once a script begins executing, all other commands/scripts are blocked until the script completes. So, other clients either see the changes made by the script or they don’t. This is because they can only execute either before the script or after the script.</li>
	<li>However, Redis <a style="color: #2da964;" href="https://redis.io/topics/transactions#why-redis-does-not-support-roll-backs" target="_blank">doesn’t do rollbacks</a>, so on an error within a script, any changes already made by the script will be retained and future commands/scripts will see those partial changes.</li>
	<li>Since all other clients are blocked while the script executes, it is critical that the script is well-behaved and finishes in time.</li>
</ul>
<h2 style="padding-top: 15px;">The ‘lua-time-limit’ Value</h2>
<p style="text-align: justify;">It is highly recommended that the script complete within a time limit. Redis enforces this in a <i>weak manner</i> with the ‘lua-time-limit’ value. This is the maximum allowed time (in ms) that the script is allowed to run. The default value is 5 seconds. This is a really long time for CPU-bound activity (scripts have limited access and can’t run commands that access the disk).</p>
<p style="text-align: justify;">However, the script is not killed when it executes beyond this time. Redis starts accepting client commands again, but responds to them with a BUSY error.</p>
<p style="text-align: justify;">If you must kill the script at this point, there are two options available:</p>

<ul style="text-align: justify;">
	<li><a style="color: #2da964;" href="https://redis.io/commands/script-kill" target="_blank"><tt>SCRIPT KILL</tt></a> command can be used to stop a script that hasn’t yet done any writes.</li>
	<li>If the script has already performed writes to the server and must still be killed, use the <a style="color: #2da964;" href="https://redis.io/commands/shutdown" target="_blank"><tt>SHUTDOWN NOSAVE</tt></a> to shutdown the server completely.</li>
</ul>
<p style="text-align: justify;">It is usually better to just wait for the script to complete its operation. The complete information on methods to kill the script execution and related behavior are available in the <a style="color: #2da964;" href="https://redis.io/commands/eval#sandbox-and-maximum-execution-time" target="_blank">documentation</a>.</p>

<h2 style="padding-top: 15px;">Behavior on Sentinel-Monitored High Availability Systems</h2>
<p style="text-align: justify;"><a style="color: #2da964;" href="https://redis.io/topics/sentinel" target="_blank">Sentinel</a>-managed high availability systems add a new wrinkle to this. In fact, this discussion applies to any high availability system that depends on polling the Redis servers for health:</p>

<ul style="text-align: justify; padding-bottom: 15px;">
	<li>Long-running scripts will initially block client commands. Later when the ‘lua-time-limit’ has passed, the server will start responding with BUSY errors.</li>
	<li>Sentinels will consider such a node as unavailable, and if this persists beyond the <a style="color: #2da964;" href="https://redis.io/topics/sentinel#other-sentinel-options" target="_blank">down-after-milliseconds</a> value configured on the Sentinels, they will determine the node to be down.</li>
	<li>If such a node is the master, a failover will be initiated. A replica node might get promoted and could start accepting new connections from clients.</li>
	<li>Meanwhile, the older master will eventually complete executing the script and come back online. However, Sentinel will eventually reconfigure it as a replica and it will begin syncing with the new master. Any data written by the script will be lost.</li>
</ul>

<h3 style="padding-top: 15px;">Demonstration</h3>
<p style="text-align: justify;">We set up a sensitive high availability system to demonstrate this failover behavior. The setup has 2 Redis servers running in a master/replica configuration that is being monitored by a 3-sentinel quorum.</p>
<p style="text-align: justify;">The lua-time-limit value was set to 500 ms so that it starts responding to clients with errors if a script runs for longer than 500 ms. The <a style="color: #2da964;" href="https://redis.io/topics/sentinel#other-sentinel-options" target="_blank">down-after-milliseconds</a> value on the Sentinels is set to 5 seconds so that a node which reports errors is marked DOWN after 5 seconds.</p>
<p style="text-align: justify;">We execute the following Lua script on the master:</p>

<pre>local i = 0
while (true)
do
local key = "Key-" .. i
local value = "Value-" .. i
redis.call('set', key, value)
i = i + 1
redis.call('time')
end
</pre>
<p style="text-align: justify;">This keeps writing entries into the Redis master. We <a style="color: #2da964;" href="https://redis.io/commands/psubscribe" target="_blank">subscribe</a> to the events on one of the sentinels to observe the behavior.</p>
<p style="text-align: justify;">The script is initiated on the master:</p>

<pre>$ <strong>redis-cli -a  --eval test.lua</strong>
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
</pre>
<p style="text-align: justify;">Here is a truncated sequence of activities as seen on Sentinel:</p>

<pre>3) "+vote-for-leader"
4) "9096772621089bb885eaf7304a011d9f46c5689f 1"
1) "pmessage"
2) "*"
3) "+sdown" <strong>&lt;&lt;&lt; master marked DOWN
</strong>4) "master test 172.31.2.48 6379"
1) "pmessage"
2) "*"
3) "+odown"
4) "master test 172.31.2.48 6379 #quorum 3/2"
1) "pmessage"
2) "*"
3) "-role-change" <strong>&lt;&lt; role change initiated
</strong>4) "slave 172.31.28.197:6379 172.31.28.197 6379 @ test 172.31.2.48 6379 new reported role is master"
1) "pmessage"
2) "*"
3) "+config-update-from"
4) "sentinel 9096772621089bb885eaf7304a011d9f46c5689f 172.31.2.48 26379 @ test 172.31.2.48 6379"
1) "pmessage"
2) "*"
3) "+switch-master"
4) "test 172.31.2.48 6379 172.31.28.197 6379"
</pre>
<p style="text-align: justify;">Later, when the old master is brought online, it is changed to a replica:</p>

<pre>3) "-role-change"
4) "slave 172.31.2.48:6379 172.31.2.48 6379 @ test 172.31.28.197 6379 new reported role is master"
1) "pmessage"
2) "*"
3) "-sdown"
4) "slave 172.31.2.48:6379 172.31.2.48 6379 @ test 172.31.28.197 6379"
1) "pmessage"
2) "*"
3) "+role-change"
4) "slave 172.31.2.48:6379 172.31.2.48 6379 @ test 172.31.28.197 6379 new reported role is slave"
</pre>
<p style="text-align: justify;">All the data written to the old master via the script is lost.</p>

<h2 style="padding-top: 15px;">Recommendations</h2>
<ul style="text-align: justify;">
	<li>You must know the characteristics of your long-running scripts in advance before deploying them in production.</li>
	<li>If your script regularly breaches the lua-time-limit, you must review the script thoroughly for possible optimizations. You can also break it down into pieces that complete in acceptable durations.</li>
	<li>If you must run scripts that breach the lua-time-limit, consider scheduling these scripts during periods where other client activity will be low.</li>
	<li>The value of the lua-time-limit can also be increased. This would be an acceptable solution if other client applications that execute in parallel with the script can tolerate receiving extremely delayed responses rather than a BUSY error and retrying later.</li>
</ul>
<p style="text-align: justify;">Additional considerations on Sentinel-monitored high availability systems:</p>

<ul style="text-align: justify;">
	<li>If the scripts are only doing read operations and you have replicas available, you can move these scripts to the replicas.</li>
</ul>
<p style="text-align: justify; padding-bottom: 20px;">Change the Sentinel parameter <a style="color: #2da964;" href="https://redis.io/topics/sentinel#other-sentinel-options" target="_blank">down-after-milliseconds</a> to a value that will ensure that failovers aren’t initiated. You must do this only after careful consideration because increasing the value drastically will compromise the high availability characteristics of your system. This could also cause genuine server failures to be ignored.</p>