Skip to content

Memcached チートシート

高性能な分散メモリオブジェクトキャッシュシステム。

01

はじめに

接続と基本コマンド

Memcached がポート 11211 の単純なテキストプロトコルを使います。set コマンドが、flags(サーバーには不透明な 32 ビット整数)、exptime(秒単位の有効期限。0 = 期限なし)、バイトサイズを取ります。値は生のバイトとして保存されます — サーバーが検査・変更することはありません。memcached-tool がサーバーに同梱され、手軽な統計に便利です。

memcached
# connect to a memcached server
telnet localhost 11211

# or use the memcached-tool (ships with the server)
memcached-tool localhost:11211 stats

# set a key (flags, exptime, bytes)
set mykey 0 3600 5
hello

# get a key
get mykey

# delete a key
delete mykey

プロトコルの概要

Memcached は、ASCII テキストプロトコル(telnet/netcat で使いやすい)とバイナリプロトコル(より効率的で、SASL 認証とアトミック操作に対応)の両方をサポートします。バイナリプロトコルは固定の 24 バイトヘッダーを使い、ほとんどの本番クライアントが好みます。どちらのプロトコルも、同じ基盤のキー・バリューストア上で動きます。

memcached
# Two protocols available:
# 1) ASCII text protocol (human-readable, telnet-friendly)
# 2) Binary protocol (lower overhead, SASL auth, request pipelining)

# text protocol example
set foo 0 0 3
bar
# -> STORED

# binary protocol needs a client (e.g. python binary protocol):
#   0x80 (request) | opcode | keylen | extras | datatype | reserved
#   bodylen | opaque | cas | extras | key | value

# both share the same in-memory data store

# check server version (text)
version
# -> VERSION 1.6.24

キーのルールと制限

キーは 250 バイトまでに制限され、テキストプロトコルではスペースや制御文字を含められません。値のデフォルトの最大サイズは 1MB です(-I フラグで引き上げ。例:-I 4m)。キーはコピーされません — Memcached がインラインで保存するため、長いキーはより多くのメモリを消費します。冗長な説明的な名前より、user:1001 のような短く構造化されたキーを使いましょう。

memcached
# Keys: max 250 bytes, no spaces or newlines (text protocol)
# Controls: max 1MB default value (configurable via -I)

# valid keys
set user:1001 0 0 5
alice
set product:sku-42 0 0 3
xyz

# INVALID keys (text protocol)
# set "with spaces" ...   -> spaces not allowed
# set mykey\n ...         -> newlines not allowed

# large value exceeds 1MB default
set bigkey 0 0 1048577
# -> SERVER_ERROR object too large for cache

# increase max item size at startup (-I in MB)
# memcached -m 256 -I 4m

よくあるユースケース

Memcached が最も適するのは、一時的で派生的なデータのキャッシュです:データベースのクエリ結果、セッション、描画されたページの断片、レート制限のカウンタ、高コストな計算。意図的にシンプルです — 永続化なし、レプリケーションなし、複雑なデータ型なし。揮発性の LRU キャッシュとして扱いましょう。システム オブ レコードから再構築できないデータは決して保存しないこと。

memcached
# 1) Database query cache
set user:1001:profile 0 600 48
{"id":1001,"name":"Alice","email":"[email protected]"}

# 2) Session storage (with TTL)
set sess:abc123 0 1800 64
{"userId":1001,"loginAt":1700000000,"role":"admin"}

# 3) Rendered HTML fragment cache
set page:home:en 0 300 128
<html><body>Hello</body></html>

# 4) Rate-limit counters
incr ratelimit:ip:1.2.3.4 1

# 5) Computed result cache (expensive aggregation)
set report:daily:20240101 0 3600 256
{"visits":1234,"signups":56}

アーキテクチャの概要

Memcached は、独立し調整されないサーバーから成る分散キャッシュです。サーバー自体にはクラスタリング、レプリケーション、フェイルオーバーがなく — すべての分散ロジックがクライアント側にあります(一貫ハッシュ)。各ノードがキースペースの重ならないスライスを所有し、ノードが死ぬとデータが失われ、クライアントが再ルートします。耐久性を犠牲に、サーバーを極めてシンプルかつ高速に保つ設計です。

memcached
# Memcached is a pool of independent servers (no clustering built-in)
#
#  +---------+   +---------+   +---------+
#  | mc:11211|   | mc:11211|   | mc:11211|
#  +---------+   +---------+   +---------+
#        ^            ^             ^
#        |            |             |
#   +----+------------+-------------+----+
#   |   CLIENT (consistent hashing)     |
#   +------------------------------------+
#
# - Each server owns a disjoint slice of the keyspace
# - Sharding is done by the CLIENT (consistent hashing)
# - Servers do NOT talk to each other (no replication, no failover)
# - A server down = its keys are lost; clients reroute to the ring

# horizontal scale = add more servers to the ring
# vertical scale = bigger -m memory per server
02

基本コマンド(set / get / delete)

set — 値の保存

set が無条件に値を保存し、既存のキーを上書きします。flags はサーバーが保存するが決して解釈しない 32 ビット整数で — クライアントがシリアライズ形式をエンコードするのに使います(例:1 = JSON、2 = 圧縮)。exptime 0 が期限なしを意味し、30 日を超える Unix タイムスタンプは絶対時刻として扱われます。発火後放置の書き込みでレスポンスをスキップするのが noreply です(速いが、エラー報告はありません)。

memcached
# syntax: set <key> <flags> <exptime> <bytes> [noreply]\r\n<data>\r\n
# response: STORED | NOT_STORED

set greeting 0 0 5
hello
# -> STORED

# with flags (app-defined 32-bit int, e.g. mark as JSON=1)
set config 1 0 14
{"a":1,"b":2}
# -> STORED

# with expiration (3600 seconds) and noreply
set token 0 3600 8 noreply
s3cr3t00
# -> (no response)

# overwrite an existing key
set greeting 0 0 7
goodbye
# -> STORED

get — 値の取得

get が、1 回のラウンドトリップで 1 つ以上のキーを取得します — バッチ(multi-get)がパフォーマンスに決定的に重要です。返される各 VALUE の行が flags を繰り返し、クライアントがデシリアライズ方法を知れるようにします。欠けているキーは静かに省かれます(エラーなし)。レスポンスは END で終端します。大きな multi-get は、単一のサーバースレッドを塞がないようチャンク化しましょう。

memcached
# single key
get greeting
# VALUE greeting 0 7
# goodbye
# END

# multiple keys in one request (batched)
get user:1 user:2 user:3
# VALUE user:1 0 5
# alice
# VALUE user:3 0 3
# bob
# END   (user:2 missing -> simply omitted)

# response format: VALUE <key> <flags> <bytes>\r\n<data>\r\n ... END
# flags lets the client decode (e.g. decompress / parse JSON)

# non-existent key
get nope
# END   (no VALUE line at all)

gets — CAS トークン付きの取得

gets(get-extended)が get と同一ですが、各 VALUE の行に cas_unique トークンを追記します。この 64 ビット整数が書き込みのたびに変わり、Memcached の楽観的並行性(CAS)の基礎です。複数のクライアントが同じキーを修正するときの、失われた更新を避けるには、gets + cas を一緒に使いましょう。トークンは不透明です — キーをまたぐ値や単調性を仮定してはいけません。

memcached
# gets returns a CAS unique identifier for optimistic concurrency
gets greeting
# VALUE greeting 0 7 12
# goodbye
# END
#                          ^ cas_unique = 12

# the cas_unique changes every time the key is written
set greeting 0 0 5
hello
gets greeting
# VALUE greeting 0 5 13
# hello
# END   (cas_unique is now 13)

# use cas_unique with the cas command for safe updates
cas greeting 0 0 5 13
world
# -> STORED

delete — キーの削除

delete が単一のキーを削除し、DELETED か NOT_FOUND を返します。ワイルドカードやパターンの削除はなく — Memcached にはキーを列挙するコマンドが全くないため、一括削除はアプリケーションが追跡する必要があります(キーのセットを別の場所で維持するか、名前空間化された flush パターンを使う)。レスポンスのスキップには noreply を加えましょう。削除されたメモリは自分の slab へ返され再利用されます。

memcached
# delete a single key
delete greeting
# -> DELETED

# delete a non-existent key
delete nope
# -> NOT_FOUND

# with noreply (fire-and-forget)
delete stalekey 0 noreply
# -> (no response)

# delete does NOT support patterns or wildcards
# delete user:*   <- INVALID, only deletes a key literally named "user:*"

# to bulk-delete, list keys yourself then delete each
# (memcached has no KEYS/SCAN command — track keys in your app)

touch と gat — 有効期限の更新

touch(1.4.8+)が、値を転送せずにキーの有効期限を更新します — セッションの更新には get+set より安価です。gat が、値を取得し 1 回のラウンドトリップで TTL をアトミックに更新するため、寿命が延びるべきセッションの読み取りに理想的です。CAS トークンも返すのが gats です。操作の間に値が変わる競合を避けるため、get+set の代わりにこれらを使いましょう。

memcached
# touch: change a key's expiration without fetching the value
touch session 3600
# -> TOUCHED

touch session 0       # make it never expire
# -> TOUCHED

# gat: get-and-touch — fetch value AND update expiration in one op
gat 3600 session
# VALUE session 0 64
# {...}
# END

# gats: get-and-touch with CAS token
gats 3600 session
# VALUE session 0 64 42
# {...}
# END

# touch a missing key
touch nope 60
# -> NOT_FOUND
03

ストレージコマンド(add / replace / append / prepend)

add — 存在しない場合だけ保存

add が、キーがまだ存在しない場合にだけ値を保存し、そうでなければ NOT_STORED を返します。競合なしに、キー(カウンタ、ロック)を遅延初期化する正統な方法です。incr/decr と組み合わせれば、安全なカウンタのパターンが形成されます:0 で作る add、その後 incr。Redis の SETNX と違い、add には TTL のショートカットがなく — コマンドで exptime を設定しましょう。

memcached
# add fails if the key already exists
add newkey 0 0 5
hello
# -> STORED

add newkey 0 0 5
world
# -> NOT_STORED   (key already exists)

# common pattern: initialize a counter only once
add counter:daily 0 0 1
0
# -> STORED on first run, NOT_STORED after

# then use incr to bump it
incr counter:daily 1
# -> 1

replace — 存在する場合だけ保存

replace が、キーが既に存在する場合にだけ値を保存します — add の鏡像です。古い更新の経路から、うっかりキャッシュエントリを作るのを防ぎます。キーがなければ NOT_STORED を返します。書き込みが既存のキャッシュを更新すべきだが、新しいエントリを決して作ってはならないとき(追い出されたキーを蘇らせるべきでないバックグラウンドの更新など)に使いましょう。

memcached
# replace fails if the key does NOT exist
replace missing 0 0 5
hello
# -> NOT_STORED  (key doesn't exist)

set existing 0 0 3
foo
# -> STORED

replace existing 0 0 3
bar
# -> STORED   (key existed, value updated)

# useful for updating cached data only if it was already cached
# (don't accidentally create a cache entry from a stale write)
replace cached:user:1 0 600 64
{"name":"Alice"}

append — 既存の値への追記

append が、既存の値の末尾へデータを連結します。キーがなければ NOT_STORED を返します。flags と exptime の引数は受け付けられますが無視され — 値が元のメタデータを保ちます。read-modify-write なしで、その場でログ行やバッファを構築するのに最適です。注意:結果の値は依然 1MB のアイテム上限内に収まらなければなりません。

memcached
# append adds data to the END of an existing value
set logline 0 0 5
hello
# -> STORED

append logline 0 0 6
 world
# -> STORED

get logline
# VALUE logline 0 11
# hello world
# END

# append to a non-existent key
append nolog 0 0 3
abc
# -> NOT_STORED  (key must exist)

# flags and exptime are IGNORED on append/prepend (value keeps old metadata)

prepend — 既存の値への前置

append の鏡像が prepend です — 既存の値の「先頭」へデータを連結します。append と同様、キーが存在する必要があり、flags/exptime を無視します。バッファされた値へのヘッダー/接頭辞の積み重ねに有用です。append と prepend は、結果を返さないという意味でクライアント間のアトミックな read-modify-write ではありません — しかしサーバー側ではアトミックな操作です。

memcached
# prepend adds data to the START of an existing value
set greeting 0 0 5
world
# -> STORED

prepend greeting 0 0 6
hello 
# -> STORED

get greeting
# VALUE greeting 0 11
# hello world
# END

# prepend to non-existent key
prepend nope 0 0 3
abc
# -> NOT_STORED

# flags/exptime ignored — only the value bytes change

ストレージコマンドの比較

Memcached の 6 つのストレージコマンド(set、add、replace、append、prepend、cas)が違うのは、保存のための前提条件だけです。set が無条件で、add/replace が存在によるゲート、append/prepend がその場での修正とメタデータの無視、cas が gets からの CAS トークンによるゲートです。正しいものを選べば、read-modify-write の競合が単一のアトミックなサーバー操作へ変わります。

memcached
# When does each command succeed?
#
#  set     -> ALWAYS (create or overwrite)
#  add     -> only if key does NOT exist
#  replace -> only if key ALREADY exists
#  append  -> only if key exists (adds to end, ignores flags/exptime)
#  prepend -> only if key exists (adds to start, ignores flags/exptime)
#
# All return STORED / NOT_STORED / EXISTS / NOT_FOUND as appropriate.

# set:        overwrite unconditionally
# add:        lazy init (counters, locks)
# replace:    refresh only if already cached
# append:     grow a buffer / log
# prepend:    stack headers

# all accept [noreply] to skip the response
04

CAS(Compare-And-Swap)

gets — CAS トークンの取得

gets(get-extended)が CAS の読み取り側です。サーバーがそのキーの修正のたびに変わると保証する、cas_unique の 64 ビットトークンと共に、値を返します。このトークンを取り込み cas へ渡しましょう。トークンが依然一致すれば、書き込みが成功します。gets なしでは安全な CAS はできません — 素の get はトークンを省きます。

