Introducing Dragonfly Cloud! Learn More

Question: Where and how does Memcached store data?


Memcached stores data in the form of key-value pairs, where both keys and values are strings. When a client sends a request to store or retrieve data, it specifies the key string associated with the data.

Memcached uses a hash table to store these key-value pairs. The hash table is divided into a fixed number of buckets, typically 1024 by default, each containing a linked list of key-value pairs. The client's key is hashed, and the resulting value is used to determine which bucket the data should be stored in.

When storing data in Memcached, the client sends the key-value pair to the Memcached server, which hashes the key to determine which bucket the data should be stored in. If the bucket already contains an entry for that key, the new value overwrites the old one. If that bucket does not contain any entry for that key, a new key-value pair is appended to the linked list in the corresponding bucket.

When retrieving data from Memcached, the client sends the key associated with the data it wants to retrieve. The server performs a lookup of the key in the hash table and returns the associated value if it exists. If the key is not found in the hash table, Memcached returns a miss and the client must retrieve the data from its original source.

Here's an example code snippet showing how to set and get values in Memcached using the Python python-memcached library:

import memcache # Connect to a Memcached server running on localhost client = memcache.Client(['']) # Store a key-value pair client.set('my_key', 'my_value') # Retrieve the value for a key value = client.get('my_key') print(value)

This code sets the value 'my_value' for the key 'my_key' in Memcached, then retrieves and prints it.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

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