Skip to content

Memcached - Delete Data

The delete command removes an existing key-value pair from the Memcached server. This operation is fundamental for cache invalidation strategies.

The basic syntax for the delete command via a telnet connection is:

delete key [noreply]

The server will respond with one of the following:

  • DELETED: The key was found and successfully removed.
  • NOT_FOUND: The key did not exist on the server.
  • ERROR: Indicates an error in the command syntax.

In this example, we’ll use telnet to connect to a Memcached server. First, we set a key named session_token, verify it exists, delete it, and then verify it’s gone.

# First, set a key-value pair
set session_token 0 3600 36
xyz-abc-123-789-pqr-lmn-456-def
STORED
# Retrieve the key to confirm it's there
get session_token
VALUE session_token 0 36
xyz-abc-123-789-pqr-lmn-456-def
END
# Now, delete the key
delete session_token
DELETED
# Try to retrieve the key again
get session_token
END
# Try to delete the same key again
delete session_token
NOT_FOUND

In a real-world application, you’ll use a client library to interact with Memcached. Here, we’ll use spymemcached, a popular Java client. The modern approach is to manage dependencies with a build tool like Maven or Gradle and to handle resources safely.

Add the spymemcached dependency to your pom.xml if you are using Maven:

<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.3</version> <!-- Use the latest stable version -->
</dependency>

This example demonstrates how to connect to the server, set a value, confirm its existence, delete it, and then confirm its deletion. We use a try-with-resources block to ensure the client connection is always closed properly.

import net.spy.memcached.MemcachedClient;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.internal.OperationFuture;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class MemcachedDeleteExample {
public static void main(String[] args) {
String serverAddress = "127.0.0.1:11211";
String key = "user:123:profile";
String value = "{"name":"John Doe", "email":"john.doe@example.com"}";
int expiration = 3600; // 1 hour
try (MemcachedClient client = new MemcachedClient(AddrUtil.getAddresses(serverAddress))) {
System.out.println("Connection to Memcached server successful.");
// 1. Set a value to be deleted later
OperationFuture<Boolean> setFuture = client.set(key, expiration, value);
if (setFuture.get()) {
System.out.println("Successfully set key '" + key + "'.");
} else {
System.err.println("Failed to set key '" + key + "'.");
return;
}
// 2. Verify the value exists
Object retrievedValue = client.get(key);
System.out.println("Retrieved value before delete: " + retrievedValue);
// 3. Delete the value
OperationFuture<Boolean> deleteFuture = client.delete(key);
if (deleteFuture.get()) {
System.out.println("Successfully deleted key '" + key + "'.");
} else {
System.out.println("Failed to delete key '" + key + "' (it may not have existed).");
}
// 4. Verify the value is now null
retrievedValue = client.get(key);
System.out.println("Retrieved value after delete: " + retrievedValue);
} catch (IOException | InterruptedException | ExecutionException e) {
System.err.println("An error occurred: " + e.getMessage());
// In a real app, you would log this exception
Thread.currentThread().interrupt();
}
}
}

When you compile and run the above program, you should see the following output:

Connection to Memcached server successful.
Successfully set key 'user:123:profile'.
Retrieved value before delete: {"name":"John Doe", "email":"john.doe@example.com"}
Successfully deleted key 'user:123:profile'.
Retrieved value after delete: null
  • Cache Invalidation: Use delete to remove stale data from the cache when the source of truth (e.g., a database record) is updated or deleted.
  • Error Handling: The Future returned by delete can fail. Always check the result and handle potential exceptions to build a robust application.
  • Resource Management: Always close your Memcached client connection to release network resources. Using a try-with-resources statement is the recommended way to do this in Java.