memcached
# gets is get + a 64-bit cas_unique token
gets counter
# VALUE counter 0 1 7
# 5
# END
#                ^ cas_unique = 7

# the token is opaque and changes on EVERY write to the key
set counter 0 0 1
5
gets counter
# VALUE counter 0 1 8      <- token changed to 8

# fetch multiple keys with tokens in one call
gets a b c
# VALUE a 0 3 11
# ...
# VALUE c 0 3 19
# ...

cas — 条件付き書き込み

cas_unique トークンが gets が返したものと依然一致する場合にだけ、値を書き込むのが cas です。STORED が書き込みの適用を、EXISTS が先に別のクライアントがキーを修正したこと(トークン不一致)を、NOT_FOUND がキーの削除を意味します。これが楽観的ロックです — EXISTS では、gets→修正→cas のループ全体を再試行しましょう。サーバー側のロックなしで失われた更新を避けます。

memcached
# syntax: cas <key> <flags> <exptime> <bytes> <cas_unique> [noreply]
gets counter
# VALUE counter 0 1 8       <- token is 8
# 5

cas counter 0 0 1 8
6
# -> STORED   (token matched, write applied)

# a concurrent write changed the token in the meantime
cas counter 0 0 1 8        # stale token 8, but key is now on token 9
6
# -> EXISTS  (token mismatch, someone else wrote first)

CAS のユースケース:安全なカウンタ

read-modify-write のセマンティクスが必要なとき(キャッシュエントリ内の JSON の塊の更新など)、CAS が失われた更新の問題を解決します。EXISTS のときは、gets で再読み込みし、変換を再適用し、cas を再試行する必要があります — 通常、ライブロックを避けるため、上限のあるリトライ回数付きでです。純粋な整数のカウンタには、incr/decr がより単純でアトミックです。CAS に手を伸ばすのは、値が構造化されているときだけにしましょう。

memcached
# read-modify-write with get+set is RACY:
#   get counter -> 5      (client A)
#   get counter -> 5      (client B)
#   set counter 6         (A writes 6)
#   set counter 6         (B writes 6, LOST A's increment!)

# safe pattern with gets/cas:
gets counter               # token = 8, value = 5
newval = 5 + 1
cas counter 0 0 1 8        # 8 -> STORED, value = 6

# on EXISTS, retry the whole loop:
gets counter               # token = 9, value = 6
cas counter 0 0 1 9        # -> STORED, value = 7

# for plain counters prefer incr/decr (atomic, no CAS needed)

CAS の失敗とリトライ

堅牢な CAS のループが処理すべき 3 つの結果:キーの欠落(add を使い、NOT_STORED ならリトライへフォールバック)、トークンの一致(STORED、完了)、トークンの不一致(EXISTS、リトライ)です。競合下でのライブロックを避けるため、リトライに上限を設けましょう。キーが本当に欠けているなら、作成を競う 2 つのクライアントが互いを上書きしないよう、set より add を推奨しましょう。

memcached
# pseudocode for a CAS retry loop
max_retries = 5
for i in range(max_retries):
    res = client.gets(key)          # value + cas token
    if res is None:
        # key missing -> use add to create it race-free
        if client.add(key, new_value, ttl):
            break
        else:
            continue                # someone else created it; retry
    old_val, cas_token = res
    new_val = transform(old_val)    # your read-modify logic
    if client.cas(key, new_value, ttl, cas_token):
        break                       # STORED
    # else EXISTS -> loop and retry
else:
    raise Exception("CAS failed after retries")

CAS の制限

CAS は単一キー専用です — Memcached には Redis の MULTI/EXEC のようなマルチキーのトランザクションがありません。悲観的ではなく楽観的です:重い競合の下では多くの書き込みが EXISTS に当たりリトライするため、ホットなキーはシャードしましょう。cas_unique はキーごとで不透明です。キーをまたいで比較したり順序を仮定してはいけません。キーが追い出され再作成されるとトークンがリセットされるため、NOT_FOUND は失敗ではなく新しい始まりとして扱いましょう。

memcached
# 1) CAS only protects a SINGLE key — no multi-key transactions
#    (memcached has no MULTI/EXEC like Redis)
#
# 2) CAS tokens are per-key and opaque — never compare across keys
#
# 3) CAS does NOT lock the key; it's optimistic — high contention
#    means many retries (consider sharding the hot key)
#
# 4) The binary protocol exposes cas more cleanly; some ASCII quirks
#    exist in older servers
#
# 5) cas_unique may RESET if a key is evicted and re-created —
#    treat absence (NOT_FOUND) as a fresh start, not a token failure

# for multi-key atomicity, use app-level locks (e.g. add-based lock)
05

カウンタ(incr / decr)

incr — アトミックな増加

incr が、値が 10 進文字列のキーへ正の整数をアトミックに加え、新しい値を返します。操作は同時クライアントをまたいで完全にアトミックです — 失われた更新はありません。値は 64 ビット符号なしの数値 ASCII でなければなりません(符号も小数もなし)。欠けているキーへの incr は NOT_FOUND を返し、非数値データではエラーになります。自動作成はなく — 先に add を使いましょう。

memcached
# syntax: incr <key> <value> [noreply]
# the key's value MUST be a numeric string (ASCII digits)
set views 0 0 1
5
# -> STORED

incr views 1
# -> 6

incr views 10
# -> 16

# returns the NEW value as a decimal string

# incrementing a non-numeric value
set name 0 0 5
alice
incr name 1
# -> CLIENT_ERROR cannot increment or decrement non-numeric value

# incr on a missing key
incr missing 1
# -> NOT_FOUND

decr — アトミックな減少

decr が数値からアトミックに引き算し、結果を返します。0 でフロア制限されます — 負の数は決して作らず、在庫のカウンタには便利ですが、decr で純負の残高を追跡することはできないことを意味します。incr と同様、値が ASCII の数字であり、キーが存在する必要があります(さもなければ NOT_FOUND)。

memcached
# syntax: decr <key> <value> [noreply]
set views 0 0 2
16
# -> STORED

decr views 1
# -> 15

decr views 10
# -> 5

# decr NEVER goes negative — stops at 0
decr views 100
# -> 0

# decr a missing key
decr missing 1
# -> NOT_FOUND

# decr a non-numeric value -> CLIENT_ERROR

カウンタの初期化

incr/decr が欠けているキーに対し NOT_FOUND を返すため、カウンタは add で初期化する必要があります(競合フリー:最初の呼び出し元が 0 で作り、他は NOT_STORED を得て incr へ直行します)。incr もするカウンタの初期化に set を使ってはいけません — set が無条件に上書きし、同時の増加と競合します。日付でカウンタに名前空間を付け TTL を設定すれば、自動的に期限切れになります。

memcached
# incr/decr do NOT create keys — initialize with add first

# race-free counter init: add creates at "0" only if absent
add counter:daily 0 86400 1
0
# -> STORED (first caller wins) or NOT_STORED (already exists)

# now safe to increment from any client
incr counter:daily 1
# -> 1

# alternative: set then incr (but set+incr is racy for resets)
# For a daily counter, key by date so it auto-expires:
#   counter:2024-01-01
#   counter:2024-01-02

カウンタのユースケース

カウンタが輝くのは、レート制限(60 秒 TTL の、IP+分のキー)、閲覧/ダウンロードの統計、デイリーのアクティブ数、在庫、ロールアウトの指標です。アトミックで安価なため、非常に高い書き込みレートへスケールします。レート制限には、ウィンドウに合うキーの粒度(ユーザーごと、IP ごと)と TTL を選び — decr が 0 で床に留まるため、在庫は負にならないことを覚えましょう。

memcached
# rate limiting (per IP per minute)
add ratelimit:1.2.3.4:2024010112 0 60 1
0
incr ratelimit:1.2.3.4:2024010112 1
# if result > 100 -> reject request

# view/download counters
incr article:42:views 1

# daily active users (with a SET of user ids tracked elsewhere)
incr dau:20240101 1

# inventory / stock (decrement on purchase)
decr product:42:stock 1
# if result == 0 -> out of stock

# feature-flag rollout counters
incr flag:newui:shown 1

カウンタの制限

カウンタは符号なし 64 ビット整数だけです — float、負、符号はありません。incr/decr はキーを自動作成しません。decr は 0 で制限されます。値がただの文字列であるため、迷子の set/replace が上書きし、同時の増加を破壊します — add で初期化し、それ以外は incr/decr だけを使いましょう。float や複数フィールドのカウンタには、代わりに構造化された値への CAS を使いましょう。

memcached
# 1) values must be unsigned 64-bit integers (no decimals, no signs)
#    incr/decr on "3.14" or "-5" -> CLIENT_ERROR
#
# 2) no auto-create — must add/set first; incr on missing = NOT_FOUND
#
# 3) decr floors at 0 — cannot represent negative balances
#
# 4) the counter is just a string; set/add/replace/cas OVERWRITE it,
#    which can clobber concurrent incr/decr (use add only to init)
#
# 5) for float counters or complex updates, use CAS on a JSON blob

# to RESET a counter, use set (not decr-to-zero) — but watch for races
06

有効期限と TTL

有効期限付きの set

exptime は秒単位です:0 が期限なしを意味し、2592000(30 日)までの値が相対 TTL、より大きい値は絶対 Unix タイムスタンプとして解釈されます。期限切れのアイテムは、その秒で積極的に回収されるわけではありません — Memcached は遅延有効期限(アクセス時に確認)と、背景の LRU クローラを使うため、触れられるか追い出されるまで、古いキーが残り得ます。

memcached
# exptime is the 4th arg to all storage commands (seconds)
# 0 = no expiration (live until evicted)

set session 0 0 5           # never expire
alice

set session 0 1800 5        # expire in 1800 seconds (30 min)
alice

# exptime > 30 days (2592000 s) is treated as a UNIX timestamp
set archive 0 1735689600 5  # expires at 2025-01-01 00:00 UTC
alice

# common TTLs
#   60      -> 1 minute  (rate limit windows)
#   3600    -> 1 hour    (short cache)
#   86400   -> 1 day     (daily cache)
#   0       -> forever   (until LRU evicts)

touch — TTL の更新

touch(1.4.8+)が、値を転送せずにキーの TTL をその場で更新します — スライディングウィンドウのセッションには get+set よりはるかに安価です。ソフトデリートには exptime を 1 に設定しましょう(即座に期限切れになります)。30 日の相対対絶対のルールは同じく適用されます。欠けているキーに対し touch は NOT_FOUND を返すため、呼び出し元はそれを「キャッシュされていない」と扱うべきです。

memcached
# touch: change a key's TTL without fetching the value
# syntax: touch <key> <exptime> [noreply]

set session 0 3600 5
alice

# extend the session by another hour
touch session 3600
# -> TOUCHED

# make it never expire
touch session 0
# -> TOUCHED

# expire it immediately (poor man's delete via TTL)
touch session 1
# -> TOUCHED   (effectively deleted on next access)

touch missing 60
# -> NOT_FOUND

gat と gats — Get and Touch

gat(1.6+)が、get と touch を 1 回のラウンドトリップでアトミックに組み合わせます — 有効期限を前に滑らせるべきセッションの読み取りに最適です。CAS トークンも返すのが gats です。別々の get+touch は、TTL が更新されない窓を作り、ラウンドトリップを 2 倍にします。gat が両方を修正します。マルチキーのスライディング読み取りには、gat が複数のキーを受け付けます。

memcached
# gat: fetch value AND update TTL in one round-trip
# syntax: gat <exptime> <key>

gat 3600 session
# VALUE session 0 5
# alice
# END

# gats: get-and-touch with CAS token
gats 3600 session
# VALUE session 0 5 42
# alice
# END

# ideal for session reads that should refresh the TTL:
#   - one network round-trip instead of get + touch
#   - atomic: no window where TTL isn't refreshed

# multiple keys: gat <exptime> <key1> <key2> ...
gat 3600 a b c

有効期限の挙動

Memcached の有効期限はデフォルトで遅延です — キーが回収されるのはアクセスされたときだけです。つまり、追い出されるまで、古いデータがメモリを占め得ます。背景の掃除を加えるのが、LRU クローラ(1.4.24+)で、期限切れのアイテムを slab ごとに積極的に解放し、メモリの浪費を防ぎます。本番では有効化しましょう:lru_crawler enable。それでも、正しさのために正確な有効期限のタイミングに頼ってはいけません。

memcached
# Memcached does NOT actively scan for expired keys every second.
# Expiration is LAZY: a key is checked when accessed (get/gets/touch).
#
# A background "LRU crawler" (1.4.24+) periodically sweeps slabs to
# free expired items so memory is reclaimed even if never accessed.
#
#   stats lru_crawler           # is the crawler enabled?
#   lru_crawler enable          # turn it on
#   lru_crawler sleep 100       # microseconds between slab visits
#   lru_crawler tocrawl 1000    # max items to inspect per slab per pass

# an expired-but-not-yet-reaped key:
get expiredkey
# -> END   (treated as missing, memory freed for its slab)

TTL のベストプラクティス

TTL は必ず設定しましょう — 上限のないキャッシュエントリが、上限のないメモリ成長と古いデータのバグを引き起こします。相関した有効期限がオリジンに殺到しないよう、TTL にランダムなジッター(±5〜10%)を加えましょう。揮発性のデータは日付で名前空間化し、古いエントリが自動的に期限切れになるようにします。ミスのときは、同じコードパスで再計算し保存し、キャッシュを温かく保ちましょう。明示的な無効化には、TTL=1 ではなく delete を使います。

memcached
# 1) ALWAYS set a TTL on cache entries — never store forever (0)
#    unless you have an explicit invalidation path.
#
# 2) add jitter to avoid thundering herds:
ttl = base_ttl + random(0, 300)   # +/- 5 minutes
#
# 3) namespace by time so old keys auto-expire:
set report:2024-01-01 0 86400 N   # yesterday's report, 1-day TTL
#
# 4) use longer TTLs for stable data, shorter for volatile data
#
# 5) on a cache miss, recompute AND set with TTL in ONE path
#
# 6) don't use exptime=1 as a "delete" in production — use delete
07

Stats コマンド

