djveremix / redis

Automatically exported from code.google.com/p/redis
0 stars 0 forks source link

[Feature Request] Increment/decrement with value limit #305

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
Atomic incr/decr is a nice feature, but imagine a situation when multiple 
clients increment a key and maximum allowed value is 100.
To enforce that rule we need to get that key, compute the difference and 
increment by that difference, all using watch/multi/exec.

My proposition is to add an optional parameter to incr/decr commands which 
would limit the value of key after incrementation:
INCRBY key integer [limit]
DECRBY key integer [limit]

And sample usage:
>INCRBY key 15 16
15
>INCRBY key 1 16
16
>INCRBY key 2 16
16
>INCRBY key 7
23
>DECRBY key 10 14
14
>INCRBY key 6 10
10

Original issue reported on code.google.com by Felix.z...@gmail.com on 12 Aug 2010 at 7:16

GoogleCodeExporter commented 8 years ago
Hello, I think that for your problem there is a nice atomic solution, since 
INCR returns the new number.

If the returned number is > the threshold, send a decrement command of the same 
amount you incremented (or a INCRBY with inverse increment).

Btw can you please provide a practical example when this is useful? The main 
point of watch is avoiding to add too much specified commands, many times there 
are tricks to avoid WATCH at all but sometimes it's just the right thing to do! 
:)

Cheers,
Salvatore

Original comment by anti...@gmail.com on 31 Aug 2010 at 3:44

GoogleCodeExporter commented 8 years ago
I've been looking at using redis for this basic feature to be honest. The use 
case is fairly simple: in an inventory managed environment you might use 
capping logic to prevent individuals from making more than some set number of 
purchases of a certain type. For example, a theatre may offer tickets to an 
event for students at a lower price, but only for the the first 25 to purchase. 
If you implement a cap against that event and price it would be a very good 
operation to say something like:

>INCRBY key 2 25

And have it only perform the increment of 2 if the amount to increment by would 
be less than or equal to 25, otherwise return an error. It's fast path and 
makes the operation a simple call from the source application. Sure, you could 
read the return result and execute a decrement call if needed, but I think that 
would be a slower operation overall. This model is faster and cleaner.

Original comment by cava...@gmail.com on 25 Jun 2014 at 5:53

GoogleCodeExporter commented 8 years ago
This issue tracker is no longer in use. The project moved to 
https://github.com/antirez/redis.

The requested feature is easily possible with Lua scripts today. You might have 
a look at them: http://redis.io/commands/eval

Original comment by jeredi...@gmail.com on 25 Jun 2014 at 6:02