Memcached’s append and prepend commands let you modify existing values without fetching and re-setting them, which sounds like a database operation but happens entirely in RAM.
Let’s see it in action. Imagine a simple counter where we want to increment a value. We’ll start with a key, say mycounter, and set an initial value of 0.
echo "set mycounter 0 60 1" | nc localhost 11211
> STORED
Now, instead of getting mycounter, adding 1, and setting it back, we can append the character 1.
echo "append mycounter 0 60 1\r\n1" | nc localhost 11211
> STORED
If we retrieve mycounter:
echo "get mycounter" | nc localhost 11211
> VALUE mycounter 0 2
01
> END
Notice the value is now 01. If we wanted to increment it to 02, we’d append 2:
echo "append mycounter 0 60 1\r\n2" | nc localhost 11211
> STORED
Retrieving again:
echo "get mycounter" | nc localhost 11211
> VALUE mycounter 0 3
012
> END
This isn’t a true numerical increment; it’s string concatenation. prepend works the same way, but adds the new data to the beginning of the existing value.
This capability is surprisingly useful for building lightweight, in-memory logs or queues where you want to atomically add data to a record without the overhead of a full get-and-set cycle. Think of it as building up a string of events or data points associated with a key. For example, you could store a user’s recent activity IDs, appending each new ID as it occurs.
The key insight is that append and prepend are atomic operations within Memcached. This means that if multiple clients try to append or prepend to the same key concurrently, Memcached handles the interleaving. The final result will be a concatenation of all the appended/prepended data, but the internal state of the value at any given moment is consistent. This avoids race conditions that would occur if you were doing a traditional get-modify-set.
The append and prepend commands require the value to be sent on a separate line, terminated by \r\n. The flags and exptime fields in the command itself are ignored; only the bytes field matters and must accurately reflect the length of the value being appended or prepended.
The next logical step is to consider how to atomically remove data from these in-place modified values, which is where custom commands or client-side logic become necessary.