Skip to content

Step 1 of 3 · Reading · ~2 min

Transactions

Advanced Features

Transactions: queue now, execute atomically later

Real Redis is single-threaded per event loop, which means MULTI/EXEC don't need locks the way a multi-threaded database's transactions do — they just need to buffer commands and run them back-to-back with nothing else interleaved. That's the whole mental model for this lesson: a transaction is a queue, not a rollback mechanism.

State machine, not a data structure

This feature is really about connection state, not a new value type. Track whether the current client is "in" a transaction and, if so, what's queued:

python

MULTI

python

The dispatcher's new branch

This is the part that's easy to get architecturally wrong: once in_multi is true, your main command dispatcher must intercept almost every command before it reaches its normal handler, and queue it instead of running it:

python

MULTI, EXEC, and DISCARD themselves are the only commands that bypass queuing — everything else, including malformed commands, gets queued as-is and only evaluated at EXEC time.

EXEC: run the queue, collect results as an array

python

The critical behavior: one queued command failing does not abort the others. If command #2 in the queue is malformed or type-mismatched, its error gets slotted into the results array in its position, and commands #3, #4, ... still run. This differs from how many people intuitively think of "transactions" (all-or-nothing) — Redis transactions are about isolation from other clients, not atomicity-with-rollback.

DISCARD

python

Edge cases to test explicitly

  • EXEC with no prior MULTI → the specific error string -ERR EXEC without MULTI\r\n, not a generic error.
  • MULTI called while already inside a transaction → -ERR MULTI calls can not be nested\r\n, and the original queue is left untouched.
  • An EXEC'd queue containing a WRONGTYPE-triggering command still executes every other queued command.
  • DISCARD outside a MULTI — decide whether you mirror real Redis's error (-ERR DISCARD without MULTI\r\n) or the simpler idempotent +OK\r\n; check the test cases for which one your grader expects.
Up nextSUBSCRIBE & PUBLISH — Pub/Sub MessagingAdvanced Features

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…