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). 키는 복사되지 않고 인라인으로 저장되므로 긴 키는 더 많은 메모리를 소비합니다. 장황한 설명형 이름 대신 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는 일시적이고 파생된 데이터 캐싱에 가장 적합합니다: DB 쿼리 결과, 세션, 렌더링된 페이지 조각, 레이트 리밋 카운터, 비싼 계산. 의도적으로 단순합니다. 영속성, 복제, 복잡한 데이터 타입이 없습니다. 휘발성 LRU 캐시로 취급하세요. 시스템 오브 레코드(system of record)에서 재구축할 수 없는 데이터는 절대 저장하지 마세요.

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는 fire-and-forget 쓰기에서 응답을 생략합니다(빠르지만 오류 보고가 없음).

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은 한 번의 왕복으로 하나 이상의 키를 조회합니다. 배칭(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)의 기반입니다. 여러 클라이언트가 같은 키를 수정할 때 lost update를 피하려면 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은 값을 가져오면서 TTL을 한 번의 왕복으로 원자적으로 갱신하며, 수명이 연장되어야 하는 세션 읽기에 이상적입니다. gats는 CAS 토큰도 반환합니다. 연산 사이에 값이 바뀌는 경쟁을 피하려면 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과 결합하면 안전한 카운터 패턴이 됩니다: add로 0에서 생성한 뒤 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 인자는 받아들이지만 무시됩니다. 값은 원래 메타데이터를 유지합니다. 읽기-수정-쓰기 없이 로그 줄이나 버퍼를 제자리에 쌓는 데 좋습니다. 주의: 결과 값도 여전히 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 — 기존 값 앞에 붙이기

prepend는 append의 거울상으로, 기존 값의 '앞'에 데이터를 연결합니다. append처럼 키가 존재해야 하며 flags/exptime을 무시합니다. 버퍼링된 값에 헤더/접두어를 쌓는 데 유용합니다. append와 prepend는 결과를 반환하지 않는다는 의미에서 클라이언트 간 원자적 읽기-수정-쓰기는 아니지만, 서버 측에서는 원자적 연산입니다.

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의 여섯 저장 명령(set, add, replace, append, prepend, cas)은 저장 전제 조건만 다릅니다. set은 무조건, add/replace는 존재 여부에 따라, append/prepend는 제자리 수정이며 메타데이터를 무시, cas는 gets의 CAS 토큰에 따릅니다. 올바른 명령을 고르면 읽기-수정-쓰기 경쟁이 단일 원자적 서버 연산으로 바뀝니다.

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는 cas_unique 토큰이 gets가 돌려준 것과 여전히 일치할 때만 값을 씁니다. STORED는 쓰기가 적용됨, EXISTS는 다른 클라이언트가 먼저 수정함(토큰 불일치), NOT_FOUND는 키가 삭제됨을 의미합니다. 낙관적 잠금입니다. EXISTS에서는 gets→수정→cas 루프 전체를 재시도하세요. 서버 측 잠금 없이 lost update를 피합니다.

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 사용 사례: 안전한 카운터

CAS는 읽기-수정-쓰기 의미가 필요할 때(예: 캐시 항목 안의 JSON 블롭 갱신) lost update 문제를 해결합니다. 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 루프는 세 가지 결과를 처리해야 합니다. 키 없음(add 사용, NOT_STORED면 재시도로 폴백), 토큰 일치(STORED, 완료), 토큰 불일치(EXISTS, 재시도). 경쟁 상황에서 라이브락을 피하려 재시도에 상한을 두세요. 키가 정말로 없다면 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는 단일 키 전용입니다. 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진 문자열인 키에 양의 정수를 원자적으로 더하고 새 값을 반환합니다. 동시 클라이언트 간에 완전히 원자적이며 lost update가 없습니다. 값은 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

카운터 사용 사례

