0
0
Redisquery~30 mins

EVALSHA for cached scripts in Redis - Mini Project: Build & Apply

Choose your learning style9 modes available
Using EVALSHA for Cached Scripts in Redis
📖 Scenario: You are managing a Redis database for a small online store. You want to use Lua scripts to perform operations efficiently. To avoid sending the full script every time, you will cache the script in Redis and use its SHA1 hash to run it quickly.
🎯 Goal: Build a Redis Lua script caching workflow using EVALSHA to run a cached script that increments a product's stock count.
📋 What You'll Learn
Create a Lua script that increments a product stock by a given amount.
Load the script into Redis and get its SHA1 hash.
Store the SHA1 hash in a variable called script_sha.
Use EVALSHA with script_sha to increment the stock count.
Handle the case where the script is not cached by loading it again.
💡 Why This Matters
🌍 Real World
Caching Lua scripts in Redis is common in real-world applications to speed up repeated script execution and reduce network traffic.
💼 Career
Understanding <code>EVALSHA</code> and script caching is valuable for backend developers and database administrators working with Redis.
Progress0 / 4 steps
1
Create the Lua script to increment stock
Create a variable called lua_script and assign it this exact Lua script as a string: return redis.call('INCRBY', KEYS[1], ARGV[1])
Redis
Need a hint?

This Lua script uses redis.call('INCRBY', ...) to increase a key's value by a given number.

2
Load the Lua script into Redis and get SHA1 hash
Use the Redis command SCRIPT LOAD with lua_script to load the script and store the returned SHA1 hash in a variable called script_sha.
Redis
Need a hint?

Use redis.call('SCRIPT', 'LOAD', lua_script) to load the script and get its SHA1 hash.

3
Use EVALSHA to increment stock count
Use redis.call with 'EVALSHA', the variable script_sha, 1 for the number of keys, the key 'product_stock', and the increment amount '5' as arguments to run the cached script.
Redis
Need a hint?

Use redis.call('EVALSHA', script_sha, 1, 'product_stock', '5') to run the cached script.

4
Handle missing cached script by loading again
Add a check: if redis.call('EVALSHA', script_sha, 1, 'product_stock', '5') fails with a NOSCRIPT error, reload the script with SCRIPT LOAD and run EVALSHA again.
Redis
Need a hint?

Use pcall to catch errors and check if the error message contains 'NOSCRIPT'. If yes, reload the script and run EVALSHA again.