Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Memcached Basics

Append, Prepend, Incr, Decr and Touch

Use Memcached's in-place commands: append and prepend for building values, incr and decr for atomic counters, and touch or gat to extend a TTL without rewriting data.

Not every update needs a full read-modify-write cycle. Memcached has commands that change an item inside the server, in a single atomic step: add text to the end of a value, bump a counter, or push the expiry forward. They are faster than fetching, changing and storing again, and, because the server does them atomically, they are free of the race conditions a read-modify-write would have.

This lesson covers append, prepend, incr, decr, touch and gat.

append and prepend

append adds bytes to the end of an existing value; prepend adds them to the front. If the key does not exist, both answer NOT_STORED. Flags and expiry are not changed.

TEXT
append <key> <flags> <exptime> <bytes>

The flags and exptime fields are required by the syntax but ignored by the server for append and prepend.

A classic use is a log-like value or a list of ids encoded as text, such as a comma-separated list of recently viewed products.

Python Build a value with append and prepend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The value grows without limit, so you must cap it yourself. Growing items also change slab class, which has a memory cost (see Performance and Sizing). Another caveat: if the item is evicted, you silently lose the whole history, so only keep data this way that you can rebuild.

incr and decr: atomic counters

incr adds a number to a counter; decr subtracts. The stored value must be an ASCII decimal number, and the server returns the new value.

TEXT
incr <key> <value>
decr <key> <value>

Rules worth knowing:

  • If the key does not exist the answer is NOT_FOUND. Memcached does not create counters for you; you add a starting value first.
  • incr works on 64-bit unsigned integers and wraps around to 0 on overflow.
  • decr never goes below 0; decrementing 5 by 10 gives 0.
  • If the stored value is not a number, the server replies with a CLIENT_ERROR.
  • decr does not guarantee the stored text gets shorter (older servers pad with spaces), so parse the value with int() after get, which ignores trailing spaces.

Counters are the standard way to build page-view counts, rate limiters and quotas, because two web servers can incr the same key at once without losing updates.

Python Counters with incr and decr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A fixed-window rate limiter

Counters plus an expiry give you a rate limiter in a few lines. The first request in a window creates the counter with a TTL equal to the window; later requests increment it; once the count exceeds the limit, reject.

Python Rate limiting with add and incr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

There is a subtle failure: if the counter expires between add and incr, incr answers NOT_FOUND. Production code handles that by retrying the add. The pattern is also approximate: a burst at the end of one window plus a burst at the start of the next can briefly exceed the intended rate.

touch and gat

touch changes an item's expiry without reading or rewriting its value, and answers TOUCHED or NOT_FOUND. gat ("get and touch") fetches the value and updates the expiry in one command; gats also returns the CAS token.

TEXT
touch <key> <exptime>
gat <exptime> <key> [<key> ...]

This gives you sliding expiration: a session that lives 30 minutes since the last request.

Python Sliding expiration with touch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

At minute 10 and 25 the session is alive and gets extended; the third check at minute 50 finds it still alive because each touch pushed the deadline out. Without the touches it would have died at minute 30.

Atomic does not mean durable

All of these commands are atomic on one server, but nothing here makes the data safe: a counter can be evicted, expired or lost when the server restarts. Use Memcached counters for approximations and throttling, not for money or inventory.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does incr return when the key does not exist?

    Memcached does not auto-create counters. Use add to create the starting value first.
  2. 2. What is the result of decr on a counter holding 5 by 10?

    Memcached counters are unsigned, and decr stops at 0.
  3. 3. Which command extends an item's expiry without rewriting its value?

    touch updates only the expiry and answers TOUCHED or NOT_FOUND.
  4. 4. Why is incr safer than get followed by set for a shared counter?

    With get-then-set two clients can read the same value and overwrite each other. incr happens in one step inside the server.

Summary

  • append and prepend extend a value in place; they fail with NOT_STORED if the key is missing and keep flags and expiry.
  • incr and decr are atomic counters on unsigned 64-bit numbers; decr stops at 0, and a missing key gives NOT_FOUND.
  • touch and gat renew expiry for sliding sessions.
  • Combine add and incr with a TTL for a simple rate limiter.
  • Atomic is not durable: counters can still be evicted or lost.

Next: CAS and Concurrent Updates