Read and reset a counter
A producer increments an event counter, while a consumer periodically reads and clears the accumulated count as one atomic operation.
Redis · Module
GETSET atomically replaces a key's string value and returns the value previously stored there. It is deprecated since Redis 6.2.0; new code should use SET with GET.
GETSET performs an atomic replacement of a key's string value and returns the value that was there before. If the key is absent, it creates it and returns a nil reply; a successful replacement also removes any existing expiration.
GETSET key value| Name | Type | Description |
|---|---|---|
key | RedisArgument | The name of the key. |
value | RedisArgument | The new value to set. |
A bulk string containing the old value, or a nil reply if the key does not exist; an error is returned when the existing key is not a string.
redis-cli SET mykey "Hello"
redis-cli GETSET mykey "World"
redis-cli GET mykeyThe command replaces the existing string and prints its previous value; the final GET confirms the new value.
A producer increments an event counter, while a consumer periodically reads and clears the accumulated count as one atomic operation.
A legacy Redis integration needs to preserve the atomic replace-and-return-old-value behavior during migration.
GETSET atomically writes a new string value and returns the old string value. If the key does not exist, it returns nil after creating the key.
Follow-up: How should new code replace GETSET? Use SET with the GET option, which provides the replacement-and-return-old-value behavior while avoiding this deprecated command.
It returns a bulk string containing the prior value, or a nil reply when the key is absent. If the key exists with a non-string value, Redis returns an error.
Follow-up: What happens to expiration? A successful replacement discards the key's previous TTL, so use an appropriate SET expiration option when migrating.
The command is atomic, so it is useful when a counter must be read and reset without an intervening update. A documented pattern increments a counter with INCR and resets it with GETSET mycounter "0".
Follow-up: Why is SET GET preferable for new implementations? GETSET is deprecated as of Redis 6.2.0, while SET supports the GET option and additional expiration controls.
SETGETINCRGETEXGETDEL