2.5 Hours

13. Transactions: Atomic Multitasking with MULTI/EXEC

Transactions

Command Queueing and Isolation

Redis provides support for transactions through the MULTI, EXEC, DISCARD, and WATCH commands. A Redis transaction begins with the MULTI command. Once issued, all subsequent commands sent by the client are not executed immediately; instead, they are validated for basic syntax and queued in server memory. When the client calls EXEC, all queued commands are executed sequentially without interruption from other clients. If the client calls DISCARD instead of EXEC, the queue is cleared, and no commands are run.

Redis transactions guarantee isolation. During execution of the queued commands, no other client request can interleave or modify the keys involved. This ensures that the transaction block runs as a single unit. However, Redis transactions do not support rollbacks in the traditional relational database sense. If a command in a transaction fails at runtime (e.g., trying to run a list command on a string key), Redis will still execute all the other commands in the queue. There is no automated cleanup of successfully committed steps.

This design choice keeps transaction performance close to normal command execution speeds. Relational databases support rollback by logging undo histories and holding locks on affected records, which introduces significant performance overhead. Redis prioritizes speed, operating on the assumption that runtime errors are programming mistakes that should be caught during development rather than production database failures.

Optimistic Concurrency Control with WATCH

Because Redis transactions queue commands rather than executing them step-by-step, you cannot use the results of an early query inside a transaction to decide what to do in a later step. For example, if you want to read a bank balance, check if there are sufficient funds, and then perform a debit, you cannot do this inside a simple MULTI/EXEC block. By the time you read the balance, the transaction has already queued subsequent writes without checking the result. To solve this, Redis uses Optimistic Concurrency Control (OCC) via the WATCH command.

The WATCH command monitors specified keys for modifications before a transaction begins. If another client modifies a watched key before the current client calls EXEC, the entire transaction is aborted, and EXEC returns a null response. The application can then catch this condition, read the updated value, and retry the operation. This is called optimistic locking because it assumes conflicts are rare, avoiding the overhead of pessimistic locking (which blocks other clients while the transaction is active).

Optimistic locking is highly efficient in environments with low write contention. However, if multiple clients write to the same key simultaneously, transactions will fail frequently, causing retry loops that consume CPU. In high-contention environments, developers should use Lua scripting to implement complex logic atomically on the server side.

JavaScript
// Safe Bank Transfer using WATCH and MULTI/EXEC with Retries
const Redis = require('ioredis');
const redis = new Redis({ host: '127.0.0.1', port: 6379 });

async function transferFunds(fromKey, toKey, amount, maxRetries = 5) {
  let retries = 0;
  while (retries < maxRetries) {
    try {
      // Step 1: Watch the source account key for changes
      await redis.watch(fromKey);
      
      // Step 2: Read balance to verify funds
      const balance = parseFloat(await redis.get(fromKey) || '0');
      if (balance < amount) {
        await redis.unwatch(); // Release key monitoring
        throw new Error('Insufficient funds');
      }
      
      // Step 3: Queue debit and credit operations
      const tx = redis.multi();
      tx.decrby(fromKey, amount);
      tx.incrby(toKey, amount);
      
      // Step 4: Execute transaction. Returns null if watched key changed.
      const result = await tx.exec();
      if (result !== null) {
        return true; // Transfer successful
      }
      
      // Watched key changed, retry transaction
      retries++;
      console.warn(`Transaction conflict on ${fromKey}. Retrying ${retries}/${maxRetries}...`);
    } catch (error) {
      await redis.unwatch();
      throw error;
    }
  }
  throw new Error('Transaction aborted: maximum retries reached due to conflict');
}

Knowledge Check

Ready to test your understanding of 13. Transactions: Atomic Multitasking with MULTI/EXEC?

Back