Skip to content

Redis Transactions ​

MULTI/EXEC (Atomic Command Batches) ​

bash
# MULTI, EXEC, DISCARD phải đi trên MỘT kết nối: gửi cả chuỗi qua stdin của một redis-cli
# Hai lệnh SET chạy liền nhau, không lệnh của client khác xen vào giữa
printf 'MULTI\nSET balance:A 900\nSET balance:B 100\nEXEC\n' | redis-cli
# DISCARD xoá hàng đợi: không lệnh nào trong hàng đợi chạy
printf 'MULTI\nSET balance:A 0\nDISCARD\n' | redis-cli

JavaScript example:

javascript
// Node.js (ioredis); chạy trong hàm async
const Redis = require('ioredis')
const redis = new Redis()
await redis.set('balance:A', 1000)
await redis.set('balance:B', 0)
const multi = redis.multi()
multi.decrby('balance:A', 100)
multi.incrby('balance:B', 100)
const results = await multi.exec()
// results = [[null, 900], [null, 100]]

Important characteristics:

  • ✅ Atomic execution (all queued commands run without interleaving; NOT all-or-nothing on runtime errors)
  • ✅ Isolated (no other commands execute during transaction)
  • ❌ No rollback (a command that fails at run time does not stop the others; a command that fails at queue time, such as a syntax error, makes EXEC return EXECABORT and nothing runs)
  • ❌ No conditional logic (can't check balance before debit)

⚠️ GOTCHA: MULTI/EXEC Has NO Rollback (Partial Success Corrupts Data)

Redis MULTI/EXEC does NOT provide rollback. If one command in the transaction fails at run time (e.g., a type error), Redis still executes ALL other commands. This leads to partial transaction success and data corruption. Errors detected while queueing (syntax error, maxmemory reached) are different: EXEC returns EXECABORT and no command runs.

Why it happens:

  • MULTI/EXEC queues commands, executes them in order at EXEC
  • If command N fails at run time, commands 1 to N-1 already executed (can't undo) and commands after N still execute
  • Redis returns errors for failed commands, but successful commands remain applied
  • No automatic rollback like SQL databases (BEGIN/COMMIT/ROLLBACK)

Real-world data corruption (Kịch bản minh hoạ, không phải sự cố có nguồn):

javascript
// Node.js (ioredis); chạy trong hàm async
// Transfer $100 from A to B
await redis.set('balance:A', 1000)
await redis.set('balance:B', 'some_string')  // chuỗi không phải số nguyên
const multi = redis.multi()
multi.decrby('balance:A', 100)  // A: 1000 → 900 ✓
multi.incrby('balance:B', 100)  // lỗi lúc chạy: B không phải số nguyên
const results = await multi.exec()

// Kết quả đo trên redis:8 + ioredis:
// [[null, 900], [ReplyError: ERR value is not an integer or out of range, undefined]]
// (WRONGTYPE chỉ xuất hiện khi B là list/hash/set, không phải string)
//
// BUG: A bị trừ $100 nhưng B không được cộng: $100 biến mất khỏi hệ thống
console.log(results)

// Final state:
// balance:A = 900 (was 1000)
// balance:B = "some_string" (unchanged!)
// $100 LOST!

Bài học: kiểm kết quả từng lệnh trong EXEC, hoặc dùng Lua/WATCH khi cần điều kiện.

How to detect:

javascript
// Node.js (ioredis); chạy trong hàm async
// Check EXEC results for errors
const results = await multi.exec()

results.forEach((result, index) => {
  if (result[0]) {  // Error exists
    console.error(`Command ${index} failed:`, result[0])
    // But previous commands ALREADY executed!
  }
})
bash
# Đếm lỗi theo loại: errorstat_WRONGTYPE, errorstat_EXECABORT, errorstat_ERR…
redis-cli INFO errorstats

Prevention:

  1. Use Lua scripts instead (atomic + conditional: validate BEFORE the first write; Lua has no rollback either, so a runtime error after a write keeps that write):

    lua
    -- Lua script for safe transfer
    local fromKey = KEYS[1]
    local toKey = KEYS[2]
    local amount = tonumber(ARGV[1])
    
    -- Validate types
    if redis.call('TYPE', fromKey).ok ~= 'string' then
      return {err = 'Invalid type for fromKey'}
    end
    if redis.call('TYPE', toKey).ok ~= 'string' then
      return {err = 'Invalid type for toKey'}
    end
    
    local balance = tonumber(redis.call('GET', fromKey))
    if not balance or balance < amount then
      return {err = 'Insufficient balance'}
    end
    
    -- All checks passed, execute atomically
    redis.call('DECRBY', fromKey, amount)
    redis.call('INCRBY', toKey, amount)
    return {ok = 'Transfer successful'}
    javascript
    // Node.js (ioredis); minh hoạ: dán Lua ở trên vào chuỗi script, chạy trong hàm async
    const script = `...` // Lua script above
    const result = await redis.eval(script, 2, 'balance:A', 'balance:B', 100)
    // Điều kiện sai thì thoát sớm và chưa có gì bị ghi; lỗi SAU lần ghi đầu vẫn KHÔNG tự hoàn tác (đo trên redis:8)
  2. Validate data types BEFORE transaction:

    javascript
    // Node.js (ioredis); chạy trong hàm async
    // Cảnh báo: kiểm tra rồi mới MULTI vẫn có khoảng hở (key có thể đổi kiểu giữa hai bước), nên kèm WATCH
    // Check types before MULTI
    const typeA = await redis.type('balance:A')
    const typeB = await redis.type('balance:B')
    
    if (typeA !== 'string' || typeB !== 'string') {
      throw new Error('Invalid key types')
    }
    
    // Safe to proceed with MULTI/EXEC
    const multi = redis.multi()
    multi.decrby('balance:A', 100)
    multi.incrby('balance:B', 100)
    await multi.exec()
  3. Check ALL results for errors and compensate:

    javascript
    // Node.js (ioredis); chạy trong hàm async
    const multi = redis.multi()
    multi.decrby('balance:A', 100)
    multi.incrby('balance:B', 100)
    const results = await multi.exec()
    
    // Check for errors
    const hasError = results.some(r => r[0])
    
    if (hasError) {
      // COMPENSATE: Manual rollback
      console.error('Transaction failed, rolling back...')
    
      // Check which commands succeeded
      if (!results[0][0]) {
        // Command 1 succeeded (balance:A debited), undo it
        await redis.incrby('balance:A', 100)
      }
    
      throw new Error('Transaction failed and rolled back')
    }
  4. Use WATCH for optimistic locking (prevents concurrent modifications):

    javascript
    // Node.js (ioredis); chạy trong hàm async
    await redis.watch('balance:A', 'balance:B')
    
    // Validate state
    const balanceA = parseInt(await redis.get('balance:A'))
    if (balanceA < 100) {
      await redis.unwatch()
      throw new Error('Insufficient balance')
    }
    
    const multi = redis.multi()
    multi.decrby('balance:A', 100)
    multi.incrby('balance:B', 100)
    const result = await multi.exec()
    
    if (!result) {
      // Transaction aborted (keys changed during WATCH)
      throw new Error('Concurrent modification, retry')
    }
  5. Use single-key atomic commands (RedisJSON is bundled in redis:8; JSON.NUMINCRBY is atomic on ONE key, two keys still need MULTI or Lua):

    bash
    redis-cli JSON.SET account:A '$' '{"balance":1000}'
    redis-cli JSON.SET account:B '$' '{"balance":0}'
    # Atomic on one key; to move money between A and B use MULTI or Lua
    redis-cli JSON.NUMINCRBY account:A '$.balance' -100

→ See also: Redis Anti-Patterns, Redis Production Patterns

WATCH (Optimistic Locking) ​

text
# Giả mã minh hoạ, không chạy độc lập: WATCH, GET, MULTI, EXEC phải cùng một kết nối
WATCH balance:A
val = GET balance:A

if val >= 100:
  MULTI
  DECRBY balance:A 100
  INCRBY balance:B 100
  EXEC  # trả null nếu balance:A đổi sau WATCH: thử lại từ đầu
else:
  UNWATCH

Từ Redis 8.4, key kiểu string còn có SET … IFEQ (compare-and-set) và DELEX (compare-and-delete) trong MỘT lệnh, không cần WATCH.

JavaScript example:

javascript
// Node.js (ioredis); gọi trong hàm async, `redis` là một kết nối ioredis
// Minh hoạ: WATCH gắn với kết nối, nhiều request song song dùng chung `redis` sẽ trộn trạng thái WATCH/MULTI (mỗi giao dịch dùng kết nối riêng); thực tế đặt trần số lần thử thay `while (true)`
async function transfer(fromKey, toKey, amount) {
  while (true) {
    await redis.watch(fromKey)

    const balance = parseInt(await redis.get(fromKey))

    if (balance >= amount) {
      const multi = redis.multi()
      multi.decrby(fromKey, amount)
      multi.incrby(toKey, amount)

      const result = await multi.exec()

      if (result) {
        return 'Success'  // Transaction committed
      } else {
        // Transaction aborted (key changed), retry
        continue
      }
    } else {
      await redis.unwatch()
      throw new Error('Insufficient balance')
    }
  }
}

Lua Scripts (Better than MULTI/EXEC) ​

Why Lua > MULTI/EXEC:

  • ✅ Conditional logic (if/else)
  • ✅ Loops (for/while)
  • ✅ Truly atomic (no WATCH needed)
  • ✅ Fewer round-trips
lua
-- deduct_if_sufficient.lua
local balance = tonumber(redis.call('GET', KEYS[1])) or 0

if balance >= tonumber(ARGV[1]) then
  redis.call('DECRBY', KEYS[1], ARGV[1])
  redis.call('INCRBY', KEYS[2], ARGV[1])
  return 1  -- Success
else
  return 0  -- Insufficient balance
end

Execute Lua script:

javascript
// Node.js (ioredis); chạy trong hàm async
const script = `
  local balance = tonumber(redis.call('GET', KEYS[1])) or 0
  if balance >= tonumber(ARGV[1]) then
    redis.call('DECRBY', KEYS[1], ARGV[1])
    redis.call('INCRBY', KEYS[2], ARGV[1])
    return 1
  else
    return 0
  end
`

const result = await redis.eval(
  script,
  2,                          // Number of keys
  'balance:A', 'balance:B',   // KEYS[1], KEYS[2]
  100                         // ARGV[1]
)

if (result === 1) {
  console.log('Transfer succeeded')
} else {
  console.log('Insufficient balance')
}

Redis Cluster: EVAL và MULTI chỉ nhận key cùng hash slot: balance:A và balance:B khác slot nên trả CROSSSLOT Keys in request don't hash to the same slot (đo trên cluster 1 nút). Đặt hash tag, ví dụ {acct}:A và {acct}:B, để hai key cùng slot.

Load script (performance):

javascript
// Node.js (ioredis); chạy trong hàm async
// Load script once (returns SHA1); ioredis không có scriptLoad, dùng script('LOAD', ...)
const sha1 = await redis.script('LOAD', script)

// Execute by SHA1 (faster, less bandwidth)
const result = await redis.evalsha(sha1, 2, 'balance:A', 'balance:B', 100)

⚠️ GOTCHA: Lua Script Blocks Entire Redis (Long-Running Scripts Freeze Server)

Lua scripts in Redis execute atomically and block the ENTIRE Redis instance until completion. A slow Lua script (complex logic, large data, infinite loop) freezes ALL client requests, causing a complete outage.

Why it happens:

  • Lua scripts run in the main Redis thread (single-threaded)
  • Redis cannot execute other commands while Lua script running
  • After busy-reply-threshold (default 5s) the script keeps running, but Redis replies BUSY to other clients and accepts only SCRIPT KILL / FUNCTION KILL / SHUTDOWN NOSAVE
  • Long-running scripts (scan millions of keys, complex computation) block for minutes
  • ALL clients timeout during script execution

Real-world outage (Kịch bản minh hoạ, không phải sự cố có nguồn):

lua
-- BAD: Scan ALL keys and process (100M keys!)
local cursor = "0"
local count = 0

repeat
  local result = redis.call('SCAN', cursor, 'COUNT', 1000)
  cursor = result[1]
  local keys = result[2]

  for i, key in ipairs(keys) do
    local value = redis.call('GET', key)
    -- Process value (expensive operation)
    count = count + 1
  end
until cursor == "0"

return count
javascript
// Node.js (ioredis); chạy trong hàm async
// Execute script on production Redis (50K req/sec)
const script = `...` // Script above
const result = await redis.eval(script, 0)

// Script runs for 3 minutes (processing 100M keys)
// During these 3 minutes:
// - ALL 50K req/sec timeout
// - Total failed requests: 9M (50K × 180s)
// - Application completely down
// - Monitoring alerts: "Redis not responding!"
// - Script above only reads (SCAN/GET), so SCRIPT KILL stops it; a restart is needed only
//   after a script has already written (UNKILLABLE, see below)

Bài học: giữ script ngắn, việc quét lớn chạy ở phía ứng dụng theo lô.

How to detect:

bash
# Khi script đang chạy lâu, mọi lệnh (kể cả INFO) trả:
# BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.
redis-cli INFO
# Sau khi script xong, tìm lệnh chậm (EVAL/EVALSHA có thời gian lớn)
redis-cli SLOWLOG GET 10

# Dừng script CHƯA ghi dữ liệu
redis-cli SCRIPT KILL
# Script đã ghi: "UNKILLABLE Sorry the script already executed write commands against the dataset."
# → chờ script kết thúc, hoặc SHUTDOWN NOSAVE (mất mọi thay đổi chưa lưu xuống đĩa)

Prevention:

  1. Keep Lua scripts SHORT (đo thời gian chạy bằng SLOWLOG):

    lua
    -- GOOD: Simple atomic operation
    local balance = redis.call('GET', KEYS[1])
    if tonumber(balance) >= tonumber(ARGV[1]) then
      redis.call('DECRBY', KEYS[1], ARGV[1])
      return 1
    end
    return 0
  2. Avoid long SCAN loops in Lua scripts (scan in application code instead):

    javascript
    // Node.js (ioredis); minh hoạ, không chạy độc lập
    // BAD: Scan in Lua (blocks Redis)
    const script = `
      local cursor = "0"
      repeat
        local result = redis.call('SCAN', cursor)
        -- Process keys
      until cursor == "0"
    `
    
    // GOOD: Scan in application (non-blocking)
    let cursor = '0'
    do {
      const [newCursor, keys] = await redis.scan(cursor)
      cursor = newCursor
    
      // Process keys in batches
      for (const key of keys) {
        await redis.get(key)
        // Other clients can still access Redis between iterations
      }
    } while (cursor !== '0')
  3. Limit script execution time (busy-reply-threshold, old alias lua-time-limit):

    conf
    # redis.conf
    # 5000 ms là mặc định; script vượt ngưỡng vẫn chạy tiếp
    busy-reply-threshold 5000
    
    # Vượt ngưỡng, log in cảnh báo (đo trên redis:8 với ngưỡng 200 ms):
    # Slow script detected: still in execution after 200 milliseconds. You can try killing the script using the SCRIPT KILL command.
    # Script KHÔNG bị kill; client khác nhận lỗi BUSY tới khi script xong hoặc bị SCRIPT KILL
  4. Test scripts on production-size datasets before deployment:

    javascript
    // Node.js (ioredis); minh hoạ, không chạy độc lập (redis.eval(script, ...))
    // Load test Lua script
    const startTime = Date.now()
    const result = await redis.eval(script, ...)
    const duration = Date.now() - startTime
    
    if (duration > 10) {  // 10ms threshold
      console.error(`Script too slow: ${duration}ms`)
      // Don't deploy to production!
    }
  5. Break large operations into batches:

    lua
    -- minh hoạ, không chạy độc lập (allKeys không được định nghĩa)
    -- BAD: Process all keys at once
    for i, key in ipairs(allKeys) do
      redis.call('DEL', key)
    end
    
    -- GOOD: Process keys in batches (call script multiple times)
    local keys = ARGV  -- Pass batch of keys
    for i, key in ipairs(keys) do
      redis.call('DEL', key)
    end
    -- Return, let Redis serve other requests
    -- Application calls script again for next batch
  6. Use EVALSHA_RO for read-only scripts (Redis 7.0+):

    javascript
    // Node.js (ioredis); chạy trong hàm async
    // Script chỉ đọc chưa ghi dữ liệu nên SCRIPT KILL dừng được
    const sha1 = await redis.script('LOAD', "return redis.call('GET', KEYS[1])")
    const result = await redis.evalsha_ro(sha1, 1, 'balance:A')
    // Safer for production (can be killed if hangs)
  7. Monitor script execution:

    javascript
    // Node.js (ioredis); minh hoạ, không chạy độc lập (redis.eval(script, ...))
    // Wrap script execution with timeout
    const executeScriptWithTimeout = async (script, timeout = 1000) => {
      const promise = redis.eval(script, ...)
    
      const timeoutPromise = new Promise((_, reject) =>
        setTimeout(() => reject(new Error('Script timeout')), timeout)
      )
    
      return Promise.race([promise, timeoutPromise])  // client-side only: the script keeps running on the server and blocks it
    }

→ See also: Redis Performance Tuning, Redis Anti-Patterns

Phải nhớ

  • MULTI/EXEC: atomic và cô lập, KHÔNG rollback. Lỗi lúc xếp hàng (sai cú pháp) cho EXECABORT, lỗi lúc chạy thì lệnh còn lại vẫn chạy.
  • Cần điều kiện: dùng WATCH (check-and-set, thử lại khi EXEC trả null) hoặc Lua/Redis Functions (7.0+, FUNCTION LOAD rồi FCALL); Lua cũng không rollback sau lần ghi đầu. Trên Redis Cluster mọi key phải cùng hash slot (CROSSSLOT).
  • Script chạy lâu chặn cả instance (client khác nhận BUSY); SCRIPT KILL chỉ dùng được khi script chưa ghi.