Decrementing Value in Memcached using Ruby (Detailed Guide w/ Code Examples)

Use Case(s)

A common use case for decrementing a value in Memcached using Ruby is when you're working with counters. For instance, this mechanism can be used to implement rate limiting or inventory management systems where you need to decrement the count of available requests or items.

Code Examples

Here is an example of how to use the decr function in Ruby with Memcached:

require 'dalli' dalli_client ='localhost:11211') dalli_client.set('counter', 10) puts dalli_client.decr('counter') # Output: 9

In this example, we first require the dalli gem, which is a high performance pure Ruby client for accessing memcached servers. Then, we create a new Dalli Client that connects to a memcached server running on localhost port 11211. We set a key called 'counter' to have the value 10. Finally, we call decr on 'counter' which decrements its value by one and then print the new value.

Note: If the key does not exist or the current value is not an integer, it will return nil.

Best Practices

  1. Make sure to check if the key exists and is an integer before calling decr. This will prevent possible errors or unexpected behavior.
  2. Avoid setting negative values as the decr operation won't "wrap around" the value from 0 to the maximum unsigned integer.
  3. Try to use atomic operations like decr or incr whenever possible instead of getting a value, changing it, and setting it back. This helps avoid possible race conditions.

Common Mistakes

Using decr on a non-existing key or one that is not an integer. Ensuring that the key exists and is of the correct type before using decr can help avoid these errors.


  1. What happens if I use decr on a key that doesn't exist?
    It will return nil.
  2. Can I decrement the value by more than 1?
    Yes, you can pass an optional second argument to decrement the value by more than 1. For example: dalli_client.decr('counter', 5) would decrease 'counter' by 5.
  3. What happens if the value becomes negative after decrementing?
    The value won't go below 0. If decrementing would make it less than 0, it's set to 0 instead.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.