stats — 概観

stats がコアのサーバー指標を出力します:cmd_get/cmd_set(合計の操作)、get_hits/get_misses(ヒット率 = hits/cmd_get)、evictions(メモリ圧迫によるアイテムの破棄)、curr_items、limit_maxbytes に対する bytes、接続数です。最初に見るべき 2 つの数字が、ヒット率と evictions です。これが、どんな Memcached のモニタリングの基礎です。

memcached
# general server statistics
stats
# STAT pid 1234
# STAT uptime 3600
# STAT curr_connections 10
# STAT total_connections 1024
# STAT cmd_get 50000
# STAT cmd_set 12000
# STAT get_hits 45000
# STAT get_misses 5000
# STAT evictions 12
# STAT bytes 8388608
# STAT limit_maxbytes 67108864
# STAT curr_items 4321
# ...
# END

# hit rate = get_hits / cmd_get  (here 90%)
# watch evictions — rising = memory pressure

stats items — slab ごとのアイテム数

stats items が、slab クラスごとに、保持するアイテム数(number)と、最も古く保存されたアイテムの年齢(age)を報告します。数が多く年齢が低い slab は撹拌されており、年齢が高い slab は長寿のデータを保持しています。チャンクサイズの調整や、特定のサイズ範囲が追い出される理由の診断のとき、最初に見るべき場所です。

memcached
# item counts and age per slab class
stats items
# STAT items:1:number 100
# STAT items:1:age 1200
# STAT items:2:number 250
# STAT items:2:age 3600
# STAT items:5:number 3
# STAT items:5:age 60
# ...
# END

# items:<slabid>:number  -> how many items live in that slab class
# items:<slabid>:age     -> age of the LRU item (seconds since stored)
# use this to see which size classes are full / hot

stats slabs — slab アロケータの状態

stats slabs が slab アロケータの構成を明らかにします:各クラスが chunk_size(アイテムのスロットはここへ切り上げられる)、chunks_per_page、total_pages、used/free のチャンクを持ちます。slab クラスに割り当てられたメモリはそこに留まります — 他のクラスへ返せません。あるクラスが満杯で追い出すのに、別のクラスが空いているなら、slab の石灰化があり、-f(成長係数)の調整で対処できます。

memcached
# memory layout of each slab class
stats slabs
# STAT 1:chunk_size 96
# STAT 1:chunks_per_page 10922
# STAT 1:total_pages 1
# STAT 1:total_chunks 10922
# STAT 1:used_chunks 100
# STAT 1:free_chunks 10822
# STAT 2:chunk_size 120
# ...
# STAT active_slabs 5
# STAT total_malloced 16777216
# END

# chunk_size    -> bytes per item slot in this class
# total_chunks  -> total slots
# used_chunks   -> slots holding data
# free_chunks   -> empty slots

stats sizes — アイテムサイズのヒストグラム

stats sizes が、(キー + 値 + オーバーヘッドの)本物のアイテムサイズのヒストグラムを構築するため、チャンクサイズの切り上げにどれほどメモリが無駄にされているか分かります。フルスキャンを行い、歴史的にサーバーをロックしてきました — モダンなバージョンはセーフモードのチェックの背後に門を置き、強制するには --disable-safe-mode を渡します。低トラフィックの間だけ実行しましょう。出力が、正しい -f 成長係数の選択を助けます。

memcached
# histogram of actual item sizes (key + value + overhead)
# WARNING: this command locks the cache while scanning — do NOT run
# in production at peak. Use stats sizes --disable-safe-mode only
# if you accept the risk.

stats sizes
# STAT 96 100       # 100 items rounded up to 96 bytes
# STAT 120 250
# STAT 192 50
# ...
# END

# compare to stats slabs to see how much memory is wasted to
# chunk-size rounding (internal fragmentation)

stats cachedump — slab の検査

stats cachedump が、与えられた slab クラスが保持するキーを列挙します(N エントリに制限)— アドホックなデバッグに有用です。slab の LRU をたどり、遅い、または一部のビルドで完全に無効化されています — 本番のキー列挙には決して使わないこと。Memcached が意図的に、すべてのキーを列挙する効率的な方法を提供しないため、アプリケーションがキー付けするブラックボックスとして扱いましょう。

memcached
# peek at keys in a specific slab class
# syntax: stats cachedump <slab_id> <limit> [noreply]
stats cachedump 1 10
# ITEM user:1 [5 b; 1700000000 s]
# ITEM user:2 [5 b; 1700000000 s]
# ...
# END

# WARNING: for debugging only — it walks the LRU and can be slow.
# Not all builds ship cachedump; it is disabled in some distros.
# Each ITEM shows: key, [value size in bytes; storage time s]

# do NOT use this for key enumeration in production code —
# memcached has no efficient SCAN command

stats reset と他のサブコマンド

stats reset が、データを落とさずに、累積のカウンタ(ops、hits、misses)をゼロにします — デプロイ後の新しい区間の測定に便利です。他の有用なサブコマンド:stats settings(実効的な設定)、stats conns(新しいビルドでの接続ごとの詳細)、stats lru_crawler(クローラの状態)。カウンタは、そうでなければプロセス開始以来の累積であるため、ベンチマークの前に reset しましょう。

memcached
# zero the cumulative counters (cmd_get, hits, misses, etc.)
stats reset
# -> RESET

# useful stats subcommands:
stats settings      # current effective configuration
stats items         # per-slab item counts/age
stats slabs         # slab allocator layout
stats sizes         # item size histogram (slow!)
stats conns         # per-connection info (newer builds)
stats lru_crawler   # crawler state

# reset counters after a deploy to measure only current run
# (counters are since process start otherwise)
08

設定

stats settings — 実効的な設定

stats settings が実行中の設定を示します:maxbytes(-m)、maxconns(-c)、growth_factor(-f)、item_size_max(-I)、evictions と CAS が有効か、LRU クローラの状態です。これらのほとんどは起動時に固定され、実行時に変えられるのは少数です。サーバーが思うフラグを拾ったかどうかの確認に、最初に見るべき場所です。

memcached
# view the server's current effective settings
stats settings
# STAT maxbytes 67108864
# STAT maxconns 1024
# STAT tcpport 11211
# STAT udpport 0
# STAT inter NULL
# STAT evictions on
# STAT cas_enabled on
# STAT chunk_size 48
# STAT growth_factor 1.25
# STAT item_size_max 1048576
# STAT lru_crawler on
# ...
# END

# this reflects flags passed at startup (-m, -c, -f, -I, ...)

起動フラグ

設定のほとんどは起動フラグ経由で行われます。決定的なもの:-m(メモリ)、-l(常に 127.0.0.1 かプライベートネットワークへ bind — Memcached を公開してはいけません)、-c(接続の上限)、-I(最大アイテムサイズ)、-f(slab 成長係数)です。-M が追い出しの挙動を、LRU 追い出しの代わりに満杯時のエラーへ切り替えます(キャッシュではめったに望まれません)。スループットのため -t を CPU 数に調整しましょう。

memcached
# common memcached startup flags
memcached -d -m 256 -p 11211 -u memcache -c 2048 -f 1.25 -I 1m

#  -d              run as a daemon
#  -m <MB>         max memory to use for items (default 64)
#  -M              return error instead of evicting when memory full
#  -c <conn>       max simultaneous connections (default 1024)
#  -p <port>       TCP port (default 11211)
#  -U <port>       UDP port (0 disables; default 11211)
#  -l <addr>       listen address (default all — bind to 127.0.0.1!)
#  -u <user>       run as this user (when started as root)
#  -f <factor>     slab growth factor (default 1.25)
#  -n <bytes>      min item allocation (default 48)
#  -I <size>       max item size (default 1m, can be 1m-1g)
#  -t <threads>    worker threads (default 4)
#  -v / -vv / -vvv verbosity

実行時の設定

Memcached が公開する実行時のノブは少数です:cache_memlimit(メモリ上限のライブ変更)、lru_crawler ファミリー(背景の回収器の有効化/無効化/調整)、verbosity(ログレベル)、flush_all(全アイテムの無効化、省略可能な遅延付き)です。設定のほとんどは起動時に固定のままです — -m、-c、-I を変えるにはプロセスを再起動します。flush_all は設定ではなく制御面の操作です。

memcached
# a small number of settings can change at runtime:

# change the memory limit (bytes) live
cache_memlimit 536870912      # 512 MB
# -> OK

# LRU crawler controls
lru_crawler enable            # turn the crawler on
lru_crawler disable           # turn it off
lru_crawler sleep 100         # us between slab visits
lru_crawler tocrawl 1000      # max items per slab per pass
lru_crawler metadump all      # dump key metadata (not values)

# log verbosity at runtime
verbosity 2

# flush_all (invalidate everything, not a config change)
flush_all
flush_all 900                 # invalidate in 900 seconds

重要な設定の解説

-m が看板の設定です:ワーキングセットと余裕に合わせましょう — 小さすぎると追い出しとキャッシュの撹拌が起きます。-f が slab クラスの粒度と内部断片化をトレードします — 同じようなサイズのアイテムが多いなら、低くしましょう(1.1 に向ける)。-I がアイテムサイズに上限を設けます。大きな blob をキャッシュしなければならない場合にだけ引き上げましょう。キャッシュで -M が使われることはめったになく — 追い出しの代わりに OOM をエラーへ変えます。

memcached
# -m  memory budget
#    the single most important knob. Size to fit your working set
#    with headroom; undersizing = evictions = cache churn.
#
# -f  slab growth factor (default 1.25)
#    smaller (1.1) = more slab classes, less internal fragmentation
#    but more per-class memory stuck. Larger (1.5) = fewer classes,
#    more waste per chunk.
#
# -I  max item size (default 1m)
#    raise to cache bigger blobs (e.g. -I 4m) at the cost of larger
#    worst-case allocations.
#
# -M  disable LRU eviction (error instead) — only for strict caches
#
# -t  worker threads (default 4) — scale to CPU count for throughput

接続の制限とスレッド

-c が同時接続に上限を設けます — (pool_size × app_instances) より快適に上に設定しましょう。さもないとクライアントが拒否されます(stats の listen_disabled_num を見る)。worker スレッドの設定が -t で、Memcached はスレッドごとにイベント駆動なので、-t を CPU コアへスケールさせましょう。通常 4〜8 です。それを超えると、ロックの競合が利得を制限します。各スレッドがハッシュテーブルのスライスを所有するため、スレッドが増えても単一のホットキーは助かりません。

memcached
# -c  max client connections (default 1024)
memcached -c 4096

# each connection costs a bit of memory; set -c above your expected
# peak concurrent clients (pool size * app instances + headroom)

# -t  worker threads (default 4)
memcached -t 8
# memcached is event-driven per thread; each thread runs its own
# event loop and owns a slice of the hash table. Scale -t to CPU
# cores. Beyond ~8 threads, contention often limits gains.

# check connection pressure:
stats
# STAT curr_connections 412
# STAT total_connections 10230
# STAT listen_disabled_num 0   # >0 means you hit -c and refused conns
09

キャッシュの戦略

Cache-Aside(遅延ローディング)

Cache-aside が最も単純で最も人気のあるパターンです:アプリがまずキャッシュを読み、ミスのとき DB からロードしキャッシュを裏で埋めます。耐障害性があります(キャッシュの停止は、より多くの DB 負荷を意味するだけ)が、コールドキーでの殺到と、明示的な無効化までの古さを許します。書き込み時の無効化があっても、無効化の見逃しのための安全網として、必ず TTL を設定しましょう。

memcached
# the most common pattern — app manages the cache explicitly

def get_user(id):
    key = "user:" + str(id)
    val = mc.get(key)              # 1) try cache
    if val is not None:
        return val                 #    hit
    val = db.query(id)             # 2) miss -> load from DB
    mc.set(key, val, ttl=3600)     # 3) back-fill the cache
    return val

# on write:
def update_user(id, data):
    db.update(id, data)
    mc.delete("user:" + str(id))   # invalidate (or set fresh value)

# pros: simple, resilient to cache failure
# cons: stampede on miss; stale until invalidated

Read-Through

Read-through では、キャッシュ層自体がミスのときローダーを呼び出します — アプリは get を呼び値を受け取るだけです。これで、キャッシュ充填のロジックが一元化され、呼び出し元をまたぐ一貫性が保証されます。代償は、キャッシュ呼び出しの中の同期 DB 読み取りです。ほとんどの Memcached クライアントは read-through を組み込みで ship しないため、通常、cache-aside の周りの薄いラッパーとして実装されます。

memcached
# the cache itself is responsible for loading from the DB
# (the client library or a cache layer provides a loader callback)

mc = memcached_with_loader(load_fn=db.query_user)

def get_user(id):
    # the cache calls load_fn(id) automatically on a miss
    return mc.get_or_load("user:" + str(id))

# pros:
#   - app code is simpler (no miss-handling logic)
#   - cache population is consistent across callers
# cons:
#   - the cache library must support a loader (or you wrap it)
#   - a cache miss is slower (synchronous DB read inside get)

Write-Through

Write-through が、すべての書き込みでキャッシュを更新し、別の無効化の経路なしに新鮮に保ちます。トレードオフは書き込みのレイテンシ(キャッシュ + DB)と、失敗の順序のリスクです:先にキャッシュへ書き DB の書き込みが失敗すれば、キャッシュが耐久性のないデータを保持し、先に DB へ書けば古さの窓があります。ほとんどのアプリが、ホットキーには write-through、残りには cache-aside を組み合わせます。

memcached
# every write goes to the cache AND the DB synchronously

def update_user(id, data):
    mc.set("user:" + str(id), data, ttl=3600)   # cache first
    db.update(id, data)                          # then DB
    # or DB first, then cache — pick an order and stick with it

# pros:
#   - cache stays fresh after writes (no stale reads)
#   - no invalidation logic needed
# cons:
#   - write latency = cache write + DB write
#   - if the DB write fails after the cache write, cache is inconsistent
#   - cache holds data even if never read (wastes memory)

Write-Behind(Write-Back)

