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
MULTI→ enters transaction mode, returns+OK- All subsequent commands return
+QUEUEDinstead of executing EXEC→ executes all queued commands, returns results as RESP arrayDISCARD→ 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
EXECwithoutMULTI→-ERR EXEC without MULTIMULTIinsideMULTI→-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…