Introducing Dragonfly Cloud! Learn More

CAS Operations in Memcached using Ruby (Detailed Guide w/ Code Examples)

Use Case(s)

Check and set (CAS) operations are commonly used in Memcached to ensure that the cache value is only changed if it has not been altered since you last fetched it. This is useful in concurrent environments where multiple processes may be attempting to update the same key-value pair.

Code Examples

Here is an example of how to use CAS in Memcached with Ruby:

require 'memcached' cache = Memcached.new('localhost:11211') # Set key-value pair cache.set('key', 'value') begin cache.cas('key') do |current_value| # Modify the current value current_value.upcase! end rescue Memcached::NotStored puts "Value was updated by another process" end

In this example, we're setting a key-value pair, then we're trying to update it using the cas method. The block passed to cas receives the current value, modifies it, and its return value will be stored back in Memcached. If the value has been changed by another process after we fetched it but before we could store the new value, a Memcached::NotStored exception is raised.

Best Practices

  • Ensure error handling is properly done for Memcached::NotStored exception.
  • Avoid lengthy operations inside the cas block to minimize the chance of conflicts.

Common Mistakes

  • Not handling the Memcached::NotStored exception, leading to silent failures.
  • Performing operations that can potentially take a long time inside the cas block.

FAQs

Q: Can I perform other operations inside the cas block? A: Yes, you can perform any operation inside the cas block. However, ensure these operations are quick to minimize the chance of another process changing the value before you can store your changes.

Q: What happens if two processes try to update the same key simultaneously? A: If two processes try to update the same key simultaneously using cas, one of them will get a Memcached::NotStored exception. The one that gets the exception should handle it and decide what to do next.

Was this content helpful?

Start building today 

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