Write-behind が、すぐキャッシュへ書き、キュー経由で非同期に DB へ永続化します — ミリ秒未満の書き込みレイテンシとスパイクの吸収を与えます。代償は一貫性(DB がキャッシュに遅れる)と耐久性です(worker が処理する前のクラッシュがデータを失わせます)。Memcached 単独ではこれができず、キュー + worker が必要です。カウンタやテレメトリのような、書き込みが多く損失を許容するワークロードに限定しましょう。

memcached
# writes go to the cache first; DB is updated ASYNCHRONOUSLY later
# (memcached alone can't do this — it's a cache, not a queue.
#  this pattern needs a worker/queue alongside it.)

def update_user(id, data):
    mc.set("user:" + str(id), data, ttl=3600)
    queue.push({"op":"update","id":id,"data":data})   # async DB write

# a background worker drains the queue to the DB

# pros:
#   - very fast writes (cache-only latency)
#   - absorbs write spikes
# cons:
#   - DB lags behind cache -> reads may see newer data than DB
#   - data loss if cache evicts/evacuates before the worker runs
#   - complex (queue + worker + reconciliation)

キャッシュの無効化

無効化がキャッシュで最も難しい部分です。書き込み時の明示的な delete が基準で、TTL が安全網です(必ず 1 つ設定)。列挙できないコレクションには、バージョン付きのキー(user:1:v42)を使い、スキーマ/データの変更でバージョンを上げれば、古いエントリが寿命で消えます。時間バケットのキー(report:2024-01-01)が日付で自動的に期限切れになります。ワイルドカードの無効化を試みてはいけません — Memcached はキーを列挙できません。

memcached
# invalidation is HARD — "there are only two hard problems in CS"

# 1) explicit invalidation on write
def update_user(id, data):
    db.update(id, data)
    mc.delete("user:" + str(id))     # drop stale entry

# 2) versioned keys to avoid invalidation entirely
key = "user:" + str(id) + ":v" + str(version)
# bump version on update -> old keys auto-expire via TTL

# 3) TTL as a safety net — even with explicit invalidation, set a TTL
#    so a missed invalidation self-heals within (e.g.) an hour

# 4) namespacing by time/date for time-bucketed data
key = "report:" + today_date()      # yesterday auto-expires

# anti-pattern: trying to invalidate "all user:* keys" —
# memcached can't enumerate keys, so use a versioned namespace instead

TTL と追い出しの戦略

TTL をデータの揮発性に合わせましょう:参照データには時間、ユーザーデータには分、レート制限のカウンタには窓の長さです。同期された有効期限の殺到を避けるため、必ずジッター(±5〜10%)を加えましょう。Memcached はメモリ圧迫の下で、アイテムごとのピン留めなしに、slab ごとに LRU 追い出しを行います。レバーは TTL と全体のサイズだけです。ホットキーには、add ベースのロックを使い、ミスのとき 1 クライアントだけが再計算するようにしましょう。

memcached
# choose TTL by data volatility:
#   reference data (rarely changes)   -> 1-24 hours
#   user data (changes on action)     -> 5-60 minutes
#   computed reports                  -> matches refresh cadence
#   sessions                          -> matches idle timeout
#   rate-limit counters               -> matches the window (60s)

# add jitter to prevent synchronized expiry / stampedes:
ttl = base + random.randint(-60, 60)

# on high memory pressure, Memcached evicts LRU items per slab.
# to AVOID eviction of critical data, give it a longer TTL OR
# store it under a key pattern you can pin (memcached has no
# explicit "no-evict" flag — TTL + sizing are your tools).

# stampede protection: lock-and-recompute on miss
if mc.add("lock:user:1", "1", ttl=30):
    val = db.query(1); mc.set("user:1", val, 3600); mc.delete("lock:user:1")
else:
    val = mc.get("user:1")  # another client is refreshing; retry shortly
10

クライアントライブラリ

Python(pymemcache)

pymemcache が純 Python で、速く、明示的です。単一のサーバーには素の Client を、一貫ハッシュを持つクラスタには HashClient を使いましょう。基本が set/get で、multi-get をバッチするのが get_many です。カウンタには add+incr を、楽観的な更新には gets/cas を使いましょう。必ず明示的なタイムアウトを渡しましょう — 死んだノードは、リクエストのスレッドをハングさせるのでなく、速く失敗すべきです。

memcached
# pip install pymemcache
from pymemcache.client.base import Client

mc = Client(("127.0.0.1", 11211), connect_timeout=2, timeout=1)

mc.set("user:1", "alice", expire=3600)
print(mc.get("user:1"))   # b"alice"

# multi-get (batched)
for k, v in mc.get_many(["user:1", "user:2", "user:3"]).items():
    print(k, v)

# counter
mc.add("views", 0)
mc.incr("views", 1)

# CAS loop
while True:
    val, cas = mc.gets("counter")
    if mc.cas("counter", int(val) + 1, cas, expire=0):
        break

# use a consistent-hashing cluster
from pymemcache.client.hash import HashClient
cluster = HashClient([("mc1", 11211), ("mc2", 11211), ("mc3", 11211)])

Node.js(memcached)

memcached の npm パッケージが、単一・マルチサーバー(一貫ハッシュ)のセットアップ、接続プーリング、リトライをサポートします。よくある経路をカバーするのが、set/get/getMulti(バッチされた multi-get)です。poolSize を自分の同時実行へ設定し、死んだノードが速く失敗するよう必ずタイムアウトを設定しましょう。ライブラリはコールバックスタイルです。Promise で包むか、async/await のエルゴノミクスのために util.promisify を使いましょう。

memcached
// npm install memcached
const Memcached = require("memcached");

const mc = new Memcached("127.0.0.1:11211", {
  timeout: 1000,
  retries: 1,
  poolSize: 10,
});

mc.set("user:1", "alice", 3600, (err) => {
  if (err) console.error(err);
});

mc.get("user:1", (err, data) => {
  console.log(data); // "alice"
});

// multi-get
mc.getMulti(["user:1", "user:2"], (err, data) => {
  console.log(data["user:1"]);
});

// counter
mc.incr("views", 1, (err, val) => console.log(val));

// cluster: pass a comma-separated list, client does consistent hashing
const cluster = new Memcached("mc1:11211,mc2:11211,mc3:11211");

mc.end(); // close connections on shutdown

PHP(memcached 拡張)

PHP の memcached 拡張(libmemcached 上に構築)が本番の選択です — サーバーをまたぐ一貫ハッシュのため OPT_LIBKETAMA_COMPATIBLE を設定し、クラスタには addServers を使いましょう。読み取りのバッチが getMulti です。cas() は fetch() の結果配列からトークンを取ります。古い memcache 拡張('d' なし)は避けましょう。機能が乏しく保守も減っています。TTL を必ず設定し、Memcached::RES_NOTFOUND をきれいに処理しましょう。

memcached
<?php
// requires the memcached extension (libmemcached-based)
$mc = new Memcached();
$mc->addServer("127.0.0.1", 11211);

$mc->set("user:1", "alice", 3600);
echo $mc->get("user:1");   // alice

// multi-get returns associative array
$rows = $mc->getMulti(["user:1", "user:2", "user:3"]);

// counter
$mc->set("views", 0);
$mc->increment("views", 1);

// CAS
$mc->getDelayed(["counter"], false, null);
while ($item = $mc->fetch()) {
    $cas = $item["cas"];
    $mc->cas($cas, "counter", intval($item["value"]) + 1);
}

// cluster with consistent hashing
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$mc->addServers([
    ["mc1", 11211],
    ["mc2", 11211],
    ["mc3", 11211],
]);

Ruby(dalli)

Dalli が Ruby の正統な Memcached クライアントです — 純 Ruby、スレッドセーフで、Rails のデフォルトのキャッシュストアです。一貫ハッシュ(ketama)のクラスタリングのためには、サーバーの配列を渡しましょう。cas のブロック形式が、競合時に自動的に再読み込みと再試行を行い、手動のループよりはるかにエルゴノミックです。expires_in をグローバルに設定し、より厳しい TTL のために呼び出しごとに上書きしましょう。

memcached
# gem install dalli
require "dalli"

# single server
mc = Dalli::Client.new("127.0.0.1:11211", { expires_in: 3600 })

mc.set("user:1", "alice")
mc.get("user:1")          # => "alice"

# multi-get (returns a hash)
mc.get_multi(["user:1", "user:2", "user:3"])

# counter
mc.incr("views", 1)
mc.decr("views", 1)

# CAS
mc.get("counter") do |val, cas|
  mc.cas("counter", cas) { val.to_i + 1 }
end

# cluster with consistent hashing (ketama)
cluster = Dalli::Client.new(["mc1:11211", "mc2:11211", "mc3:11211"],
                            { expires_in: 3600 })

Java(spymemcached)

spymemcached が、高性能で非同期の NIO ベースの Java クライアントです。API は Future ベースで、確認が必要なとき get() がブロックします。一貫ハッシュのため、スペース区切りのサーバーリストを AddrUtil へ渡しましょう。楽観的並行性を提供するのが gets()/cas() で、バッチされた multi-get が getBulk() です。IO スレッドを解放するため、アプリのテアダウンで必ず shutdown() しましょう。

memcached
// build.gradle: implementation 'net.spy:spymemcached:2.12.3'
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.AddrUtil;

MemcachedClient mc = new MemcachedClient(
    AddrUtil.getAddresses("mc1:11211 mc2:11211 mc3:11211"));

// async API returns java.util.concurrent.Future
Future<Boolean> f = mc.set("user:1", 3600, "alice");
f.get(); // block for confirmation

Object val = mc.get("user:1");    // "alice"

// counter
mc.incr("views", 1);

// CAS
CASValue<Object> cv = mc.gets("counter");
CASResponse r = mc.cas("counter", cv.getCas(), newVal);
if (r == CASResponse.OK) { /* success */ }

// bulk get
Map<String, Object> rows = mc.getBulk("user:1", "user:2", "user:3");

mc.shutdown();

Go(gomemcache)

gomemcache(bradfitz)が Go の事実上のクライアントです — 単純で速く、複数のサーバーをまたぐ一貫ハッシュをサポートします。Set/Get が、キー、値、TTL、CAS トークンをまとめる Item 構造体を取り、楽観的な更新を行うのが CompareAndSwap です。GetMulti が名前でキー付けされたマップを返します(欠けているキーはエラーではなく不在です)。同時実行セーフなので、goroutine をまたいで 1 つのクライアントを再利用しましょう。

memcached
// go get github.com/bradfitz/gomemcache/memcache
import memcache "github.com/bradfitz/gomemcache/memcache"

mc := memcache.New("mc1:11211", "mc2:11211", "mc3:11211")

// set
err := mc.Set(&memcache.Item{
    Key: "user:1", Value: []byte("alice"), Expiration: 3600,
})

// get
it, err := mc.Get("user:1")
// it.Value -> []byte("alice")

// multi-get (returns map, missing keys absent)
rows, _ := mc.GetMulti([]string{"user:1", "user:2"})

// counter
mc.Increment("views", 1)
mc.Decrement("views", 1)

// CAS
it, _ = mc.Get("counter")
it.Value = []byte("6")
it.Cas = it.Cas   // use existing token
mc.CompareAndSwap(it)

// delete
mc.Delete("user:1")
11

分散アーキテクチャ

一貫ハッシュ

一貫ハッシュが、サーバーとキーの両方をリングへマッピングします。キーを所有するのは時計回りの次のサーバーです。サーバーの追加・削除は、そのサーバーのキーのスライス(約 1/N)だけを動かし、キースペース全体ではありません — メンバーシップの変更でほとんどすべてを再マッピングする hash(key) % N よりはるかに良いです。ほとんどのクライアントが、バランスの取れた分布のために、サーバーごとに多くの仮想ノードを持つ ketama バリアントを使います。

memcached
# consistent hashing spreads keys across servers with minimal
# remapping when the pool changes.
#
# 1) hash each server onto a ring (multiple virtual nodes each)
# 2) hash the key, walk the ring clockwise to the next server
#
#   ring:  s1---s2---s3---s1
#          ^         ^
#        keyA       keyB  -> goes to s3
#
# adding s4 only moves keys between s3 and s4 (not the whole ring)
# removing s1 only moves keys between s1's predecessor and s2
#
# result: |keys moved| ~= keys/N when adding/removing one server
# (vs. ~all keys remapped with hash(key) % N)

# most clients implement ketama consistent hashing automatically
# when you pass a list of servers

クライアント側のシャーディング

すべてのシャーディングがクライアント側にあります:各キーを 1 サーバーへハッシュし、マルチ get をサーバーへ並行に振り分けます。各キーが正確に 1 ノードに存在するため — レプリケーションがなく、死んだノードがキースペースのスライスを失います。プロキシもコーディネーターもなく、すべてのクライアントが同じサーバーリストとハッシュ設定(ketama)を共有しなければなりません。さもないと、キーが別のノードに着地し、大量のミスになります。

memcached
# memcached servers do NOT coordinate — sharding is 100% client-side.
#
# the client picks ONE server per key:
#   server = ring[hash(key)]
#
# a multi-get is split across servers in parallel:
#   getMulti(["a","b","c"])
#     -> get "a" from mc1
#     -> get "b" from mc2   (concurrent, fan-out)
#     -> get "c" from mc1
#
# this means:
#   - each key lives on exactly ONE server (no replication)
#   - a multi-get touches multiple servers but returns one result set
#   - the client must know the full server list (no proxy)

# never put a replica behind the same client as a primary for the
# same key range — memcached clients do not read-replicate

ハッシュのアルゴリズム(Ketama)

Ketama が memcached の正統な一貫ハッシュの方式です:バランスの取れた負荷のために、各物理サーバーが多くの仮想ノード(約 160)としてリングへマッピングされます。キーの所在は、それをハッシュし、時計回りに次のノードをたどります。決定的な落とし穴:すべての言語のすべてのクライアントが、同じアルゴリズムと同一のサーバーラベル文字列を使わなければなりません。さもないと、所有権について意見が割れ、デプロイ後に大量のキャッシュミスになります。

