Caching Application Data

The flexible runtime environment provides a standard memcached service.

Accessing the Memcached Service

The flexible runtime environment adds two environment variables for talking to memcached:


Install a memcached client library

In order to use memcached, use any standard client library that supports the memcached text protocol.

We recommend using gomemcache.

Create a Go app for the flexible environment in the usual way.

Install the bindings.

$ go get

Here is a code example showing it in action:

package main

import (



var memcacheClient *memcache.Client

func main() {
	host := os.Getenv("MEMCACHE_PORT_11211_TCP_ADDR")
	if host == "" {
		host = "localhost"

	port := os.Getenv("MEMCACHE_PORT_11211_TCP_PORT")
	if port == "" {
		port = "11211"

	addr := fmt.Sprintf("%s:%s", host, port)

	memcacheClient = memcache.New(addr)

	http.HandleFunc("/", handle)

func handle(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)

	var count uint64
	var err error

	for {
		count, err = memcacheClient.Increment("count", 1)
		if err == nil {
		if err != memcache.ErrCacheMiss {
			msg := fmt.Sprintf("Could not increment count: %v", err)
			http.Error(w, msg, http.StatusInternalServerError)
		initial := &memcache.Item{
			Key:   "count",
			Value: []byte("0"),
		err := memcacheClient.Add(initial)
		if err != nil && err != memcache.ErrNotStored {
			msg := fmt.Sprintf("Could not populate initial value: %v", err)
			http.Error(w, msg, http.StatusInternalServerError)
		// Increment via the next iteration of the loop.

	fmt.Fprintf(w, "Count: %d", count)

Testing memcached locally

If you are testing your app locally, you need to install a memcached daemon in your OS:


  1. Use the memcached package.

    For Debian and Ubuntu derivatives:

    apt-get install memcached

    For Red Hat, CentOS, and Fedora, use yum:

    yum install memcached

    For Linux Arch:

    pacman -S memcached
  2. Run it as a daemon (or check systemd for an automatic startup):

    memcached -d

Mac OS X

  1. Install Homebrew:

    ruby -e "$(curl -fsSL"
  2. Install memcached:

    brew install memcached
  3. Run it as a daemon:

    memcached -d
  4. Create a database:

    curl --header 'Authorization: Bearer [ACCESS_TOKEN]' \
    --header 'Content-Type: application/json' \


  1. Build your own memcached. Alternatively, you can download freeware binaries.

  2. Run it as a daemon:

    memcached -d

Send feedback about...

App Engine flexible environment for Go