Skip to content

Memcached - Set Data

The Memcached set command is the most fundamental and widely used write operation. It stores a key-value pair in the cache. If the key already exists, set will unconditionally overwrite its current value and expiration time.

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

set key flags exptime bytes [noreply]
value
  • key: The name of the key to store the data under.
  • flags: A 32-bit integer that is stored with the value and returned on retrieval. Client libraries often use this for serialization metadata (e.g., distinguishing between strings, numbers, and pickled objects).
  • exptime: The expiration time in seconds. A value of 0 means the item never expires. If the value is over 30 days (2592000), it’s treated as a Unix timestamp of the absolute expiration time.
  • bytes: The length of the value in bytes.
  • noreply (optional): Instructs the server not to send a response, reducing latency.
  • value: The data to be stored, sent on a new line.
  • STORED indicates the data was successfully stored.
  • ERROR indicates a syntax error or other issue during storage.

This example demonstrates setting a key, verifying it, and then overwriting it with a new value.

# 1. Set a key 'website:title' with a 15-minute (900s) expiration.
set website:title 0 900 23
World's Largest Library
STORED
# 2. Retrieve the value to confirm.
get website:title
VALUE website:title 0 23
World's Largest Library
END
# 3. Set the same key again with a new value. This overwrites the old one.
set website:title 0 900 25
Modern Tech Tutorials
STORED
# 4. Verify the new value is in place.
get website:title
VALUE website:title 0 25
Modern Tech Tutorials
END

Modern Application: Storing Data with Python

Section titled “Modern Application: Storing Data with Python”

In a modern application, you’ll use a client library. Here’s how to use set with Python and pymemcache, including how to handle different data types.

First, install the library using pip:

pip install pymemcache
import json
from pymemcache.client.base import Client
from pymemcache.serde import Serde
MEMCACHED_SERVER = ('127.0.0.1', 11211)
# Best Practice: Use a serializer for non-string data.
# This ensures data is stored and retrieved consistently.
json_serde = Serde(
serializer=lambda k, v: (json.dumps(v).encode('utf-8'), 1),
deserializer=lambda k, v, f: json.loads(v.decode('utf-8')) if f == 1 else v
)
def run_set_example():
"""Demonstrates setting various data types in Memcached."""
# Pass the serializer to the client on initialization
client = Client(MEMCACHED_SERVER, serde=json_serde)
try:
# --- Example 1: Storing a simple string ---
key1 = 'api:status_message'
value1 = 'Service is running normally.'
client.set(key1, value1, expire=300)
retrieved1 = client.get(key1)
print(f"Set and got string: '{retrieved1}'")
# --- Example 2: Storing a dictionary (using JSON serde) ---
key2 = 'user:profile:42'
value2 = {
'username': 'jane_doe',
'email': 'jane.doe@example.com',
'roles': ['editor', 'commenter'],
'last_login_ts': 1672531200
}
client.set(key2, value2, expire=3600)
retrieved2 = client.get(key2)
print(f"Set and got dictionary: {retrieved2}")
print(f"Type of retrieved object: {type(retrieved2)}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
client.close()
print("Connection closed.")
if __name__ == "__main__":
run_set_example()
Set and got string: 'Service is running normally.'
Set and got dictionary: {'username': 'jane_doe', 'email': 'jane.doe@example.com', 'roles': ['editor', 'commenter'], 'last_login_ts': 1672531200}
Type of retrieved object: <class 'dict'>
Connection closed.

Best Practices and Real-World Applications

Section titled “Best Practices and Real-World Applications”
  • Primary Caching Strategy: set is the workhorse of caching. The most common use case is caching the result of an expensive database query or an API call. A web application would first try to get the data from Memcached. On a cache miss, it fetches from the database and then uses set to store the result in the cache for subsequent requests.
  • Choose a TTL Wisely: Setting an appropriate Time-To-Live (expire) is crucial. For data that changes infrequently, a long TTL is fine. For rapidly changing data, a short TTL (e.g., 60 seconds) is better to reduce staleness. Never-expiring keys (expire=0) should be used with caution as they can fill up the cache.
  • Serialization: Always use a consistent serialization method (like JSON) for complex data types. This ensures that what you set is what you get, regardless of the client library or programming language used to access the cache.
  • set vs. add vs. replace: Remember the difference: set always works (create or update). add only works if the key does not exist. replace only works if the key already exists.