memcached
# ketama is the de-facto consistent-hashing algorithm for memcached.
#
# for each server, create N virtual nodes (default ~160-200):
#   for i in range(vnodes):
#       point = hash("server:port-" + i)
#       ring[point] = server
#
# to locate a key:
#   point = hash(key)
#   server = first node clockwise from point on the ring
#
# benefits of many virtual nodes:
#   - balanced load (no single server gets a huge arc)
#   - smooth redistribution on add/remove
#
# IMPORTANT: all clients must use the SAME algorithm + server labels,
# or they will disagree on which server owns a key.

# enable in clients:
#   PHP:   Memcached::OPT_LIBKETAMA_COMPATIBLE
#   Ruby:  default in dalli
#   Python: HashClient (pymemcache)

サーバーの追加と削除

一貫ハッシュにより、サーバーの追加・削除は約 1/N のキーだけを再マッピングします — ほとんどすべてを再マッピングするモジュロハッシュよりはるかに良いです。しかし、サーバーのクラッシュは依然そのキーを恒久的に失わせます(レプリケーションなし)。これらのエントリが再充填する間、オリジンの負荷へ一時的なスパイクが起きます。メンバーシップの変更は、すべてのクライアントへ一度に展開し、稼働の前に影の読み取りで新しいノードを予熱することを検討しましょう。

memcached
# adding a server to the ring:
#   - only ~1/N of keys remap (the slice the new server now owns)
#   - those keys are cold misses until repopulated -> brief spike
#
# removing a server (e.g. crash):
#   - that server's keys are GONE (no replication)
#   - its slice of the ring is reassigned to neighbors
#   - all reads to those keys miss until repopulated
#
# best practices for membership changes:
#   1) deploy new server list to all clients simultaneously
#   2) warm a new server with a shadow-read phase if possible
#   3) expect a transient increase in DB load (cache misses)
#   4) use weighted virtual nodes to add capacity gradually

# anti-pattern: hash(key) % N  -> changes ALL key placements on
# every membership change (catastrophic for cache hit rate)

レプリケーションとフェイルオーバー

Memcached には組み込みのレプリケーションやフェイルオーバーがありません — 死んだノードがデータを失い、クライアントが再ルートします。冗長性を加えるには、クライアントでレプリケートするか(N ノードへ書き込む、コスト増)、mcrouter/twemproxy のようなプロキシを実行するか、損失を受け入れオリジンから再構築します。正統な選択は最後です:キャッシュを使い捨てとし、プールを、1 ノードの損失が許容できるようにサイズし、ミスが DB から再充填させましょう。

memcached
# memcached has NO built-in replication or failover.
# if a node dies, its data is gone — clients reroute to the ring.
#
# to ADD replication, options:
#
# 1) client-side replication: write to N servers per key
#    - the client writes to primary + replica(s) on each set
#    - reads try primary, fall back to replica
#    - trade-off: N x write traffic + memory, weaker consistency
#
# 2) repcached: a memcached fork with master/replica replication
#    - largely unmaintained today; avoid for new projects
#
# 3) use a layer above: twemproxy / mcrouter / mc-router
#    - proxy that handles sharding, pooling, failover
#
# 4) accept the loss: cache is volatile by design — rebuild from DB

# the "memcached way" is usually option 4: don't replicate, just
# size the pool so a single node loss is survivable
12

メモリ管理(Slab / LRU)

Slab アロケータ

Memcached は slab アロケータを使います:メモリが固定サイズのチャンクのクラスへ分割され、アイテムが収まる最も小さいチャンクに(切り上げて)保存されます。これで malloc/free の断片化が避けられ O(1) の割り当てが得られます。代償は、内部断片化(チャンク内の無駄なスペース)と、クラスの石灰化(メモリがクラス間を動けない)です。値のサイズの均等な混合が、効率のために効く理由です。

memcached
# memcached does NOT use malloc/free per item (that fragments).
# instead it pre-allocates fixed-size "slab classes" of chunks.
#
#   slab class 1: chunks of 96 bytes
#   slab class 2: chunks of 120 bytes
#   slab class 3: chunks of 152 bytes   (grow by -f factor)
#   ...
#
# a 50-byte value -> rounded up to 96-byte chunk (class 1)
# a 100-byte value -> rounded up to 120-byte chunk (class 2)
#
# trade-offs:
#   + no per-item malloc overhead, no heap fragmentation
#   + O(1) alloc/free
#   - internal fragmentation (wasted bytes inside a chunk)
#   - memory is stuck per class (can't move between classes)

# inspect with:
stats slabs

Slab クラスと成長係数

slab クラスのサイズは -n の最小(デフォルト 48 バイト)から始まり、-I の最大アイテムサイズまで、-f の係数(デフォルト 1.25)で成長します。低い -f が、より多くの、より細かいクラスを与えます(無駄が減るが、クラスの石灰化のリスクが増す)。高い -f が、より少ない、より粗いクラスを与えます(無駄が増す)。stats sizes で本物の値サイズのヒストグラムを検査し、人気のサイズがよく満たされたクラスに着地するよう -f を調整しましょう。

memcached
# slab class sizes start at -n (default 48 bytes) and grow by -f:
#
#   class 1:  48 bytes  (base, -n)
#   class 2:  48 * 1.25 = 60
#   class 3:  60 * 1.25 = 75 -> 80
#   class 4:  80 * 1.25 = 100
#   ...
#   up to the max item size (-I, default 1MB)
#
# -f default 1.25 balances class count vs. waste.
#   lower (1.1) -> more classes, less waste, but more stuck memory
#   higher (1.5) -> fewer classes, more waste per chunk
#
# tune -f to your value-size distribution (check stats sizes)

# example: many small JSON values -> -f 1.1 -n 80
memcached -m 512 -f 1.1 -n 80

LRU 追い出し

追い出しは slab クラスごとに、そのクラス内では厳密に LRU です:クラスが満杯になると、そのクラスの最も最近使われていないアイテムが場所を作るために落とされます。空きチャンクのあるクラスは決して追い出さないため、偏ったサイズの分布が、あるクラスでの重い追い出しと、別のクラスのアイドルを引き起こし得ます — クラシックな slab の石灰化の問題です。発見するには、stats で evictions と evicted_active を見ましょう。

memcached
# when a slab class is full and a new item arrives in that class,
# memcached evicts the LEAST RECENTLY USED item in that class.
#
# eviction is PER-SLAB-CLASS, not global:
#   - a full class-1 (96B) evicts class-1 items only
#   - a class with free chunks never evicts
#
# this means an unbalanced workload can evict from one class
# while another class sits idle with free chunks.
#
# check eviction pressure:
stats
# STAT evictions 1234     # total items ever evicted
# STAT evicted_active 12  # evicted even though recently used (1.6+)
# STAT evicted_unfetched 50  # evicted before ever read

stats items
# STAT items:1:evicted 500   # evictions in slab class 1
# STAT items:1:outofmemory 0

メモリの上限(-m)

-m がアイテムメモリに MB で上限を設けます。上限に達すると、Memcached が slab ページの追加を止め、クラス内で LRU を追い出します。追い出しの代わりに満杯時のエラーへ方針を変えるのが -M です(キャッシュではめったに望まれません)。上限のライブ変更は cache_memlimit です。余裕付きのワーキングセットに -m をサイズしましょう — 100% での実行は、恒常的な追い出しと、撹拌的な低ヒット率のキャッシュを意味します。

memcached
# -m sets the max memory for items (in MB)
memcached -m 64        # default: 64 MB
memcached -m 4096      # 4 GB

# once -m is reached, memcached stops allocating new slab pages and
# relies on LRU eviction within each class.
#
# -M flips behavior: instead of evicting, return an ERROR on writes
# when memory is full (rarely what you want for a cache).
memcached -m 512 -M

# resize the memory cap at runtime (bytes):
cache_memlimit 2147483648   # 2 GB
# -> OK   (only grows/shrinks the page pool; doesn't drop items
#          unless shrinking forces eviction)

# monitor:
stats
# STAT bytes 424463360        # current bytes in use
# STAT limit_maxbytes 536870912  # the -m limit

追い出しポリシーと調整

Memcached の唯一の追い出しポリシーが slab ごとの LRU です — LFU やランダムのオプションはありません。追い出しを減らす方法:-m を上げる、TTL を短くする、値のサイズの再バランス、-f の調整です。石灰化を緩和するため、モダンなビルドが LRU クローラと、slab ページの再割り当ての能力を加えています(slabs reassign / slabs automove)。ホットなクラスの検出は、stats items の evicted/outofmemory のカウンタで。

memcached
# memcached's only eviction policy is LRU (per slab class).
# (Redis offers LRU/LFU/random/TTL; memcached does not.)
#
# 1.6+ adds an LRU crawler + "temporary" vs "permanent" LRU tiers:
#   lru_crawler enable
#   lru_crawler tocrawl 1000
#
# to reduce evictions:
#   - increase -m (more memory)
#   - shorten TTLs so items self-expire before LRU drops them
#   - rebalance value sizes (avoid one hot slab class)
#   - tune -f so popular sizes map to well-populated classes
#
# detect a hot/evicting class:
stats items
# STAT items:5:evicted 9999     <- class 5 is under pressure
# STAT items:5:outofmemory 0

# rebalance slab memory automatically (1.5+):
slabs reassign 5 1   # move a page from class 5 to class 1
slabs automove 1     # let the server auto-rebalance (cautious mode)

Slab の Automove と Reassign

slabs reassign(手動)と slabs automove(1.5+、自動)により、slab ページが、空きチャンクのあるクラスから追い出し圧力下のクラスへ再バランスできます — slab の石灰化の治療です。production-safe な、慎重でゆっくりした背景の動かし手が automove=1 で、=2 は積極的で実験的です。前後で必ず stats slabs で検証しましょう — 間違った再割り当てが、クラスを飢えさせます。

memcached
# 1.5+ lets you move a slab PAGE from a class with free chunks
# to a class under memory pressure.
#
# manual one-shot move:
slabs reassign 1 5     # take a page from class 1, give to class 5
# -> DONE  (or BUSY if the page is being freed)

# automatic rebalancing (runs in the background):
slabs automove 0       # off (default)
slabs automove 1       # cautious auto-move (slow, safe)
slabs automove 2       # aggressive (experimental; watch carefully)

# the automover watches evictions/free chunks and slowly shifts
# pages to relieve pressure. It's conservative by design.

# check current slab state:
stats slabs
# STAT 1:total_pages 4
# STAT 1:free_chunks 0    <- class 1 is full
# STAT 5:total_pages 12
# STAT 5:free_chunks 8000 <- class 5 has room to give
13

パフォーマンスの最適化

noreply とパイプライン

noreply が書き込みごとのレスポンスを切り、パイプラインが多くのコマンドを 1 回のネットワークラウンドトリップへまとめます — 両方合わせて、一括書き込みの最大のスループットのレバーです。読み取りに対する同じことが multi-get です。noreply の代償は、コマンドごとのエラーフィードバックを失うことであるため、非クリティカルで高ボリュームの書き込みに限定し、失敗が表面化されるべきすべてにはレスポンスを残しましょう。

memcached
# noreply skips the server's response for write commands.
# use it for fire-and-forget writes to cut latency & network:
set k1 0 0 5 noreply
hello
set k2 0 0 5 noreply
world
# (no STORED echoed back)

# pipelining: send many commands in one batch without waiting for
# each response (binary protocol and most clients support this).
# ideal for bulk inserts/refreshes.

# trade-off:
#   + fewer round-trips, higher throughput
#   - no error feedback per command (use sparingly for critical writes)

# multi-get is the read-side equivalent: one request, N keys
get user:1 user:2 user:3 user:4

バイナリプロトコル

バイナリプロトコルが ASCII より効率的です:テキストのパースの代わりの固定 24 バイトヘッダー、パイプラインのためのネイティブな quiet(noreply 風)の操作、認証のための SASL 対応です。小さな値と高いスループットの一括書き込みでは、測定可能に速いです。サーバーが同じポートで両方のプロトコルを話すため、有効化は純粋にクライアント側の選択です。本番のクライアントではこれを推奨しましょう。

memcached
# the binary protocol (vs ASCII text) is more efficient:
#   - fixed 24-byte header (no string parsing)
#   - supports SASL authentication
#   - supports pipelining and quiet (noreply-equivalent) ops natively
#   - smaller wire footprint for small values
#
# enable on the client side (the server speaks both on the same port):
#   pymemcache: Client(..., allow_unicode_keys=True, default_noreply=True)
#   spymemcached: use the binary connection factory
#   libmemcached: MEMCACHED_BINARY_PROTOCOL

# binary quiet ops (Noop/SetQ/AddQ/...):
#   pipelined writes that only reply on error — perfect for bulk loads

# the server listens for both protocols on 11211 by default;
# no server-side flag is required

接続プーリング

接続プーリングは不可欠です — リクエストごとの TCP 接続のオープンが、エフェメラルポートを燃やし、レイテンシを加えます。サーバーごと、プロセスごとに、自分の同時実行に合わせた、小さい永続接続のプールを保ちましょう。stats で total_connections と curr_connections を見ましょう:total が traffic と共に成長するのに curr がフラットなら、プーリングしています。total が爆発するなら、していません。設定すれば、ほとんどのクライアントが内部でプールします。

memcached
# opening a TCP connection per request is extremely wasteful.
# reuse connections via a pool:
#
#   - keep N persistent connections per server per app process
#   - checkout -> use -> checkin (don't close)
#   - size the pool to your concurrency, not your request rate
#
# pymemcache: HashClient manages a pool internally
# Node.js memcached: set poolSize
# PHP: persistent connections via memcached::OPT_CONNECT_TIMEOUT
# Java spymemcached: one MemcachedClient (thread-safe, NIO)
#
# signs of a missing pool:
#   - high total_connections in stats (grows with traffic)
#   - TIME_WAIT exhaustion on the server (ephemeral ports)
#   - request latency dominated by connect() not get()/set()

stats
# STAT total_connections 1000000   <- too high; pool your conns
# STAT curr_connections 50         <- healthy pooled count

一括操作(Multi-Get)

