0
0
Redisquery~5 mins

Multi-key transactions for consistency in Redis

Choose your learning style9 modes available
Introduction

Multi-key transactions help keep data correct when changing several things at once. They make sure all changes happen together or not at all.

When you want to update multiple related values in Redis without errors.
When you need to make sure no other changes happen between your updates.
When you want to avoid partial updates that could cause wrong data.
When you are handling money transfers between accounts stored in Redis.
When you want to keep counters or stats consistent across keys.
Syntax
Redis
MULTI
  command1
  command2
  ...
EXEC
Use MULTI to start a transaction block.
Commands queued after MULTI run together when EXEC is called.
Examples
This increments two keys together. Both increments happen or none.
Redis
MULTI
INCR key1
INCR key2
EXEC
This sets two keys to new values in one transaction.
Redis
MULTI
SET key1 "value1"
SET key2 "value2"
EXEC
Sample Program

This transaction sets balances for two users together. Then it gets their balances to show the result.

Redis
MULTI
SET user:1:balance 100
SET user:2:balance 200
EXEC
GET user:1:balance
GET user:2:balance
OutputSuccess
Important Notes

Commands inside MULTI are queued and run only when EXEC is called.

If any command fails, EXEC still runs all commands; Redis does not rollback automatically.

Use WATCH to monitor keys for changes before starting MULTI for safer transactions.

Summary

Multi-key transactions group commands to run together for data consistency.

Use MULTI and EXEC to start and run the transaction.

They help avoid partial updates and keep related data correct.