Skip to content

Memcached - Prepend Data

Memcached - Prepending Data to an Existing Item

Section titled “Memcached - Prepending Data to an Existing Item”

The prepend command is an atomic operation that adds data to the beginning of an existing value for a given key. This is useful for tasks like adding metadata or updating a list without needing to first read the entire value.

The basic syntax for the prepend command is as follows:

prepend key flags exptime bytes [noreply]
<value>
  • key: The key of the item to modify.
  • flags: A 32-bit integer stored with the item, retrievable on get calls.
  • exptime: The new expiration time for the item in seconds. A value of 0 means it never expires.
  • bytes: The size in bytes of the data you are prepending.
  • [noreply] (optional): Instructs the server not to send a response, which can improve performance in write-heavy scenarios.
  • value: The data to be prepended.

Let’s demonstrate using telnet. First, we set a key, then we prepend data to it.

# Connect to Memcached
$ telnet localhost 11211
# 1. Set an initial key-value pair
set site 0 900 11
example.com
STORED
# 2. Prepend a prefix to the existing value
prepend site 0 900 8
https://
STORED
# 3. Retrieve the final value
get site
VALUE site 0 19
https://example.com
END

The server responds with STORED on success. If the key does not exist, it will respond with NOT_STORED.

Modern Development: Prepending Data with a Java Client

Section titled “Modern Development: Prepending Data with a Java Client”

In a real application, you will use a client library to interact with Memcached. The following example uses the popular spymemcached library in Java.

Add the spymemcached dependency to your project’s pom.xml:

<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.12.3</version> <!-- Use the latest stable version -->
</dependency>
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;
import java.net.InetSocketAddress;
public class PrependExample {
public static void main(String[] args) {
// Use try-with-resources for automatic connection management and cleanup
try (MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211))) {
System.out.println("Connection to Memcached server successful.");
String key = "user:profile:activity";
String initialActivity = "viewed_homepage";
String newActivity = "clicked_login,";
// 1. Set an initial value for the key (15-minute expiration)
OperationFuture<Boolean> setFuture = mcc.set(key, 900, initialActivity);
if (setFuture.get()) { // .get() blocks until the operation completes
System.out.println("Successfully set initial value for key '" + key + "'.");
}
// 2. Retrieve the current value to verify
System.out.println("Current value: " + mcc.get(key));
// 3. Prepend new activity data to the existing string
OperationFuture<Boolean> prependFuture = mcc.prepend(key, newActivity);
if (prependFuture.get()) {
System.out.println("Successfully prepended '" + newActivity + "'.");
}
// 4. Retrieve the updated value
System.out.println("Updated value: " + mcc.get(key));
} catch (Exception e) {
System.err.println("An error occurred: " + e.getMessage());
// In a production application, use a proper logging framework (e.g., SLF4J)
e.printStackTrace();
}
}
}
Connection to Memcached server successful.
Successfully set initial value for key 'user:profile:activity'.
Current value: viewed_homepage
Successfully prepended 'clicked_login,'.
Updated value: clicked_login,viewed_homepage
  • Atomicity: prepend is an atomic operation. This makes it safe to use in concurrent environments without needing application-level locks for simple prefixing tasks.
  • Key Must Exist: The operation will fail (NOT_STORED) if the key does not already exist in the cache. Your application logic must handle this case, perhaps by setting an initial value first.
  • Item Size Limit: Be mindful of Memcached’s default item size limit (typically 1MB). Repeatedly prepending data to a key without it expiring can cause the item to exceed this limit, resulting in an error.
  • Use Cases: prepend is ideal for maintaining time-ordered lists (where newest items come first), adding prefixes like version numbers or metadata, or building up a log string in cache.