multi-get が 1 回のラウンドトリップで N キーを取得します — 利用可能な最大の単一の読み取り最適化です。クライアントがキーをサーバーへ並行に振り分けるため、レイテンシはキー数ではなく最も遅いサーバーに上限が設けられます。単一のサーバースレッドが独占されないよう、非常に大きな multi-get(100 キーなど)はチャンク化し、欠けているキーが結果のマップから静かに不在になることを覚えましょう。

memcached
# fetching N keys in one get is far cheaper than N single gets:
#   1 network round-trip instead of N
#   server parses 1 command instead of N

# text protocol: space-separated keys
get user:1 user:2 user:3 user:4 user:5

# clients wrap this:
#   pymemcache:  mc.get_many([...])
#   Node.js:     mc.getMulti([...])
#   PHP:         $mc->getMulti([...])
#   Go:          mc.GetMulti([]string{...})

# best practices:
#   - chunk very large multi-gets (e.g. 100 keys at a time)
#     so no single server thread is monopolized
#   - keys in a multi-get fan out to multiple servers — the client
#     parallelizes, so a multi-get is bound by the SLOWEST server
#   - missing keys are simply absent from the result

値の適正サイズ

アイテムが次のチャンクサイズへ切り上げられるため、値のサイズが内部断片化を直接駆動します — 96 バイトのチャンクの中の 60 バイトの値が 37% を無駄にします。値を適正サイズにしましょう:JSON の空白のトリミング、約 1KB を超えるものの圧縮(フラグのビットで印付ける)、blob 全体ではなくプロジェクションのキャッシュです。stats sizes でサイズのヒストグラムを検査し、よくあるサイズがチャンクの境界近くに着地するよう -f を調整しましょう。

memcached
# because of the slab allocator, value size drives memory waste:
#
#   a 60-byte value -> 96-byte chunk -> 36 bytes wasted (37%!)
#   a 97-byte value -> 120-byte chunk -> 23 bytes wasted (19%)
#
# right-size values to fit chunk boundaries:
#   - trim/normalize JSON before caching (drop whitespace, short keys)
#   - compress large values (>1KB) with gzip/snappy; set a flags bit
#   - avoid caching huge blobs; cache projections instead
#
# check your size distribution:
stats sizes      # (off-peak; it locks)

# pick -f so common sizes land near chunk boundaries:
#   if most values are 100-200 bytes, -f 1.25 is fine
#   if values cluster at a few sizes, tune -f to match

# flags bit to mark compression:
set bigval 2 0 4096   # flags=2 means "gzip compressed" (your convention)

ホットキーの回避

ホットキーが、単一サーバー・単一スレッドのボトルネックです — その読み取りが 1 ノード上で逐次化される間、他がアイドルします。N 個のバケットへシャードするか(ランダムなバケットを読み、更新時にすべてへ書く)、リロードを統合するため 1 秒のクライアント側 TTL を加えるか、プロセス内の LRU へ動かしましょう。ホットキーの検出は、サーバーごとの CPU の不均衡か、1.6+ ではアクセス頻度を覗く lru_crawler metadump で。

memcached
# a single hot key creates a bottleneck: it lives on ONE server
# and ONE worker thread, so concurrent reads serialize.
#
# symptoms: one memcached server at 100% CPU while others idle;
#           one slab class churning while others are calm.
#
# fixes:
#   1) shard the hot key into N buckets:
#        key = "hot:" + str(random.randint(0, 9))   # 10 buckets
#      write to all N on update; read from a random one
#   2) add a short client-side TTL (e.g. 1s) to coalesce reloads
#   3) precompute and rotate (cache the rendered page, not the query)
#   4) move the hot value closer to the app (in-process LRU)
#
# detect with:
#   - per-server CPU/stats imbalance
#   - lru_crawler metadump all  (peek at access frequency, 1.6+)
14

モニタリング

見るべきコアの統計

4 つの看板の指標は、ヒット率(get_hits/cmd_get、目標 >95%)、evictions(メモリ圧迫、定常状態の目標 0)、メモリ利用率(bytes/limit_maxbytes、目標 <90%)、listen_disabled_num(接続上限への到達、目標 0)です。カウンタだけでなく、時間をかけたレートとして追跡しましょう。落ちるヒット率や上がる evictions が、不健康なキャッシュの最も早い兆候です。

memcached
# the four numbers to monitor continuously:
stats
# STAT cmd_get, cmd_set        # throughput (ops/sec deltas)
# STAT get_hits, get_misses    # hit rate = hits / cmd_get
# STAT evictions               # memory pressure (rising = bad)
# STAT bytes / limit_maxbytes  # memory utilization %

# derived metrics:
#   hit_rate    = get_hits / cmd_get            # target > 95%
#   eviction_r  = evictions_delta / cmd_set_delta
#   mem_usage   = bytes / limit_maxbytes        # target < 90%

# connection health:
# STAT curr_connections         # active conns
# STAT listen_disabled_num      # >0 = hit -c limit (refused conns)

# alert thresholds (suggestions):
#   hit_rate < 90%        -> investigate cold keys / undersizing
#   evictions > 0 (steady)-> add memory or shorten TTLs
#   listen_disabled_num > 0 -> raise -c

memcached-tool

memcached-tool が、手軽なアドホックチェックのための同梱 CLI です:slab ごとのテーブルは stats、ライブ更新のビューは display、キーを覗くのは dump です(デバッグ専用 — LRU をたどります)。SSH での 1 回の実行には完璧ですが、継続的なモニタリングには向きません。本番のダッシュボードとアラートには、Prometheus エクスポーターと Grafana とペアにしましょう。

memcached
# memcached-tool ships with the server — quick CLI stats:
memcached-tool host:port stats
memcached-tool host:port display      # live-refreshing table
memcached-tool host:port dump         # dump keys (debug only!)

# sample output of "stats":
#   #  Item_Size  Max_age  Pages  Count  Full?  Evicted Evict_Time
#   1     96B        3600s    1    100    no        0       0
#   2    120B        7200s    2    250    no        0       0
#   ...

# great for a one-off SSH check; not for continuous monitoring.
# for the latter, use a Prometheus exporter + Grafana.

Telnet でのモニタリング

ポート 11211 への Telnet か netcat が、アドホックチェックのためのテキストプロトコルへの即時の対話アクセスを与えます:stats、stats settings、stats items、stats slabs、version です。スクリプトには、nc の 1 行(echo 'stats' | nc -q 1 host 11211)を使いましょう。flush_all が破壊的であることを覚えましょう — 安易にエイリアスしないこと。これが、ノードを検査する最も低い摩擦の方法です。

memcached
# quick interactive check via telnet/nc:
telnet localhost 11211
stats
stats settings
stats items
stats slabs
version
quit

# or one-liners with nc:
echo "stats" | nc -q 1 localhost 11211
echo "stats slabs" | nc -q 1 localhost 11211

# flush all keys (DESTRUCTIVE — use with care):
echo "flush_all" | nc -q 1 localhost 11211

# tip: pipe commands from a file for repeatable checks
nc localhost 11211 < checks.txt

Prometheus エクスポーターと Grafana

memcached_exporter が標準の Prometheus 統合です — 各ノードの隣で 1 つ実行し、:9150 を収集しましょう。Grafana のダッシュボードが、ヒット率、追い出し率、メモリ使用量、slab ごとの充填を追跡します。アラートの対象:90% 未満へのヒット率の低下、どんな定常的な evictions、90% を超えるメモリ、listen_disabled_num > 0 です。これで、アドホックな telnet では得られない、継続的で歴史的な可視性が得られます。

memcached
# popular exporters scrape memcached stats into Prometheus:
#
# 1) memcached_exporter (official):
#    https://github.com/prometheus/memcached_exporter
#    run alongside each memcached instance:
memcached_exporter --memcached.address=localhost:11211 \
  --web.listen-address=:9150

# 2) scrape config in prometheus.yml:
#    - job_name: 'memcached'
#      static_configs:
#        - targets: ['mc1:9150','mc2:9150','mc3:9150']

# 3) Grafana dashboard (e.g. community id 37 or custom):
#    - hit rate (get_hits / cmd_get)
#    - eviction rate (rate(evictions[5m]))
#    - memory usage (bytes / limit_maxbytes)
#    - connections (curr_connections, listen_disabled_num)
#    - per-slab fill / evictions

# alert on: hit rate < 90%, evictions > 0 steady, mem > 90%

主要指標とアラート

アラートの対象:ヒット率の劣化(警告 <90%、クリティカル <75%)、どんな定常的な evictions、90% を超えるメモリ、どんな拒否された接続です。キャッシュの指標は常にオリジンの指標と相関させましょう — DB の CPU スパイクとペアになったヒット率の低下が、キャッシュミスの嵐の署名であり、上昇するオリジンのレイテンシとペアになった上昇する evictions が、undersized なキャッシュを指します。サイレントな再起動を捉えるため、uptime のリセットを追跡しましょう。

memcached
# metric                  alert when                     severity
# ------------------------------------------------------------------
# hit_rate                < 90% sustained                 warning
# hit_rate                < 75% sustained                 critical
# evictions (rate)        > 0 steady                      warning
# evictions (rate)        > 100/min                       critical
# mem_usage               > 90%                           warning
# mem_usage               > 98%                           critical
# listen_disabled_num     > 0 (refused conns)             critical
# curr_connections        > 80% of -c                     warning
# uptime                  resets (process restarted)      info
# cmd_get/cmd_set rates   sudden drop (app -> cache down) critical

# pair cache metrics with origin metrics:
#   if cache hit rate drops AND DB CPU spikes -> cache miss storm
#   if cache evictions rise AND origin latency rises -> undersized
15

セキュリティ

ネットワークの隔離

Memcached のテキストプロトコルには認証がないため、公開されてはいけません — -l で 127.0.0.1 かプライベート NIC へ bind し、未使用なら -U 0 で UDP を無効化し、11211 をアプリのサブネットだけにファイアウォールしましょう。公開で到達可能な Memcached が、開かれたデータキャッシュであり、UDP 増幅の DDoS の経路でもあります(CVE-2018-1000115)。デフォルトの listen アドレスがすべてのインターフェースであるため — 必ず上書きしましょう。

memcached
# memcached has NO authentication in the text protocol.
# it MUST NOT be exposed to the public internet.
#
# bind to loopback or a private network only:
memcached -l 127.0.0.1                  # local only
memcached -l 10.0.0.5                   # private NIC
memcached -l 10.0.0.5 -U 0              # also disable UDP

# firewall: deny 11211 from outside, allow only app subnets
# iptables example:
#   iptables -A INPUT -p tcp --dport 11211 -s 10.0.0.0/24 -j ACCEPT
#   iptables -A INPUT -p tcp --dport 11211 -j DROP

# CRITICAL: the default -l is ALL interfaces.
# A public memcached is an open cache AND a UDP amplification
# vector (CVE-2018-1000115 etc.) — disable UDP if unused.

SASL 認証(バイナリプロトコル)

SASL 認証はバイナリプロトコル上でのみ利用可能です(-S でサーバーを起動)。接続のセットアップフェーズで PLAIN の資格情報を使い、プーリングが償却する 1 ラウンドトリップを加えます。ネットワーク隔離だけでは不十分な、共有かマルチテナントのネットワークでは SASL を使いましょう。テキストプロトコルは認証できません — 認証が必要なら、バイナリプロトコルを端から端まで使う必要があります。

memcached
# the BINARY protocol supports SASL (PLAIN) authentication.
# the text protocol does NOT.
#
# server: start with SASL enabled (built-in in most distros)
memcached -S -l 10.0.0.5

# create a SASL user (e.g. via saslpasswd2):
echo -n "myuser" | saslpasswd2 -p -a memcached myuser

# client: provide credentials
#   pymemcache: Client(..., sasl_credentials=("myuser","pass"))
#   spymemcached: use the binary factory + auth descriptor
#   libmemcached: MEMCACHED_BEHAVIOR_SASL

# note: SASL adds a round-trip at connection setup; pooled
# connections amortize this. Use it on shared/multi-tenant networks
# where -l alone isn't enough.

暗号化と TLS

Memcached にはネイティブの TLS がありません — トラフィックを暗号化するには、各ノードの前に stunnel や HAProxy のようなサイドカーで TLS を終端し、その後ろでループバック上の平文の memcached を実行しましょう。ほとんどの LAN デプロイでは、ネットワーク隔離と省略可能な SASL が十分です。TLS は、ネットワークをまたぐフローやコンプライアンスを要求される環境に限定しましょう。新しいフォーク(といくつかのクラウドのマネージドサービス)がネイティブ TLS を加えています。

memcached
# memcached itself does NOT support TLS/SSL natively.
# to encrypt traffic, terminate TLS in front of the server:
#
#   app --TLS--> stunnel/haproxy --plain--> memcached
#
# stunnel example (server side):
#   [memcached]
#   accept = 11443
#   connect = 127.0.0.1:11211
#   cert = /etc/stunnel/mc.pem
#
# the client also needs a stunnel/haproxy side, OR a client that
# speaks TLS (some newer forks/patches add native TLS).
#
# for most LAN deployments, network isolation + SASL is enough;
# reserve TLS for cross-network or compliance-required flows.

ファイアウォールとアクセス制御

防御をレイヤー化しましょう:プライベート NIC への bind、アプリサブネットへのファイアウォール、UDP の無効化、共有ネットワークでの SASL、非 root ユーザーでの実行、systemd の強化(NoNewPrivileges、ProtectSystem、PrivateTmp)です。決定的に重要なのは、Memcached に生のシークレットを保存しないことです — それはキャッシュでありボールトではありません。encrypt-then-cache するか、シークレットは専用のシークレットマネージャーに置き、非機密の参照だけをキャッシュしましょう。

memcached
# defense in depth for memcached:
#
# 1) bind to a private interface (-l 10.0.0.5)
# 2) firewall 11211 to app subnets only
# 3) disable UDP if unused (-U 0) — UDP is an amplification vector
# 4) use SASL on shared networks
# 5) TLS via stunnel for cross-network
# 6) run as a non-root user (-u memcache)
# 7) drop privileges / use systemd hardening
# 8) never store secrets in memcached unencrypted — it's a cache,
#    not a vault (use a secrets manager + encrypt-then-cache)

