0
0
Redisquery~30 mins

Lua vs transactions comparison in Redis - Hands-On Comparison

Choose your learning style9 modes available
Using Lua Scripts and Transactions in Redis
📖 Scenario: You are managing a Redis database for a small online store. You want to update the stock quantity of a product safely when a purchase happens. You will learn two ways to do this: using Lua scripts and using Redis transactions.
🎯 Goal: Build two Redis commands: one using a Lua script to safely decrease stock if enough quantity exists, and another using Redis transactions to do the same. This will help you understand the difference between Lua scripting and transactions in Redis.
📋 What You'll Learn
Create a Redis key product_stock with initial value 10
Create a Lua script that decreases product_stock by 3 only if stock is enough
Create a transaction that watches product_stock and decreases it by 3 safely
Compare the Lua script and transaction approach in terms of atomicity and simplicity
💡 Why This Matters
🌍 Real World
Managing stock quantities in an online store requires safe updates to avoid selling more items than available.
💼 Career
Understanding Redis Lua scripts and transactions is important for backend developers working with Redis to ensure data consistency and atomic operations.
Progress0 / 4 steps
1
DATA SETUP: Create the initial stock key
Use the Redis command SET product_stock 10 to create a key called product_stock with the value 10.
Redis
Need a hint?

Use the SET command to create a key with a number value.

2
CONFIGURATION: Write the Lua script to decrease stock
Write a Lua script that gets the current stock from product_stock, checks if it is at least 3, and if yes, decreases it by 3 and returns the new stock. Use redis.call('GET', 'product_stock') and redis.call('SET', 'product_stock', new_stock).
Redis
Need a hint?

Use redis.call to get and set the key inside the Lua script.

3
CORE LOGIC: Use Redis transactions to decrease stock safely
Use Redis commands to watch product_stock, get its value, check if it is at least 3, then start a transaction with MULTI, decrease the stock by 3 with SET, and execute with EXEC. Use WATCH product_stock before reading the value.
Redis
Need a hint?

Use WATCH before reading, then MULTI to start transaction, SET to update, and EXEC to commit.

4
COMPLETION: Add a comment comparing Lua scripts and transactions
Add a comment explaining that Lua scripts run atomically and are simpler for this use case, while transactions require watching keys and can fail if keys change.
Redis
Need a hint?

Write a clear comment comparing the two methods.