[NEW] INCRBY and EXPIRE
The Problem/Use-Case This Feature Addresses
When using counters, you often need to set them to expire after a certain period. Currently, the only known solution is:
- Call
INCRBY. - If the returned result equals the initial value (indicating a new record was created), call
EXPIRE.
This issue is also discussed in the following resources:
To avoid the race condition where INCRBY executes but EXPIRE does not, the recommended approach is to use a Lua script via EVAL. However, this method negatively impacts performance.
Alternatives Considered
It would be beneficial to have a single command that combines both operations—only applying expiration when the record is initially created. Using a transaction isn't ideal because EXPIRE will always execute, unnecessarily updating the TTL.
A clean solution would be to introduce an additional parameter, EX, to the INCR family of commands, similar to how it's used in SET.
Another alternative is to enhance the EXPIRE command by adding an NX option. With NX, EXPIRE would only apply if the key does not already have an expiration, making it more flexible.
Hi fellow Erlang programmer! 😄
EXPIRE already has the NX option. You can use it.
Adding options to INCR sounds like a good idea to me. We could add EX, PX, NX, XX.
Hello @zuiderkwast, all great projects seem to have you involved ! Yes, the main idea behind the ticket was to add at least EX and NX options to INCR to avoid having to use Lua scripts like:
value = INCR(ip)
IF value == 1 THEN
EXPIRE(ip,1)
END
Yeah, so you can use INCR ip ; EXPIRE ip 1 NX in a transaction to avoid the conditional code and the round trip.
If we add LT and EX to INCR, you'd be able to write the whole conditional increment with expire with just one command, like
INCR ip LT 10 EX 1 NX
Discussion was that we'll extend INCR, INCRBY, DECR, and DECRBY with:
- NX: Only increment it if the key does not exist. XX would be useful.
- EX/EXAT: Set the expire. We will need to rewrite the command to be
SET EXAT Yto avoid clock skew and be very compatible with the API. Probably also add PXAT and PX. - GT and LT were suggested, but we didn't get consensus on if those should be added now.
We might need to also update the HINCRBY series of commands.
@PingXie @enjoy-binbin @soloestoy Please weigh in.
Nobody cared about incrbyfloat, so we decided not to update that one.