카운터는 레이트 리밋(IP+분 키에 60s TTL), 조회/다운로드 통계, DAU 수, 재고, 롤아웃 지표에서 빛을 발합니다. 원자적이고 저렴해 매우 높은 쓰기 속도에도 확장됩니다. 레이트 리밋에서는 창에 맞는 키 세분화(사용자별, 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비트 정수만 가능합니다. 실수, 음수, 부호 불가. incr/decr은 절대 키를 자동 생성하지 않습니다. decr은 0에서 하한이 걸립니다. 값이 그저 문자열이므로 우연한 set/replace가 이를 덮어써 동시 증가를 망가뜨립니다. add로 초기화하고 이후에는 incr/decr만 사용하세요. 실수나 다중 필드 카운터는 구조화된 값에 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를 한 번의 왕복으로 원자적으로 결합합니다. 만료를 앞으로 미뤄야 하는 세션 읽기에 완벽합니다. gats는 CAS 토큰도 반환합니다. get과 touch를 따로 쓰면 TTL이 갱신되지 않는 창이 생기고 왕복도 두 배입니다. 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는 핵심 서버 지표를 보여 줍니다. cmd_get/cmd_set(총 연산), get_hits/get_misses(히트율 = hits/cmd_get), evictions(메모리 압박으로 버려진 항목), curr_items, bytes vs limit_maxbytes, 연결 수. 히트율과 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)를 보고합니다. number는 높은데 age가 낮은 slab은 계속 뒤집히는 중이고, age가 높은 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, 사용/여유 청크가 있습니다. 한 slab 클래스에 할당된 메모리는 그대로 있습니다. 다른 클래스로 돌려줄 수 없습니다. 한 클래스가 가득 차 쫓아내는 동안 다른 클래스가 비어 있으면 slab 석회화(slab calcification)이며, -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)를 0으로 만듭니다. 배포 후 새 구간을 측정할 때 유용합니다. 기타 유용한 하위 명령: 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), eviction과 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 또는 사설 네트워크에 바인딩. Memcached를 공개 노출하지 마세요), -c(연결 상한), -I(최대 항목 크기), -f(slab 성장 인자). -M은 eviction 동작을 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이 대표 설정입니다. 워킹 셋 + 여유분으로 크기를 잡으세요. 부족하면 eviction과 캐시 churn이 생깁니다. -f는 slab 클래스 세분도와 내부 단편화의 절충입니다. 크기가 좁은 항목이 많으면 1.1 쪽으로 낮추세요. -I는 항목 크기 상한이며 큰 블롭을 캐시해야 할 때만 올리세요. -M은 캐시에서는 거의 안 쓰입니다. OOM을 eviction 대신 오류로 만듭니다.

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 확인). -t는 워커 스레드이며 Memcached는 스레드별 이벤트 구동이므로 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를 내장하지 않으므로 보통 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가 캐시에 뒤처짐)과 내구성(워커가 처리하기 전 크래시 시 데이터 유실)입니다. Memcached만으로는 불가능하며 큐 + 워커가 필요합니다. 카운터, 텔레메트리처럼 쓰기 많고 유실을 견딜 수 있는 워크로드에만 사용하세요.

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이 안전망입니다(항상 설정). 열거할 수 없는 컬렉션에는 버전화된 키(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과 Eviction 전략

TTL을 데이터 휘발성에 맞추세요. 참조 데이터는 몇 시간, 사용자 데이터는 몇 분, 레이트 리밋 카운터는 창 길이. 동기화된 만료 스탬피드를 피하려 항상 지터(±5~10%)를 더하세요. Memcached는 메모리 압박 시 slab별 LRU로 쫓아내며 항목별 고정(pinning)이 없습니다. 레버는 TTL과 전체 크기뿐입니다. 핫 키에는 add 기반 락을 써서 미스 시 한 클라이언트만 재계산하게 하세요.

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이 기본이고 get_many가 multi-get을 배칭합니다. 카운터는 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로 감싸거나 util.promisify로 async/await 인체공학을 챙기세요.

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()가 낙관적 동시성을 제공하고 getBulk()가 배칭 multi-get을 합니다. 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는 이름을 키로 하는 맵을 반환합니다(없는 키는 오류가 아니라 부재). 동시성 안전이므로 고루틴 전반에서 클라이언트 하나를 재사용하세요.

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

클라이언트 측 샤딩

모든 샤딩은 클라이언트에 있습니다. 각 키를 해싱해 한 서버로 보내고 multi-get은 서버들에 병렬로 팬아웃합니다. 각 키는 정확히 한 노드에만 존재합니다. 복제가 없으므로 죽은 노드는 키스페이스의 해당 조각을 잃습니다. 프록시나 코디네이터가 없으므로 모든 클라이언트가 같은 서버 목록과 해싱 설정(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 같은 프록시 운영, 또는 손실을 받아들이고 원본에서 재구축 중 하나입니다. 관용적 선택은 마지막입니다. 캐시를 일회용으로 취급하고, 한 노드의 손실을 견딜 수 있게 풀 크기를 잡고, 미스는 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

메모리 관리 (Slabs / 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바이트)에서 시작해 -f 인자(기본 1.25)로 커지며 -I 최대 항목 크기까지 올라갑니다. -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 Eviction

Eviction은 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은 정책을 eviction 대신 가득 찼을 때 오류로 바꿉니다(캐시에서는 거의 바람직하지 않음). cache_memlimit가 상한을 라이브로 조정합니다. -m은 여유분을 포함한 워킹 셋에 맞추세요. 100%로 돌면 끊임없는 eviction과 낮은 히트율의 뒤집히는 캐시를 의미합니다.

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

Eviction 정책과 튜닝

Memcached의 유일한 eviction 정책은 slab별 LRU입니다. LFU나 랜덤 옵션은 없습니다. eviction을 줄이려면: -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+, 자동)는 여유 청크가 있는 클래스에서 eviction 압박을 받는 클래스로 slab 페이지를 재조정합니다. slab 석회화의 처방입니다. 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는 쓰기당 응답을 끊고, 파이프라이닝은 많은 명령을 한 번의 네트워크 왕복에 모읍니다. 이 둘이 대량 쓰기 처리량의 가장 큰 레버입니다. 읽기에는 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 vs curr_connections를 보세요. curr은 평평한데 total이 트래픽과 함께 늘면 풀링 중이고, 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은 한 번의 왕복으로 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 이상은 압축(flags 비트로 표시), 블롭 전체가 아니라 프로젝션을 캐시. 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)

