Incrementing Values in Memcached using Golang (Detailed Guide w/ Code Examples)

Use Case(s)

The incr function in Memcached is often used when you want to increment a numeric value stored in the cache. This is useful for implementing counters, such as keeping track of the number of page views or API calls.

Code Examples

Consider the following example where we increment a key's value:

package main import ( "" "log" ) func main() { mc := memcache.New("") // Set initial value err := mc.Set(&memcache.Item{Key: "pageviews", Value: []byte("100")}) if err != nil { log.Fatal(err) } newVal, err := mc.Increment("pageviews", 1) if err != nil { log.Fatal(err) } log.Printf("New Value: %d", newVal) }

In this code, we first create a new memcache client connected to the local memcached server. We then set an initial value of "100" for the key "pageviews". Then we use mc.Increment("pageviews", 1) to increment the value of the key "pageviews" by 1. The new value (101) is returned and printed to the console.

Best Practices

  • Use meaningful keys that correspond to the data being stored.
  • Always check for errors when using the Increment function as there could be issues like network errors, the memcached server being down, or the key not existing.
  • Be aware that if the value currently stored for a key isn't a number (or if there's no such key), Memcached won't be able to increment it and will return an error.

Common Mistakes

  • Trying to increment a non-existent key: This will return an error. Ensure the key exists before you try to increment it.
  • Trying to increment a key that is not storing a numeric value: Increment only works with numeric values.


Q: What happens if the incremented value exceeds the maximum 64-bit integer? A: The value wraps around to 0. Memcached uses unsigned 64-bit integers for counters and when they overflow, they reset to 0.

Q: Do I need to convert the numeric value to a string before setting it in Memcached? A: Yes, Memcached only stores data as byte arrays, which is why we convert the number to a string before setting it.

Was this content helpful?

Start building today

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