PHP Memcached CAS (Detailed Guide w/ Code Examples)

Use Case(s)

CAS, or Check-And-Set, is a method used in the PHP Memcached client for handling concurrent modifications. It helps avoid race conditions when multiple processes are trying to read and write to the same key simultaneously.

A common use case would be a web app where multiple clients might try to update a user's profile at the same time; using CAS can ensure that no data gets overwritten unintentionally.

Code Examples

Example 1:

// Create instance of Memcached $memcached = new Memcached(); $memcached->addServer('localhost', 11211); // Get a value and its CAS token list($cas_token, $value) = $memcached->gets('key'); // Modify value $value .= 'Additional Data'; // Attempt to store the value back only if it hasn't been changed by someone else if ($memcached->cas($cas_token, 'key', $value)) { echo "Success: Value updated\n"; } else { echo "Error: Value has been modified by someone else\n"; }

In this example, we first retrieve the value stored under 'key' along with its CAS token. The value is then modified, and cas() is used to attempt to update the value only if no other process has modified it in the meantime.

Best Practices

  1. Always retrieve the CAS token alongside the value (using methods like Memcached::gets or Memcached::getMulti) before attempting to use cas(). This allows you to see if the data has been altered since your last get.

  2. Be prepared to handle cases where cas() returns false due to the value being updated by another process. This could involve re-fetching the data and trying again, or notifying the user of the concurrent modification.

Common Mistakes

  1. A common mistake is not checking the return value of cas(). This method returns false if the original value was modified by another process, or true on success. Ignoring this return value can lead to overwriting changes made by other processes unknowingly.

  2. Another mistake is using Memcached::get instead of Memcached::gets. The former does not retrieve the CAS token, rendering it impossible to use cas() correctly.


  1. Why do I get a false return from cas() even though I know no one else has modified the value?

    It's possible that Memcached has evicted your item due to memory limitations. When Memcached runs out of memory, it starts removing older items, which invalidates their CAS tokens.

  2. When should I use cas() instead of just set()?

    You should use cas() when you're dealing with shared data that might be accessed and modified by multiple processes at the same time. If you only have single-process access or don't care about overwriting concurrent modifications, using set() would be simpler.

Was this content helpful?

Start building today

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