# systemd hardening example:
# [Service]
#   User=memcache
#   NoNewPrivileges=true
#   ProtectSystem=strict
#   PrivateTmp=true

セキュリティのベストプラクティス

最重要のルール:Memcached を公開しない、常にプライベートインターフェースへ bind する、UDP を無効化する、共有ネットワークで SASL を使う、です。シークレットや PII を暗号化せずに保存してはいけません。ユーザーをまたぐ漏れを防ぐため、キーをテナントごとに名前空間化しましょう。サーバーをパッチで保ち、stats conns で接続を監査し、キャッシュの侵害をデータ侵害として扱いましょう — キャッシュされたかもしれないトークンをすべてローテーションします。

memcached
# 1) NEVER expose memcached to the internet (no auth in text proto)
# 2) ALWAYS set -l to loopback or a private address
# 3) disable UDP (-U 0) unless you specifically need it
# 4) use SASL on the binary protocol for multi-tenant networks
# 5) don't store secrets/PII in the cache unencrypted
# 6) namespace keys per-tenant to avoid cross-tenant leakage
#    (e.g. "tnt:42:user:1" — never shared global keys)
# 7) keep memcached updated (security CVEs do happen)
# 8) audit with stats conns to see who's connected
# 9) log and alert on unexpected connection sources
# 10) treat a cache breach as a data breach: rotate any tokens that
#     might have been cached
16

Memcached 対 Redis

データ型と機能

Memcached が純粋な文字列のキー・バリューのキャッシュであるのに対し、Redis がデータ構造のサーバーです:リスト、ハッシュ、セット、ソート済みセット、ストリーム、Lua スクリプト、トランザクション、pub/sub、モジュール。必要なときは、Redis の豊かさが強みですが、純粋なキャッシングにとっては、Memcached のミニマリズムが機能です — 表面が小さく、誤設定も減ります。サーバー側のデータ構造が必要かどうかで選びましょう。

memcached
# Memcached:
#   - strings only (key -> bytes), plus the numeric incr/decr trick
#   - no lists, hashes, sets, sorted sets, streams, pub/sub
#   - no server-side scripting (no Lua)
#   - no transactions (single-key CAS only)
#   - no keyspace notifications
#
# Redis:
#   - rich types: strings, lists, hashes, sets, zsets, streams, ...
#   - Lua scripting, MULTI/EXEC transactions, pub/sub
#   - modules (RedisJSON, RediSearch, RedisGraph, ...)
#   - per-key TTL on any type
#
# verdict: Redis is a data-structure server; memcached is a
# pure key-value cache. Pick memcached when you only need a cache.

永続化

Memcached には永続化がゼロです — 設計により、再起動で空になり、キャッシュは常に使い捨てです。RDB スナップショットと AOF の耐久性、加えてレプリケーションを提供するのが Redis で、一次データストアとして機能できます。キャッシュが再起動に耐えるべきか、信頼できるデータを保持すべきなら、Redis が勝ちます。ミスで再構築する純粋な揮発キャッシュが欲しいなら、Memcached のシンプルさが美徳です。

memcached
# Memcached:
#   - NO persistence. A restart loses everything. By design.
#   - no snapshots, no AOF, no replication
#   - the cache is always disposable; rebuild from the DB on miss
#
# Redis:
#   - RDB snapshots (point-in-time) and AOF (append-only log)
#   - can act as a primary datastore with durability
#   - replication + sentinel/cluster for HA
#
# verdict: if you need the cache to survive restarts, use Redis.
# if you want a pure volatile cache (and rebuild on miss), memcached's
# lack of persistence is simpler and faster.

レプリケーションとクラスタリング

Memcached にはサーバー側のクラスタリングもレプリケーションもありません — 分散は完全にクライアント側で、死んだノードがキーを恒久的に失います。Redis が提供するのは、master/replica のレプリケーション、HA のための Sentinel、自動フェイルオーバー付きのシャーディングのための Redis Cluster です。Memcached が運用はより簡単です(gossip なし、フェイルオーバーのロジックなし)が HA はなく、Redis が運用の複雑さと本物の耐性をトレードします。

memcached
# Memcached:
#   - NO server-side clustering or replication
#   - sharding is 100% client-side (consistent hashing)
#   - a dead node loses its keys; clients reroute
#   - scale out = add nodes to the ring
#
# Redis:
#   - master/replica replication (async)
#   - Sentinel for HA/failover
#   - Redis Cluster for sharding + automatic failover
#   - more moving parts, but true HA
#
# verdict: memcached is simpler to operate (no cluster gossip) but
# has no failover — a dead node is data loss for its keys.
# Redis gives you replication + failover at the cost of complexity.

パフォーマンスの特性

どちらもメモリ内でミリ秒未満です。Memcached がデフォルトでマルチスレッドであり、純粋な get/set でコアをまたいでスケールするのに対し、Redis は(ほとんど)コマンド実行がシングルスレッドです。そのため、get/set だけを行う大きなマルチコアのマシンでは、Memcached がより高い QPS に届けます。ほとんどの実アプリでは差は無視でき、マイクロベンチマークではなく、機能と運用の適合で選びましょう。

memcached
# Both are in-memory and very fast (sub-millisecond, >100k ops/s).
#
# Memcached:
#   - multi-threaded by default (-t workers); scales across cores
#   - simple protocol, low overhead per op
#   - excellent for high-throughput pure get/set
#
# Redis:
#   - single-threaded command execution (Redis 6+ threads the I/O)
#   - one core does the work; more cores don't speed a single command
#   - richer ops can be slower, but core get/set is comparable
#
# verdict: for pure get/set at very high QPS on a big multi-core box,
# memcached's multi-threading can win. For most apps the difference
# is negligible; pick by features, not microbenchmarks.

メモリ効率

不透明な blob には Memcached の slab アロケータが軽いですが、チャンクの切り上げでスペースを無駄にします。Redis はキー/フィールドごとのオーバーヘッドがありますが、小さな構造にコンパクトなエンコーディング(listpack)を選びます。どちらが普遍的に小さいかはありません — 一様な blob では Memcached が勝ち、小さな構造化データでは Redis が勝てます。どちらが安いかを仮定する前に、自分の値の形状で必ず測りましょう。

memcached
# Memcached:
#   - slab allocator: fixed chunks, some internal fragmentation
#   - no per-field overhead (it's just bytes)
#   - very lean for small uniform values
#   - can waste memory if value sizes don't fit slab classes
#
# Redis:
#   - per-key/per-field overhead (complex internal structures)
#   - many encodings (listpack, hashtable, skiplist, ...) chosen by size
#   - richer structures use more memory than a flat string
#   - but more memory-efficient for small structured data via listpack
#
# verdict: memcached is leaner for opaque blobs; Redis can be leaner
# for small structured data (listpack). Measure with your own data.

どちらを選ぶか

運用の単純さとマルチスレッドのスケーリングが効く、純粋で使い捨ての get/set キャッシュには Memcached を選びましょう。データ構造、永続化、レプリケーション、クラスタリング、Lua、pub/sub、モジュールが必要なら Redis です。相互排他ではありません — 多くのスタックが両方を実行し、生のページ/クエリのキャッシングに Memcached、セッション、リーダーボード、レート制限、ストリームに Redis を使います。

memcached
# Choose Memcached when:
#   - you need a pure, disposable get/set cache
#   - you value operational simplicity (no clustering, no persistence)
#   - you want multi-threaded scaling on a big box
#   - your data is opaque blobs and you rebuild on miss
#
# Choose Redis when:
#   - you need data structures (lists, hashes, sets, zsets, streams)
#   - you need persistence or durability
#   - you need replication / failover / clustering
#   - you need server-side logic (Lua, pub/sub, modules)
#   - you need per-key TTL on rich types
#
# both can coexist: memcached for raw page/query cache, Redis for
# sessions, leaderboards, rate-limiting, streams.
17

トラブルシューティング

接続拒否

接続拒否の通常の意味は、サーバーが動いていない、期待するアドレスで listen していない(ループバックに bind した -l がリモートクライアントをブロックする)、ファイアウォールされている、または -c の接続上限に達した(listen_disabled_num > 0)です。チェックリストをたどりましょう:プロセスは ps/systemctl、リスナーは ss/netstat、ファイアウォールは iptables、接続上限は stats、クラッシュのログは journalctl です。

memcached
# symptom: client reports "connection refused" to 11211
#
# 1) is memcached running?
ps aux | grep memcached
systemctl status memcached

# 2) is it listening on the expected address/port?
ss -tlnp | grep 11211
netstat -tlnp | grep 11211

# 3) check the -l bind address (default = ALL; you may have set 127.0.0.1)
#    a client on another host can't reach a loopback-bound server

# 4) firewall blocking?
iptables -L -n | grep 11211

# 5) hit the -c connection limit? (check listen_disabled_num)
echo "stats" | nc -q 1 host 11211 | grep listen_disabled

# 6) check memcached logs / journalctl
journalctl -u memcached -n 100

追い出しの嵐

満杯のキャッシュで上昇する evictions は、ワーキングセットが -m を超えていることを意味します。診断は stats(bytes == limit_maxbytes)と stats items(どの slab クラスが追い出しているか)で。修正:-m を上げる、アイテムが自己期限切れになるよう TTL を短くする、slab ページの再バランスは slabs reassign/automove、値を膨らませる暴走する writer の追跡です。恒久的に満杯のキャッシュには、より多くのメモリか、より小さなワーキングセットが必要です。

memcached
# symptom: evictions counter rising fast, hit rate dropping
#
# diagnosis:
stats
# STAT evictions 999999     <- climbing
# STAT bytes 67108864
# STAT limit_maxbytes 67108864   <- 100% full

stats items
# STAT items:3:evicted 500000    <- slab class 3 is the victim
# STAT items:3:outofmemory 0

# fixes:
# 1) add memory: raise -m (or cache_memlimit at runtime)
# 2) shorten TTLs so items self-expire before LRU drops them
# 3) rebalance slab classes: slabs reassign <donor> <receiver>
#    or: slabs automove 1
# 4) check for a runaway writer creating oversized values
# 5) review your working set — maybe you're caching too much

低いヒット率

高い DB 負荷と共に低いヒット率(<90%)の通常の意味は、TTL が短すぎる、ワーキングセットがメモリを超える(evictions)、キーが再利用されていない(キー内のタイムスタンプのような揮発性コンポーネント)、コールドスタート、またはクライアントが ketama の設定について意見が割れキーが別のサーバーに着地することです。すべてのクライアントが同一のサーバーリストとハッシュを共有することを検証し、キー再利用のパターンをアプリのログで確認しましょう。

memcached
# symptom: hit rate < 90%, DB load high
#
# diagnosis:
stats
# STAT cmd_get 100000
# STAT get_hits 70000          <- 70% hit rate, too low
# STAT get_misses 30000

# common causes:
# 1) TTL too short -> items expire before reuse (raise TTL)
# 2) working set > cache memory -> evictions (see eviction storm)
# 3) keys not reused -> each request computes a unique key
#    (e.g. including a timestamp; remove volatile components)
# 4) cold start -> warmup period; preheat the cache
# 5) multiple client configs -> keys hashed to different servers
#    (verify all clients use the same ketama config)
# 6) cache invalidated too eagerly on writes (delete too broad)

# check TTL distribution vs access patterns in your app logs

Slab の石灰化

slab の石灰化とは、必要としないクラスにメモリが留まり、別のクラスが追い出しで撹拌されている状態です — ページが自力で移行できません。診断は stats slabs(free_chunks 対 total_pages)と stats items(クラスごとの evicted)で。修正は、slabs reassign(1 回)か slabs automove 1(背景)で、再発の予防は、値サイズの分布に合う -f の調整です。

memcached
# symptom: one slab class keeps evicting while another has free chunks
#
# diagnosis:
stats slabs
# STAT 1:total_pages 4    STAT 1:free_chunks 0      <- class 1 full
# STAT 5:total_pages 12   STAT 5:free_chunks 8000   <- class 5 idle
#
# stats items
# STAT items:1:evicted 99999   <- class 1 churning

# cause: over time, all pages got assigned to popular classes;
# memory is stuck and can't move to where it's needed.

# fixes:
# 1) one-shot: slabs reassign 5 1    # move a page class5 -> class1
# 2) auto:     slabs automove 1      # cautious background rebalance
# 3) restart with a better -f growth factor that matches your data
# 4) enable lru_crawler for smarter eviction

# verify after:
stats slabs

高いメモリ使用量

予想外のメモリ使用量の通常の原因は、内部断片化(値がチャンクに収まらない)、肥大化した値(圧縮されていない JSON)、膨大なキー数(アイテムごとのオーバーヘッド)です。診断は stats(limit_maxbytes 対 bytes)と stats slabs(total 対 used のチャンク)で。修正:大きな値の圧縮、空白とキー名のトリミング、無駄を減らす -f の調整、-m が実際に必要なワーキングセットと一致することの確認です。

memcached
# symptom: memcached using more memory than expected
#
# diagnosis:
stats
# STAT bytes 600000000          # actual item bytes
# STAT limit_maxbytes 671088640 # the -m cap
# STAT bytes_read / bytes_written help gauge traffic

stats slabs
# look at used_chunks vs total_chunks per class — internal
# fragmentation = (total_chunks * chunk_size) - bytes

# common causes:
# 1) internal fragmentation (values don't fit chunks well)
# 2) bloated values (cache full JSON with whitespace; compress!)
# 3) too many keys (key+metadata overhead per item)
# 4) memory leak in the client holding dead connections
# 5) -m is just set high and the working set filled it

# fix: compress large values, trim keys, tune -f, lower -m

遅いレスポンスとタイムアウト

遅いレスポンスの通常の原因は、1 スレッド上で逐次化するホットキー、サーバーを塞ぐ過大な multi-get、ネットワークを飽和させる巨大な値、アプリとキャッシュの間のネットワークレイテンシ、少なすぎる -t スレッドからの CPU 飽和、そして決定的に — Memcached のディスクへのスワップです(スワップさせてはいけません。物理 RAM 未満に -m を固定しましょう)。積極的なクライアントのタイムアウト(50〜100ms)を設定し、遅いキャッシュがリクエストを止めるのでなく、オリジンへ劣化するようにしましょう。