핫 키 피하기

핫 키는 단일 서버 단일 스레드 병목입니다. 읽기가 한 노드에서 직렬화되는 동안 다른 노드는 놉니다. 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

모니터링

주시할 핵심 통계

대표 지표 네 가지는 히트율(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입니다. stats는 slab별 표, display는 실시간 갱신 뷰, dump는 키 엿보기(디버그 전용. LRU를 순회함)입니다. SSH 일회성 작업에는 완벽하지만 지속 모니터링용은 아닙니다. 프로덕션 대시보드와 알림에는 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 원라이너를 쓰세요(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 통합입니다. 노드마다 하나를 옆에 실행하고 :9150을 스크레이프하세요. Grafana 대시보드가 히트율, eviction 비율, 메모리 사용량, 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 상승 + 원본 지연 상승은 캐시가 작다는 신호입니다. 조용한 재시작을 잡기 위해 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에 바인딩하고, 미사용 시 -U 0으로 UDP를 끄고, 11211은 앱 서브넷만 방화벽으로 허용하세요. 공개적으로 도달 가능한 Memcached는 열린 데이터 캐시이자 UDP 증폭 DDoS 벡터입니다(CVE-2018-1000115). 기본 리슨 주소는 모든 인터페이스이므로 항상 재정의하세요.

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 자격증명을 사용하며 왕복이 하나 더해지지만 풀링이 이를 상쇄합니다. 네트워크 격리만으로 부족한 공유 또는 멀티테넌트 네트워크에서 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에 바인딩, 앱 서브넷만 방화벽 허용, UDP 비활성화, 공유 네트워크에서 SASL 추가, 비루트 사용자로 실행, systemd 강화(NoNewPrivileges, ProtectSystem, PrivateTmp). 무엇보다 원시 비밀을 Memcached에 저장하지 마세요. 캐시는 금고가 아닙니다. 암호화 후 캐시하거나 비밀은 전용 시크릿 매니저에 두고 민감하지 않은 참조만 캐시하세요.

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를 절대 공개 노출하지 않기, 항상 사설 인터페이스에 바인딩, 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 vs 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에는 영속성이 전혀 없습니다. 재시작하면 설계대로 비어 있으며 캐시는 항상 일회용입니다. Redis는 RDB 스냅샷과 AOF 내구성, 복제를 제공하므로 주 데이터 저장소가 될 수 있습니다. 캐시가 재시작을 견디거나 권위 있는 데이터를 담아야 하면 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는 마스터/레플리카 복제, 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.

메모리 효율

Memcached의 slab 할당자는 불투명 블롭에 가볍지만 청크 올림으로 공간을 낭비합니다. Redis는 키/필드별 오버헤드가 있지만 작은 구조에 압축 인코딩(listpack)을 고릅니다. 어느 쪽이 항상 더 작지는 않습니다. 균일한 블롭에는 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

문제 해결

연결 거부

연결 거부는 보통 서버가 실행 중이 아니거나, 예상 주소에서 리슨하지 않거나(루프백 바인딩 -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

Eviction 폭풍

가득 찬 캐시에서 evictions가 오르면 워킹 셋이 -m을 초과한다는 뜻입니다. stats(bytes == limit_maxbytes)와 stats items(어느 slab 클래스가 쫓아내는지)로 진단하세요. 처방: -m 상향, 항목이 스스로 만료되게 TTL 단축, slabs reassign/automove로 slab 페이지 재조정, 값을 부풀리는 무분별한 쓰기 찾기. 지속적으로 가득 찬 캐시는 메모리 추가 또는 워킹 셋 축소가 필요합니다.

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 석회화는 메모리가 필요 없는 클래스에 갇힌 채 다른 클래스는 eviction으로 뒤집히는 상태입니다. 페이지는 스스로 이동하지 못합니다. stats slabs(free_chunks vs total_pages)와 stats items(클래스별 evicted)로 진단하고, slabs reassign(일회성)이나 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(bytes vs limit_maxbytes)와 stats slabs(사용 vs 전체 청크)로 진단하세요. 처방: 큰 값 압축, 공백과 키 이름 다듬기, 낭비를 줄이는 -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

느린 응답과 타임아웃

느린 응답은 보통 한 스레드에서 직렬화되는 핫 키, 서버를 막는 과대 multi-get, 네트워크를 포화시키는 거대 값, 앱-캐시 네트워크 지연, -t 스레드 부족으로 인한 CPU 포화, 또는 무엇보다 Memcached가 디스크로 스왑하는 것에서 옵니다(스왑을 절대 허용하지 마세요. -m을 물리 RAM 아래로 고정). 공격적인 클라이언트 타임아웃(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

배포 설정

데몬으로 실행

-d로 Memcached를 데몬으로 실행하되 항상 -u로 비루트 사용자에게 권한을 내려놓으세요. 핵심 프로덕션 플래그: -m(메모리), -l(바인딩 주소. 절대 모든 인터페이스로 두지 마세요), -c(연결 상한), -t(스레드), -f(slab 성장 인자). 관리 편의를 위해 -P로 pidfile을 작성하고, netcat으로 간단한 version 확인으로 프로세스를 검증하세요.

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로 재정의하는 편이 이식성에 좋습니다.

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에서는 메모리 한도가 두 개라는 점을 기억하세요. memcached의 -m(항목 메모리)과 컨테이너 메모리 상한(docker -m). OOM 킬러를 피하려면 런타임과 연결을 위한 여유를 두고 항상 컨테이너 상한을 memcached의 -m보다 높게 설정하세요. 재현성을 위해 :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%를 겨냥하세요. 스파이크 여유를 두고 eviction churn을 피하기 위함입니다. 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 오크코드는 파이프라인 대량 연산을 텍스트 프로토콜보다 훨씬 효율적으로 만듭니다. 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는 고처리량, 비연결, fire-and-forget 조회를 위한 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 친화적으로 유지되고, 서버 스레드를 독점하지 않으며, 부분 실패가 블롭 전체 손실이 아니라 복구 가능해집니다.

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 기반 락으로 한 클라이언트만 재구축하고 나머지는 잠시 기다렸다 재시도하는 것입니다. TTL 지터를 결합해 동기화된 만료를 막고, 핫 키에는 사전 갱신(만료 전 갱신, 한 클라이언트가 재구축하는 동안 오래된 데이터 제공)을 더하세요. 미스 하나조차 비싼 키에는 필수입니다.

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?