Can a key expire within a MULTI/EXEC transaction?

Last updated 08, May 2024

Question

Can a key expire within a MULTI/EXEC transaction?

Answer

Keys can expire within a MULTI/EXEC transaction. Check the following example.

127.0.0.1:6379> GET cnt
"1"
127.0.0.1:6379> EXPIRE cnt 10
(integer) 1
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> INCR cnt
QUEUED

Wait some time and execute the transaction.

127.0.0.1:6379(TX)> EXEC
1) (integer) 1
127.0.0.1:6379> GET cnt
"1"

The key cnt has expired in the transaction, then reinitialized by the INCR command to 1.

Expired WATCHed keys

Note also that in Redis versions before 6.0.9, an expired watched key would not cause a transaction to be aborted. Starting with 6.0.9, watched keys expiration cause transactions abortion.

127.0.0.1:6379> EXPIRE cnt 20
(integer) 1
127.0.0.1:6379> WATCH cnt
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> SET hola mundo
QUEUED

Wait some time, and observe how the transaction is aborted.

127.0.0.1:6379(TX)> EXEC
(nil)

Modifying the TTL in a MULTI/EXEC transaction

The expiration time of a key can be modified directly within a MULTI/EXEC transaction.

127.0.0.1:6379> EXPIRE cnt 30
(integer) 1
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> EXPIRE cnt 1000
QUEUED
127.0.0.1:6379(TX)> EXEC
1) (integer) 1
127.0.0.1:6379> TTL cnt
(integer) 994