memcached
# symptom: get/set taking >10ms or timing out
#
# 1) a hot key serializing on one server thread (see hot keys)
# 2) huge multi-get blocking a server thread — chunk it
# 3) oversized values (multi-MB) saturating the network/parse
# 4) network latency between app and cache (co-locate them!)
# 5) server CPU saturated (-t too low for load)
# 6) swap! memcached must NEVER swap — check free -m; pin -m below RAM
#
# diagnose:
stats
# STAT curr_connections 4000   <- near -c? pool leak?
# STAT threads 4               <- raise -t?
# top -H -p <pid>              <- which thread is hot?

# on the client: set aggressive timeouts (e.g. 50-100ms) so a slow
# cache degrades gracefully to the origin instead of stalling
18

デプロイの設定

デーモンとしての実行

デーモンとして Memcached を実行するのが -d で、常に -u で非 root ユーザーへ権限を落としましょう。本番の不可欠なフラグは、-m(メモリ)、-l(bind アドレス — すべてのインターフェースのままにしないこと)、-c(接続の上限)、-t(スレッド)、-f(slab 成長係数)です。管理しやすいよう -P で pidfile を書き、netcat での素早いバージョン確認でプロセスを検証しましょう。

memcached
# start memcached as a background daemon (-d):
memcached -d -m 256 -p 11211 -u memcache -l 127.0.0.1 -c 2048

# common production flags:
#   -d              daemonize
#   -u memcache     drop privileges to this user
#   -m 256          256 MB item memory
#   -l 127.0.0.1    bind to loopback (or private NIC)
#   -c 2048         max connections
#   -t 8            8 worker threads
#   -f 1.25         slab growth factor
#   -I 1m           max item size
#   -v / -vv        log verbosity
#   -P /var/run/memcached.pid   write a pidfile

# check it's up:
echo "version" | nc -q 1 127.0.0.1 11211
# -> VERSION 1.6.24

Systemd サービス

systemd のユニットが与えるもの:自動再起動(Restart=on-failure)、権限の落下(User=memcache)、ファイルディスクリプタの制限(多くの接続のための LimitNOFILE)、セキュリティの強化(NoNewPrivileges、ProtectSystem、PrivateTmp)です。ほとんどのディストロが、ファイル全体を書き直すのでなく /etc/systemd/system/memcached.service.d/override.conf 経由で上書きできるデフォルトのユニットを ship します — 移植性のためこちらを推奨します。

memcached
# /etc/systemd/system/memcached.service
[Unit]
Description=Memcached
After=network.target

[Service]
Type=simple
User=memcache
Group=memcache
ExecStart=/usr/bin/memcached -m 256 -p 11211 -l 127.0.0.1 -c 2048 -t 8 -f 1.25
Restart=on-failure
RestartSec=2
LimitNOFILE=8192

# hardening
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/var/run

[Install]
WantedBy=multi-user.target

# enable and start:
#   systemctl daemon-reload
#   systemctl enable --now memcached
#   systemctl status memcached

Docker デプロイ

Docker では、2 つのメモリ上限があることを覚えましょう:memcached の -m(アイテムメモリ)と、コンテナのメモリ上限(docker -m)です。ランタイムと接続のための場所を残すため、コンテナの上限を memcached の -m より常に高く設定しましょう。さもないと OOM キラーが来ます。再現性のため、:latest ではなく特定のバージョンタグ(memcached:1.6)を固定し、耐性のため restart=unless-stopped を付けましょう。

memcached
# run memcached in Docker:
docker run -d \
  --name memcached \
  -p 11211:11211 \
  -m 512m \
  --restart=unless-stopped \
  memcached:1.6 \
  -m 256 -c 2048 -t 4 -f 1.25

# note: -m inside the container is memcached's item memory (256 MB);
#       the docker -m 512m limit caps the whole container (memcached +
#       overhead). Always set the docker limit HIGHER than memcached's -m.

# docker-compose snippet:
#   memcached:
#     image: memcached:1.6
#     command: -m 256 -c 2048 -t 4
#     ports:
#       - "11211:11211"
#     restart: unless-stopped

複数インスタンス

ホストごとの複数の Memcached インスタンスの実行で、ホットな slab クラスの隔離、プロセスごとの再起動の影響の縮小、より多くのコアの利用ができます — クライアントには、追加のリングのメンバーとして見えるだけです。コストは、より多くの接続とプロセスごとの slab ページのオーバーヘッドです。ほとんどのワークロードには、単一のマルチスレッドプロセス(-t を自分のコア数へ)がより単純で十分です。特定のボトルネックに当たったときだけ分割しましょう。

memcached
# run several memcached instances per host for isolation or to
# use more cores efficiently:
#
# instance A: port 11211, 4 GB
memcached -d -m 4096 -p 11211 -l 127.0.0.1 -t 4
# instance B: port 11212, 4 GB
memcached -d -m 4096 -p 11212 -l 127.0.0.1 -t 4

# the client treats them as two ring members (more shards).
# trade-offs:
#   + isolates a hot slab class to its own process
#   + smaller per-process working set = simpler restarts
#   - more connections to manage
#   - more memory overhead per process (slab pages don't share)

# alternative: one process with -t 8 threads (simpler, usually fine)

メモリのサイジング

測定したワーキングセットと余裕に -m をサイズし、ピークで 70〜80% の利用率を目指しましょう — スパイクのための場所があり、追い出しの撹拌が起きません。Memcached をスワップさせてはいけません — OS と他のプロセスを考慮した後の利用可能な RAM 未満に -m を保ちましょう。定常的な利用率が 90% を超えるなら、-m を上げるか、ワーキングセットを縮めましょう(より短い TTL、より少ないキャッシュ対象)。

memcached
# how big should -m be?
#
# 1) measure your working set: the keys actually hot in a typical hour
# 2) add headroom: target ~70-80% memory utilization at peak
# 3) leave RAM for the OS, connections, and slab overhead
#
# rule of thumb:
#   -m = working_set_bytes / 0.75
#
# example: 3 GB working set -> -m 4096 (4 GB) for 75% utilization
#
# never let memcached swap:
#   -m must be BELOW available RAM (check free -m)
#   account for other processes on the same host
#
# monitor utilization:
stats
# STAT bytes 3221225472          # 3 GB used
# STAT limit_maxbytes 4294967296 # 4 GB cap  -> 75% utilization

# if utilization > 90% steady: raise -m or shrink the working set

ロギングと Verbosity

Memcached は設計上静かです。デバッグのためだけに、-v/-vv/-vvv か実行時の verbosity コマンドで冗長さを上げましょう — すべてのコマンドのロギングがスループットを潰すためです。本番では、静かに実行し、可視性は stats と Prometheus エクスポーターに頼りましょう。ログは、systemd では journald、コンテナでは docker logs へ行きます。特定の問題の追跡のため -vv を短く使い、その後元へ戻しましょう。

memcached
# memcached is deliberately quiet; increase verbosity for debugging:
memcached -v        # log errors + warnings
memcached -vv       # also log each command (very noisy!)
memcached -vvv      # even more (connection-level detail)

# change at runtime without restart:
verbosity 2         # telnet in and raise the level
verbosity 0         # back to quiet

# with systemd, logs go to journald:
journalctl -u memcached -f

# with Docker:
docker logs -f memcached

# in production, run quiet (no -v) — verbose modes are only for
# debugging, as logging every command kills throughput.
# for access patterns, use stats + an exporter instead of -vv.
19

応用トピック

バイナリプロトコルの深掘り

バイナリプロトコルの固定 24 バイトヘッダーが、効率的なパース、SASL 認証、quiet(レスポンス抑制)のオペコードを可能にし、パイプライン化された一括操作がテキストプロトコルよりはるかに効率的になります。quiet のパイプラインの末尾の Noop がそれを流し、エラーを表面化させます。ほとんどの本番クライアントが、より低い操作ごとのオーバーヘッドと豊かな機能セットのため、デフォルトでバイナリプロトコルを好みます。

memcached
# the binary protocol uses a fixed 24-byte request header:
#
#  Magic (1)    0x80 request / 0x81 response
#  Opcode (1)   0x01 Get / 0x02 Set / 0x03 Add / ... / 0x05 Delete ...
#  Key length (2)
#  Extras length (1)
#  Data type (1)   usually 0
#  VBucket/reserved (2)
#  Total body length (4)   extras + key + value
#  Opaque (4)              client-supplied, echoed back
#  CAS (8)
#
# followed by: extras | key | value
#
# "quiet" opcodes (GetQ, SetQ, ...) skip responses except on error,
# enabling efficient pipelined bulk operations.
#
# a Noop at the end flushes the pipeline and confirms success.
# prefer the binary protocol in production clients for lower overhead.

UDP のサポート

Memcached が、高いスループットで接続レスな発火後放置のルックアップのため UDP をサポートします — TCP ハンドシェイクのコストが支配的な特殊なセットアップで有用です。損失がありサイズが制限されるため、冪等なキャッシュの読み取りにだけ使いましょう。決定的に重要なのは、UDP が既知の増幅 DDoS の経路であることです(CVE-2018-1000115)。具体的でファイアウォールされた必要性がない限り、本番では -U 0 で無効化しましょう。

memcached
# memcached can serve UDP (-U port, default 11211; -U 0 disables).
# UDP is for very high-throughput, fire-and-forget scenarios where
# a connection setup is too costly.
#
# each UDP datagram carries:
#   frame header (8 bytes): request ID, sequence, total datagrams
#   then the (possibly multi-datagram) command
#
# limits:
#   - responses may arrive out of order or be lost
#   - datagram size limits (~1400 bytes payload to avoid fragmentation)
#   - no guarantees — use only for cacheable, idempotent lookups
#
# SECURITY: UDP is a known amplification vector (CVE-2018-1000115).
# DISABLE it (-U 0) unless you have a specific, firewalled use case.

memcached -U 0    # recommended in production

大きなオブジェクトとチャンク化

-I で 1MB のアイテム上限を引き上げられますが、大きなアイテムがスループットと slab のバランスを損ないます。より良いパターンがアプリケーションレベルのチャンク化です:値を番号付きのキーの下で約 512KB の断片に分割し、カウントのキーを保存し、読み取り時に再構成します。これで、アイテムが slab に優しくなり、サーバーのスレッドの独占を避け、部分的な失敗が blob 全体の喪失ではなく回復可能になります。

memcached
# memcached's default max item size is 1 MB (-I).
# raising it (-I 4m) works but large items hurt: they're slow to
# transfer, monopolize server threads, and risk slab fragmentation.
#
# better: chunk large values yourself:
#
def set_large(key, value, ttl=3600):
    chunks = [value[i:i+512*1024] for i in range(0, len(value), 512*1024)]
    for idx, c in enumerate(chunks):
        mc.set(key + ":" + str(idx), c, ttl)
    mc.set(key + ":n", len(chunks), ttl)

def get_large(key):
    n = mc.get(key + ":n")
    if n is None: return None
    return b"".join(mc.get(key + ":" + str(i)) for i in range(n))

# trade-off: more keys/round-trips, but smaller items fit slabs
# better and a single chunk failure doesn't lose the whole value.

名前空間とバージョニング

Memcached には本物の名前空間がありません — キーの接頭辞で偽造し、論理的な名前空間全体を一度に無効化するには、バージョン化された接頭辞を使いましょう(nsver のキーを上げれば、古いキーが到達不能になり TTL で消えます)。アプリバージョンの接頭辞を含めれば、すべてのデプロイが新しいキャッシュを得ます。Memcached がキーを列挙したりパターン削除できないため、これが正統な一括無効化の方法です。

memcached
# memcached has no native namespaces — fake them with key prefixes.
#
# per-tenant isolation:
key = "tnt:" + tenant_id + ":user:" + user_id

# version the whole namespace to invalidate en masse:
ns_version = mc.get("nsver:user") or "1"
key = "user:" + ns_version + ":" + user_id
# to invalidate ALL user:* keys: incr "nsver:user" -> new version
# old keys become unreachable and expire via TTL

# or include a deploy version so each deploy starts fresh:
key = "v" + APP_VERSION + ":user:" + user_id

# time-bucketed namespaces for reports:
key = "report:" + today_date()   # auto-expires by date

# NEVER try "flush_all user:*" — memcached can't enumerate keys.
# versioned prefixes are the canonical bulk-invalidation trick.

キャッシュ殺到の予防

殺到が起きるのは、多くのリクエストが同じ期限切れのキーをミスし、すべてが再計算して、オリジンを叩くときです。正統な修正が add ベースのロックで、1 クライアントだけが再構築し、他は短く待って再試行します。同期された有効期限を防ぐため TTL のジッターと組み合わせ、ホットキーには積極的な更新(期限切れ前の更新、1 クライアントの再構築中に古いものを提供)を加えましょう — 1 つのミスさえ高くつくホットキーでは。

memcached
# a stampede: many requests miss the same expiring key, all
# recompute the same expensive value, overwhelming the origin.
#
# fix 1: lock-and-recompute (only ONE client rebuilds)
def get_with_lock(key, rebuild_fn, ttl=3600, lock_ttl=30):
    val = mc.get(key)
    if val is not None:
        return val
    # try to take a rebuild lock
    if mc.add("lock:" + key, "1", ttl=lock_ttl):
        try:
            val = rebuild_fn()           # only the winner recomputes
            mc.set(key, val, ttl)
            return val
        finally:
            mc.delete("lock:" + key)
    else:
        # another client is rebuilding; wait briefly and retry
        time.sleep(0.05)
        return get_with_lock(key, rebuild_fn, ttl, lock_ttl)

# fix 2: add jitter to TTLs so expirations don't synchronize
ttl = base_ttl + random.randint(-60, 60)

# fix 3: "dogpile" — serve a stale value while one client rebuilds
# (store value + a "refresh_at" timestamp; refresh proactively)

Was this helpful?