Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define start number for redis INCR

Tags:

redis

I want to increment a redis counter but I want to start counting not from zero but from a defined starting number (for example -5).

I know how this can be achieved via SET/INCR inside a Lua script but I was wondering if I can achieve it only with INCR command. Something similar we define for INCRBY where the increment is defined, can we define the starting point?

like image 443
georgeliatsos Avatar asked Sep 10 '25 15:09

georgeliatsos


2 Answers

Lua is perfectly fine for this procedure, but you can also do it with a transaction:

MULTI
SET counter -5 NX
INCR counter
EXEC

The INCR will run every time, so if you want your first call to set it to -5 you should change the SET value to -6. You can also pipe those 4 commands to avoid the 4 RTTs of sending the commands.

like image 107
Ofir Luzon Avatar answered Sep 13 '25 04:09

Ofir Luzon


You can't do it with the INCR command alone. I would inspect the value of SETNX and if it returns 0 (meaning the key existed), then increment it.

Notice that if you are talking about non expiring counters, you can achieve atomicity this way without Lua, at the price of two roundtrips: If the key did not exist, we create it, set it to the initial value and that's it, one roundtrip, atomic. If it did exist, we increment it, but we are still consistent (unless the key expired or was deleted between the two calls).

However, there is no reason not to use a Lua script for this, it's the preferred way to do this stuff.

like image 40
Not_a_Golfer Avatar answered Sep 13 '25 04:09

Not_a_Golfer