Redis Transactions
Redis supports transaction operations in distributed environments. Transactions allow multiple commands to be executed as a single unit, where all commands within the transaction are serialized and executed sequentially. During execution, a transaction is not interrupted by command requests from other clients. The server will only continue processing commands for other clients after completing all commands within the current transaction.
Redis transaction operations consist of three phases: opening a transaction, queuing commands, and executing the transaction.
- Transaction Opening: The client executes the
MULTIcommand to open a transaction. - Request Submission: The client submits commands to the transaction.
- Queueing: Redis places the client's request into a transaction queue for later execution.
- Status Feedback: The server returns
QUEUED, indicating that the command has been added to the transaction queue. - Execution: The client executes the transaction using the
EXECcommand. - Error Handling: If a command within a Redis transaction fails, other commands continue to execute; the transaction does not rollback automatically. You can use
WATCHto monitor the execution status and handle exceptions caused by command execution errors. - Result Return: The server returns the result of the transaction execution to the client.
Redis Transaction Commands
The relevant commands for Redis transactions are MULTI, EXEC, DISCARD, WATCH, and UNWATCH:
| Command | Description |
|---|---|
| MULTI | Marks the beginning of a transaction block |
| EXEC | Executes all commands within the transaction block |
| DISCARD | Discards the current transaction, aborting execution of all commands in the block |
| WATCH | Monitors one (or more) keys; if any of these keys are modified by other commands before the transaction executes, the transaction will be aborted |
| UNWATCH | Cancels monitoring for all keys set by a WATCH command |
Redis Transactions and ACID
Generally, transactions have four ACID properties: Atomicity, Consistency, Isolation, and Durability.
- Atomicity: Redis transactions are atomic; all commands either execute completely or not at all.
- Consistency: Redis transactions ensure that if a command fails, the data can be rolled back to its pre-execution state, unless the Redis process terminates unexpectedly.
- Isolation: Redis transactions provide isolation but do not support isolation levels found in structured databases.
- Durability: Redis transactions do not guarantee durability because both RDB and AOF persistence strategies in Redis are asynchronous.