Definition of Success

Sign with Failure (left) and Success (right)

Last time I had a task to optimize a cache deletion in a legacy code which seemed weird and it begged for refactoring. So I started it and ran into some unexpected behaviour in the PHP Memcache library methods. Before I go forward here is the original method:

What does the original method do?

function my_memcache_delete($key, $time)
{
    global $memcache;
    $i = 0;
    do {
        $memcache->delete($key, $time);
        if ($i >= 1000) {
            return false;
        }
        $i++;
    } while ($memcache->get($key));
}
  1. It is deleting the $key from the Memcached
  2. Get the $key from Memcached and exit if it does not exist (the deletion was successful)
  3. Retry a maximum of 1000 times the deletion before giving up and returning (exit from the method)

First try

So we saw when deleting keys from the cache it also calls a $memcache->get(). It seems unnecessary when we are sure the deletion was successfully executed and the documentation says:

Returns true on success or false on failure.

memcache delete() – Return Values

OK then we can remove the $memcache->get() check from the exit condition and we can use the return value of the $memcache-delete() safely. Right?

function my_memcache_delete($key, $time)
{
    global $memcache;
    $i = 0;
    do {
        $success = $memcache->delete($key, $time);
        if ($i >= 1000) {
            return false;
        }
        $i++;
    } while (!$success);
}

When I made this change the test ran much longer than on the original code.

What? Why?

It took me a while to figure it out. The delete() method always returns false.

Hey! Why did it return false?

At this point, I am starting to suspect that Memcache::delete() is not working as I expected. I read the comments in the PHP documentation and StackOverflow but can’t find any proper explanation. I had to do my research to recognize that success is not what I thought.

What is success?

For the extension developer or document writer it means the key can only be removable then it exists in the service and any other case is unsuccess.

So when the key does not exist, then the deletion fails. If it exists then the deletion is successful.

Well, for me the success of the Memcache::delete() is when the call or request is processed properly and the key surely does not exist in the service.

I was burned out.

If you are curious about the solution and the result of my research, please visit my php-memcache-smart-deletion repository on GitHub.

tl;dr

Use set instead of delete. It’s obvious, isn’t it?

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.