Skip to content
MULTI & EXEC — Transactions
step 1/3

Reading — step 1 of 3

Transactions

~1 min readAdvanced Features

MULTI & EXEC — Transactions

Redis transactions group commands to execute atomically — no other client can interleave.

How Transactions Work

  1. MULTI → enters transaction mode, returns +OK
  2. All subsequent commands return +QUEUED instead of executing
  3. EXEC → executes all queued commands, returns results as RESP array
  4. DISCARD → cancels the transaction, returns +OK

Example

MULTI           → +OK
SET name Alice  → +QUEUED
GET name        → +QUEUED
EXEC            → *2\r\n+OK\r\n$5\r\nAlice\r\n

Error Handling

  • EXEC without MULTI-ERR EXEC without MULTI
  • MULTI inside MULTI-ERR MULTI calls can not be nested
  • Errors in queued commands appear in the EXEC result array but don't abort the transaction

Implementation

Use a boolean flag in_transaction and a list queue. In transaction mode, append commands to the queue instead of executing. On EXEC, execute all queued commands and collect results.

Congratulations — you've built Redis from scratch!

Discussion

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

Sign in to post a comment or reply.

Loading…