Connecting to Memcached

Once you have a managed Memcached instance running, your containers connect to it directly over the internal project network. There is no public endpoint and no authentication step — access is restricted to containers in the same project. This article shows how to wire up a client library in several languages.

Updated 3 Aug 20263 min read

Once you have a managed Memcached instance running, your containers connect to it directly over the internal project network. There is no public endpoint and no authentication step — access is restricted to containers in the same project. This article shows how to wire up a client library in several languages.

Where the connection details come from

Each Memcached instance runs per region, alongside the containers in the same project and region. The exact host and port for your instance are shown in the Console on the instance's detail page. Memcached listens on port 11211. See the Memcached overview for the connection-address pattern.

The recommended approach is to pass the connection details into your container as an environment variable rather than hard-coding them. You can set a plain environment variable with the host and port, or store it as a secret if you prefer to manage it in the vault. Reading the value at runtime keeps your image portable across projects and regions.

The examples below assume an environment variable named MEMCACHED_SERVERS in the form host:11211. Adjust the name to whatever you configure.

PHP — memcached

<?php
$mc = new Memcached();
[$host, $port] = explode(':', getenv('MEMCACHED_SERVERS') ?: 'localhost:11211');
$mc->addServer($host, (int) $port);
 
$mc->set('greeting', 'hello', 300); // TTL in seconds
$value = $mc->get('greeting');

For a multi-node instance, add each node with addServers() and enable consistent hashing so adding a node only reshuffles a fraction of keys:

$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);

Python — pymemcache

import os
from pymemcache.client.base import Client
 
host, port = os.environ.get("MEMCACHED_SERVERS", "localhost:11211").split(":")
client = Client((host, int(port)))
 
client.set("greeting", "hello", expire=300)  # TTL in seconds
value = client.get("greeting")

For multiple nodes, use pymemcache.client.hash.HashClient with a list of servers so keys are spread with consistent hashing.

Node.js — memjs

const memjs = require('memjs');
 
const client = memjs.Client.create(process.env.MEMCACHED_SERVERS || 'localhost:11211');
 
await client.set('greeting', 'hello', { expires: 300 }); // TTL in seconds
const { value } = await client.get('greeting');

memjs accepts a comma-separated list of servers and hashes keys across them automatically.

Ruby — dalli

require 'dalli'
 
client = Dalli::Client.new(ENV.fetch('MEMCACHED_SERVERS', 'localhost:11211'))
 
client.set('greeting', 'hello', 300) # TTL in seconds
value = client.get('greeting')

Dalli::Client.new takes an array or comma-separated list of servers and uses consistent hashing by default.

Go — gomemcache

import (
    "os"
    "github.com/bradfitz/gomemcache/memcache"
)
 
servers := os.Getenv("MEMCACHED_SERVERS")
if servers == "" {
    servers = "localhost:11211"
}
mc := memcache.New(servers)
 
mc.Set(&memcache.Item{Key: "greeting", Value: []byte("hello"), Expiration: 300}) // TTL in seconds
item, _ := mc.Get("greeting")

memcache.New accepts several server addresses and distributes keys across them.

Multiple nodes

If your instance has more than one node, give the client all of the node addresses and let it hash keys across them. Every client library above supports consistent hashing, which means adding a node redistributes only a fraction of keys rather than emptying the whole cache. See Sizing and eviction for guidance on when to add memory or nodes.

From the blog