Skip to content

Memcached - Delete Key

The Memcached delete command is used to remove an existing key-value pair from the cache. This operation is fundamental for implementing cache invalidation strategies, ensuring that stale data is removed when the source data changes (e.g., an entry is updated in your database).

When interacting with Memcached directly (e.g., via telnet), the syntax is:

delete key [noreply]

key is the key to be deleted. The optional noreply parameter tells the server not to send a response, which can improve performance in high-throughput scenarios.

The server will respond with one of the following:

  • DELETED indicates that the key was found and successfully deleted.
  • NOT_FOUND indicates that the key did not exist in the cache.
  • ERROR indicates a syntax error in the command.

This example demonstrates setting a key, verifying its existence, deleting it, and then confirming its removal.

# 1. Set a key 'user:session:42' with a value and 900s TTL.
set user:session:42 0 900 36
{"userId": 42, "role": "admin"}
STORED
# 2. Retrieve the key to confirm it was stored.
get user:session:42
VALUE user:session:42 0 36
{"userId": 42, "role": "admin"}
END
# 3. Delete the key.
delete user:session:42
DELETED
# 4. Attempt to retrieve the key again; it's gone.
get user:session:42
END
# 5. Attempt to delete the same key again.
delete user:session:42
NOT_FOUND

Modern Application: Deleting Data with Python

Section titled “Modern Application: Deleting Data with Python”

In modern applications, you’ll use a client library to interact with Memcached. Here’s how to delete data using Python with the pymemcache library, a popular and well-maintained choice.

First, install the library using a package manager like pip. It’s a best practice to manage your project’s dependencies in a requirements.txt file.

# In your terminal
pip install pymemcache
# Add to your requirements.txt
pymemcache>=4.0.0
from pymemcache.client.base import Client
from pymemcache.exceptions import MemcacheUnexpectedCloseError
# Best Practice: Use environment variables for configuration.
# In a cloud environment, this would point to a managed service like AWS ElastiCache.
MEMCACHED_SERVER = ('127.0.0.1', 11211)
def run_delete_example():
"""Demonstrates the full lifecycle of setting, verifying, deleting, and re-verifying a key."""
client = None
try:
client = Client(MEMCACHED_SERVER, connect_timeout=2, timeout=2)
# Check if the server is reachable
client.version()
print(f"Successfully connected to Memcached server at {MEMCACHED_SERVER}")
except (ConnectionRefusedError, MemcacheUnexpectedCloseError, TimeoutError):
print(f"Error: Connection to Memcached server at {MEMCACHED_SERVER} failed. Is it running?")
return
key = 'user:profile:123'
value = '{"name": "John Doe", "status": "active"}'
try:
# 1. Set an initial value
client.set(key, value, expire=300)
print(f"-> SET: Key '{key}' with value '{value}'")
# 2. Verify the key exists
retrieved = client.get(key)
if retrieved:
print(f"-> GET: Found key '{key}': {retrieved.decode('utf-8')}")
else:
print(f"[ERROR] Verification failed: Key '{key}' not found after setting.")
return
# 3. Delete the key
# The delete method returns True if the key existed and was deleted, False otherwise.
was_deleted = client.delete(key)
print(f"-> DELETE: Attempting to delete key '{key}'...")
if was_deleted:
print(" Result: Success. The key was found and deleted.")
else:
print(" Result: Failure. The key was not found when delete was attempted.")
# 4. Verify the key is gone
retrieved_after_delete = client.get(key)
if retrieved_after_delete is None:
print(f"-> GET: Verification successful. Key '{key}' is no longer in the cache.")
else:
print("[ERROR] Key was found in cache after deletion.")
except Exception as e:
print(f"An unexpected error occurred during cache operations: {e}")
finally:
if client:
client.close()
print("Connection closed.")
if __name__ == "__main__":
run_delete_example()
Successfully connected to Memcached server at ('127.0.0.1', 11211)
-> SET: Key 'user:profile:123' with value '{"name": "John Doe", "status": "active"}'
-> GET: Found key 'user:profile:123': {"name": "John Doe", "status": "active"}
-> DELETE: Attempting to delete key 'user:profile:123'...
Result: Success. The key was found and deleted.
-> GET: Verification successful. Key 'user:profile:123' is no longer in the cache.
Connection closed.

Best Practices and Real-World Applications

Section titled “Best Practices and Real-World Applications”
  • Cache Invalidation: The primary use for delete is invalidating cached data. When a user updates their profile in your database, you must delete the corresponding user:profile:<id> key from Memcached to prevent serving stale information.
  • User Logout: When a user logs out, their session data, often stored in Memcached for fast access, must be invalidated. A call to client.delete('session:' + user_id) is a perfect use case.
  • Graceful Handling: The delete command does not raise an error if the key doesn’t exist. Your application logic should rely on the boolean return value (True/False) rather than assuming the key was always present.
  • Performance with noreply: For ‘fire-and-forget’ deletions where confirmation is not critical (like cleaning up temporary keys), using client.delete(key, noreply=True) can reduce network round-trip time and slightly improve application performance.