Skip to content

Redis CLI 치트시트

인메모리 데이터 구조 저장소 - CLI 명령과 사용법.

01

시작하기

Redis 서버에 연결

redis-cli는 표준 명령줄 클라이언트입니다. 기본값은 127.0.0.1:6379에 연결합니다. 호스트는 -h, 포트는 -p, 비밀번호는 -a로 지정합니다(또는 REDISCLI_AUTH 환경 변수를 설정해 셸 히스토리에 비밀번호가 남지 않게 하세요). TLS를 쓰려면 --tls와 인증서/키가 필요합니다. Redis 6 이상에서는 redis:// URL 스킴을 지원하고, TLS에는 rediss://를 사용합니다.

redis-cli
# connect to local server (default port 6379)
redis-cli

# connect to a remote host with custom port
redis-cli -h redis.example.com -p 6380

# connect with authentication
redis-cli -a "yourpassword"
redis-cli -h host -p 6379 -a "yourpassword"

# connect over TLS
redis-cli --tls --cert client.crt --key client.key -h host -p 6379

# connect using a URL (Redis 6+)
redis-cli redis://user:password@host:6379/0
redis-cli rediss://user:password@host:6379/0  # TLS

연결 옵션과 모드

redis-cli는 대화형 모드와 단발(one-shot) 모드를 모두 지원합니다. 명령을 인자로 넘기면 실행 후 종료합니다. 파이프 모드는 stdin에서 RESP/텍스트 명령을 읽으므로 스크립팅과 대량 적재에 좋습니다. -n은 논리 데이터베이스를 선택합니다. --stat와 --latency는 내장 모니터링 도우미입니다. --raw는 타입 접두사 없이 값을 출력해 파이프 처리에 유용합니다.

redis-cli
# select a specific database index (0-15)
redis-cli -n 1            # use database 1

# run a single command and exit (non-interactive)
redis-cli GET mykey
redis-cli -h host PING

# pass command with arguments
redis-cli SET counter 100
redis-cli INCR counter

# read commands from stdin (pipe mode)
echo "SET k1 v1" | redis-cli
cat commands.txt | redis-cli

# repeat a command every second (watch mode)
redis-cli --stat
redis-cli --latency

# pretty-print JSON output (Redis 6+)
redis-cli --raw GET user:json

PING과 연결 테스트

PING은 가장 간단한 상태 확인 방법입니다. 정상 동작하는 Redis는 PONG을 반환합니다. --latency는 왕복 시간을 계속 측정하며(네트워크 문제 진단에 유용), --latency-dist는 히스토그램을, --latency-history는 롤링 통계를 보여줍니다. 성능 튜닝 전에 이 명령들로 연결 품질의 기준선을 잡아 두세요.

redis-cli
# basic connectivity test
redis-cli ping
# PONG

# ping with a message (echoed back)
redis-cli PING "hello"
# "hello"

# test auth + connection in one shot
redis-cli -a password PING

# check round-trip latency (continuous)
redis-cli --latency
# output: min: 0, max: 1, avg: 0.27 (3421 samples)

# latency histogram
redis-cli --latency-dist

# latency history (rolling, every 15s by default)
redis-cli --latency-history -i 1

대화형 모드 팁

대화형 모드는 Redis 명령을 위한 REPL입니다. HELP <command>나 HELP @<group>은 내장 문서를 보여줍니다(인터넷 불필요). CONNECT는 세션 중 서버를 전환하고, CLEAR는 화면을 지웁니다. CLI는 따옴표로 묶인 문자열의 여러 줄 입력을 자동 감지합니다. 콜론(:)을 붙이면 :raw 같은 CLI 전용 명령을 실행합니다.

redis-cli
# start interactive mode
redis-cli

# inside the CLI:
127.0.0.1:6379> HELP SET       # command help
127.0.0.1:6379> HELP @string   # help for a command group
127.0.0.1:6379> SCAN 0         # any Redis command

# clear the screen
127.0.0.1:6379> CLEAR

# connect to a different server without restarting
127.0.0.1:6379> CONNECT host 6380

# exit
127.0.0.1:6379> EXIT
127.0.0.1:6379> QUIT

# multi-line input: end with a backslash
127.0.0.1:6379> SET mykey "this is \
a multi-line value"

# toggle raw output mode
127.0.0.1:6379> :raw

데이터베이스 선택과 기초

Redis 데이터베이스는 같은 메모리를 공유하는 논리적 네임스페이스(0-15)이며, 격리된 스키마가 아닙니다. 대부분의 앱은 db 0만 사용합니다. FLUSHDB는 현재 db를, FLUSHALL은 모든 데이터를 지웁니다(주의!). 여러 db는 단일 스레드를 공유하므로 권장되지 않으며, 인스턴스를 분리하거나 키 접두사를 쓰는 편이 좋습니다.

redis-cli
# Redis has 16 logical databases (0-15) by default
SELECT 0     # switch to database 0
SELECT 15    # switch to database 15

# move a key to another database
MOVE mykey 1

# flush the current database (DESTRUCTIVE)
FLUSHDB

# flush ALL databases (VERY DESTRUCTIVE)
FLUSHALL

# get the number of keys in the current db
DBSIZE

# swap two databases (Redis 4.0+)
SWAPDB 0 1

도움말과 명령 탐색

COMMAND는 서버의 명령 테이블을 조회해 지원 기능과 인자 수(arity)를 파악하는 데 유용합니다. COMMAND DOCS(7.0+)는 구조화된 문서를 반환합니다. CLI의 HELP는 카테고리(@string, @hash, @server 등)별로 오프라인 문서를 보여줍니다. 모든 CLI 플래그와 옵션은 'redis-cli --help'로 확인하세요.

redis-cli
# list all commands (huge output)
COMMAND

# get details of a specific command
COMMAND INFO GET
COMMAND INFO SET HSET LPUSH

# structured documentation (Redis 7+)
COMMAND DOCS SET
COMMAND DOCS @string

# count available commands
COMMAND COUNT

# CLI help
redis-cli --help
redis-cli --version

# inside interactive mode
HELP
HELP @server
HELP @string
HELP @hash
HELP GETSET
02

문자열

기본 SET과 GET

SET/GET은 가장 기본적인 문자열 연산입니다. NX는 키가 없을 때만 설정(락 구현에 사용), XX는 키가 있을 때만 설정합니다. EX/PX/EXAT/PXAT는 만료를 원자적으로 설정하므로 SET과 EXPIRE 사이의 경쟁 조건이 없습니다. GETSET은 새 값을 설정하면서 이전 값을 반환합니다. 문자열은 최대 512MB까지 바이너리 안전합니다.

redis-cli
# set and get a key
SET mykey "Hello"
GET mykey               # "Hello"

# set only if not exists (NX) or only if exists (XX)
SET mykey "new" NX      # set only if key does NOT exist
SET mykey "new" XX      # set only if key DOES exist

# set with expiration (seconds / milliseconds)
SET token "abc" EX 3600    # expires in 3600s
SET token "abc" PX 60000   # expires in 60000ms

# set with expiration at a Unix timestamp
SET token "abc" EXAT 1700000000

# get and set atomically (returns old value)
GETSET counter 0        # returns old value, sets new

# delete a key
DEL mykey

숫자 카운터(INCR/DECR)

INCR/DECR는 원자적이므로 락 없이도 동시 접근에 안전합니다. 그래서 Redis는 카운터, 속도 제한(INCR + EXPIRE), 시퀀스 ID 생성에 적합합니다. INCRBYFLOAT은 소수를 지원하지만 배정밀도를 쓰므로 반올림에 주의하세요. 값이 정수가 아니면 INCR은 오류를 반환합니다.

redis-cli
# increment a numeric string atomically
SET counter 100
INCR counter            # 101
INCRBY counter 10       # 111

# decrement
DECR counter            # 110
DECRBY counter 5        # 105

# floating point increment
SET price "10.50"
INCRBYFLOAT price 0.25  # "10.75"
INCRBYFLOAT price -1.00 # "9.75"

# all increment ops are atomic and concurrency-safe
# use for: counters, rate limiting, sequence IDs, stats

# INCR on a non-integer value returns an error
SET mystr "hello"
INCR mystr              # ERROR: value is not an integer

APPEND와 문자열 연산

APPEND는 문자열을 확장하고(없으면 생성), STRLEN은 길이를 반환합니다. GETRANGE/SETRANGE는 바이너리 안전하게 부분 문자열을 다룹니다. GETDEL(6.2+)은 값을 반환하면서 원자적으로 삭제하므로 일회성 읽기 패턴에 유용합니다. GETEX는 값을 반환하면서 TTL을 설정하므로 읽을 때 세션 만료를 갱신하기 좋습니다.

redis-cli
# append to a string value
SET msg "Hello"
APPEND msg " World"     # "Hello World"

# get string length
STRLEN msg              # 11

# get substring
GETRANGE msg 0 4        # "Hello"
GETRANGE msg 6 -1       # "World"

# overwrite a substring (grows if needed)
SETRANGE msg 6 "Redis"  # "Hello Redis"

# get and delete atomically
GETDEL mykey            # returns value AND deletes key
# get and set expiration atomically (6.2+)
GETEX mykey EX 3600     # returns value, sets TTL

# append only if key exists
APPEND existing_key "more"

MSET과 MGET(배치 연산)

MSET/MGET은 여러 연산을 한 번의 왕복으로 묶으므로 성능에 필수입니다(Redis는 단일 스레드라 명령별 오버헤드가 중요합니다). MSETNX는 원자적이어서 모든 키가 설정되거나 하나도 설정되지 않습니다. 작은 키-값 쌍이 많다면 해시(HSET)로 묶어 listpack 인코딩의 메모리 효율을 활용하세요.

redis-cli
# set multiple keys at once (atomic)
MSET k1 "v1" k2 "v2" k3 "v3"

# get multiple keys at once
MGET k1 k2 k3           # 1) "v1" 2) "v2" 3) "v3"

# set multiple only if ALL keys are new
MSETNX k1 "v1" k4 "v4"  # 1 if all set, 0 if any existed

# MSET/MGET reduce round-trips — much faster than
# separate SET/GET calls in a loop

# get the length of a string value
STRLEN k1               # 2

# set multiple fields of different keys is not possible;
# for per-field updates use hashes (HSET)

# pipeline alternative in CLI:
printf '%s\n' "SET k1 v1" "SET k2 v2" "GET k1" | redis-cli --pipe-mode

비트맵(문자열 기반)

비트맵은 약 512MB로 최대 40억 사용자의 불리언 플래그를 저장할 수 있어 공간 효율이 매우 뛰어납니다. BITOP AND/OR/XOR/NOT은 비트맵을 결합합니다(예: 여러 날 활동한 사용자). BITCOUNT는 활성 사용자 수를 세고, BITFIELD는 여러 작은 카운터를 하나의 문자열에 패킹합니다. 위치가 곧 사용자 ID입니다. 활용 예: 일일 활성 사용자, 기능 플래그.

redis-cli
# bitmaps are strings operated on at the bit level
# great for boolean flags on a large user base

# set bit at position (0 or 1)
SETBIT user:1:active 7 1    # user 1 active
GETBIT user:1:active 7      # 1

# count set bits
BITCOUNT user:1:active      # total bits set to 1

# bitwise operations between strings
SETBIT users:d1 5 1
SETBIT users:d2 5 1
BITOP AND active-both users:d1 users:d2
BITCOUNT active-both        # users active on both days

BITOP OR  active-either users:d1 users:d2
BITOP XOR diff         users:d1 users:d2

# find the first set bit
BITPOS user:1:active 1      # position of first 1-bit

# bitfield: multiple counters in one string
BITFIELD mycnt SET u8 0 100
BITFIELD mycnt INCRBY u8 0 10

문자열 만료와 TTL

TTL은 없는 키에 -2, 만료가 없는 키에 -1을 반환합니다. EX를 붙인 SET은 원자적이라 SET과 EXPIRE 사이의 경쟁 조건이 없습니다. KEEPTTL(6.0+)은 TTL을 유지한 채 값을 갱신하므로 만료 시간을 초기화하지 않고 캐시 값을 새로 고칠 때 유용합니다. 만료는 접근 시 확인하는 지연 방식과 주기적 백그라운드 스윕을 함께 사용합니다.

redis-cli
# set a key with expiration in one atomic command
SET session "data" EX 3600    # 1 hour
SET cache "value" PX 60000    # 60 seconds (ms)

# set expiration on an existing key
EXPIRE mykey 60               # 60 seconds
PEXPIRE mykey 60000           # 60 seconds (ms)
EXPIREAT mykey 1700000000     # Unix timestamp

# view remaining time to live
TTL mykey          # seconds (-1 = no expiry, -2 = no key)
PTTL mykey         # milliseconds

# remove expiration (make key persistent)
PERSIST mykey

# TTL with KEEPTTL option (6.0+): set value, keep existing TTL
SET mykey "newval" KEEPTTL
03

리스트

푸시와 팝 연산

리스트는 양방향입니다. LPUSH+RPOP은 큐(FIFO), LPUSH+LPOP은 스택(LIFO)입니다. BLPOP/BRPOP은 항목이 생길 때까지 블록하므로 폴링 없이 Redis 큐를 만들 수 있는 기반입니다. BLPOP에는 반드시 타임아웃을 설정해 연결 끊김에 대비하세요. 리스트는 양 끝 연산이 O(1)이고 중간 접근은 O(N)입니다.

redis-cli
# lists are ordered sequences of strings (linked lists)
LPUSH mylist "a" "b"      # list: [b, a]
RPUSH mylist "c"          # list: [b, a, c]

# pop from head or tail
LPOP mylist               # "b" (removes from head)
RPOP mylist               # "c" (removes from tail)

# pop multiple (6.2+)
LPOP mylist 2             # pop 2 from head

# get length
LLEN mylist               # 0

# blocking pop (waits if empty, up to timeout)
BLPOP queue:tasks 30      # blocks up to 30 seconds
BRPOP queue:tasks 0       # blocks forever

# push only if the list exists (don't create new key)
LPUSHX mylist "x"         # 0 if key doesn't exist

LRANGE와 인덱싱

LRANGE 0 -1은 리스트 전체를 반환합니다. LINDEX는 중간 요소에 O(N)이 걸립니다. 리스트는 끝부분 접근에 최적화되어 있기 때문입니다. LSET은 인덱스로 값을 수정하고, LINSERT는 O(N)이므로 큰 리스트에서는 신중히 사용하세요. LPOS는 요소를 제거하지 않고 위치를 찾습니다. 인덱스로 자주 무작위 접근해야 한다면 리스트는 잘못된 선택이며 정렬된 집합을 고려하세요.

redis-cli
# get a range of elements (0-based, negative from end)
LRANGE mylist 0 -1        # all elements
LRANGE mylist 0 2         # first 3 elements
LRANGE mylist -3 -1       # last 3 elements

# get element by index (O(N) traversal)
LINDEX mylist 0           # first element
LINDEX mylist -1          # last element

# set an element by index
LSET mylist 1 "newval"

# get length
LLEN mylist

# insert before or after a pivot element
LINSERT mylist BEFORE "pivot" "new"
LINSERT mylist AFTER "pivot" "new"

# find the position of an element (6.0+)
LPOS mylist "value"
LPOS mylist "value" RANK 2   # find 2nd occurrence

블로킹 팝과 큐

BRPOPLPUSH/BLMOVE는 항목을 원본에서 대상으로 원자적으로 이동합니다. 소비자는 안전하게 처리할 수 있고, 처리 중 크래시가 나도 항목은 대상 리스트에 남습니다(신뢰성 있는 큐 패턴). BRPOP 후 처리하다 크래시가 나면 항목을 잃는 방식보다 낫습니다. 처리 후에는 대상 리스트에서 삭제하세요.

redis-cli
# simple FIFO queue: LPUSH to add, RPOP to consume
LPUSH tasks "job1" "job2"
RPOP tasks                # "job1" (FIFO order)

# reliable queue with BRPOP (blocking, waits for work)
BRPOP tasks 0             # blocks until a task is available

# move items between lists atomically
RPOPLPUSH source destination  # move one item

# blocking move (reliable queue pattern)
BRPOPLPUSH source destination 30  # blocks up to 30s

# Redis 6.2+: BLMOVE replaces BRPOPLPUSH
BLMOVE source destination RIGHT LEFT 30

# capped queue (e.g., recent events)
LPUSH recent "event"
LTRIM recent 0 99         # keep latest 100

LREM, LSET, LTRIM

LTRIM은 리스트 크기를 제한하는 흔한 패턴입니다(예: 최근 100개 이벤트만 유지). LREM은 값으로 제거합니다(count가 양수면 앞에서, 음수면 뒤에서, 0이면 전체). LMPOP(7.0+)은 여러 리스트에서 한 번에 팝하므로 우선순위 큐에 유용합니다. 리스트 중간에서 자주 연산해야 한다면 리스트는 적합하지 않습니다.

redis-cli
# trim to a range (removes everything outside)
LTRIM mylist 0 99         # keep only first 100 elements
LTRIM mylist -50 -1       # keep only last 50

# remove elements by value
LREM mylist 2 "value"     # remove first 2 occurrences of "value"
LREM mylist -2 "value"    # remove last 2 occurrences
LREM mylist 0 "value"     # remove ALL occurrences

# pop and push in one atomic operation
RPOPLPUSH source dest

# pop from multiple lists (7.0+)
LMPOP 2 mylist1 mylist2 LEFT COUNT 3

# blocking pop from multiple lists (7.0+)
BLMPOP 30 2 mylist1 mylist2 LEFT COUNT 3

# remove a key only if it's a list (type-safe)
DEL mylist                # works on any type

리스트 활용 사례

리스트는 끝부분 접근 패턴이 있는 시퀀스에 가장 적합합니다: 큐, 스택, 피드, 버퍼. LTRIM을 쓰면 크기가 제한된 로그/피드에 이상적입니다. 속도 제한에는 타임스탬프 리스트와 LTRIM으로 간단한 슬라이딩 윈도우를 만들 수 있습니다. 정렬/우선순위 큐가 필요하면 정렬된 집합을 사용하세요. 리스트는 중복 제거를 지원하지 않으므로 그 용도에는 집합을 쓰세요.

redis-cli
# 1. Task queue (FIFO)
LPUSH tasks "process_order:123"
BRPOP tasks 30

# 2. Recent activity feed (capped)
LPUSH user:1:feed "post:99" "post:98"
LTRIM user:1:feed 0 49     # latest 50

# 3. Stack (LIFO)
LPUSH stack "item"
LPOP stack

# 4. Circular buffer (limited size)
LPUSH buffer "new"
LTRIM buffer 0 999         # keep 1000 items

# 5. Rate limiter (sliding window)
LPUSH rate:user:1 1700000000
LTRIM rate:user:1 0 99
LLEN rate:user:1           # request count in window

# 6. Chat history (capped)
LPUSH chat:room:1 "alice: hello"
LTRIM chat:room:1 0 999    # keep last 1000 messages
04

집합

SADD, SMEMBERS, SISMEMBER

집합은 고유 값을 저장하므로 태그, 카테고리, 중복 제거에 완벽합니다. SISMEMBER는 O(1)이라 리스트 확인보다 훨씬 빠릅니다. SMEMBERS는 큰 집합에서 서버를 막을 수 있으므로 반복에는 SSCAN을 사용하세요. SMISMEMBER(7.4+)는 여러 멤버를 한 번에 확인해 왕복을 줄입니다. 모든 멤버가 정수이면 intset(정렬 배열)을 사용해 메모리 효율이 매우 높습니다.

redis-cli
# sets: unordered collection of unique strings
SADD tags "redis" "db" "cache"
SADD tags "redis"          # ignored (already exists)

# check membership (O(1))
SISMEMBER tags "redis"     # 1 if member, 0 if not

# get all members (avoid on large sets)
SMEMBERS tags              # 1) "redis" 2) "db" 3) "cache"

# get the number of members
SCARD tags                 # 3

# remove a member
SREM tags "cache"          # 1

# check multiple memberships at once (7.4+)
SMISMEMBER tags "redis" "db" "missing"
# 1) 1  2) 1  3) 0

집합 연산(합집합/교집합/차집합)

집합 연산은 Redis의 강력한 기능입니다. 합집합, 교집합, 차집합을 클라이언트 처리 없이 O(N)에 수행합니다. 활용 예: 상호 친구(SINTER), 순 방문자(SUNION), 태그 기반 필터링(태그 집합의 SINTER). SINTERCARD(7.0+)는 개수만 반환하므로 멤버가 필요 없을 때 더 빠릅니다. 결과를 저장해 재계산을 피하세요.

redis-cli
# set union, intersection, difference
SADD set1 "a" "b" "c"
SADD set2 "b" "c" "d"

# union (all unique members from all sets)
SUNION set1 set2           # a, b, c, d

# intersection (members in ALL sets)
SINTER set1 set2           # b, c

# difference (members in set1 but NOT in set2)
SDIFF set1 set2            # a

# store the result in a new set
SUNIONSTORE result set1 set2
SINTERSTORE result set1 set2
SDIFFSTORE result set1 set2

# count intersection without returning members (7.0+)
SINTERCARD 2 set1 set2 LIMIT 0

# operations on multiple sets at once
SUNION s1 s2 s3 s4

SREM, SMOVE, SPOP

SMOVE는 원자적이므로 상태 전이에 유용합니다(예: 사용자를 'pending'에서 'active' 집합으로 이동). SPOP은 무작위 멤버를 제거합니다(추첨/샤딩에 유용). SRANDMEMBER는 제거하지 않습니다. BSPOP(7.0+)은 집합용 BLPOP처럼 블록하며, 순서가 중요하지 않은 이벤트 기반 패턴에 유용합니다. SREM은 실제로 제거된 개수를 반환합니다.

redis-cli
# remove one or more members
SADD myset "a" "b" "c" "d"
SREM myset "a" "b"         # 2 (number removed)

# move a member from one set to another atomically
SMOVE source dest "member"

# pop a random member (removes it)
SPOP myset                 # removes and returns one
SPOP myset 3               # removes and returns 3 (6.2+)

# get a random member (does NOT remove)
SRANDMEMBER myset          # one random member
SRANDMEMBER myset 3        # 3 random (may repeat)
SRANDMEMBER myset -3       # 3 unique random

# blocking set pop (7.0+) - waits until a member exists
BSPOP myset 30             # blocks up to 30 seconds

# delete the entire set
DEL myset

SSCAN 반복

SSCAN은 큰 집합을 안전하게 반복하는 방법입니다. SMEMBERS는 거대한 집합에서 서버를 막습니다. SSCAN은 커서 기반이라 커서가 0으로 돌아올 때까지 반복 호출합니다. COUNT는 힌트일 뿐이라 더 많거나 적게 반환될 수 있습니다. SSCAN은 약한 보장을 제공합니다. 반복 중 추가된 멤버를 놓치거나 중복을 반환할 수 있지만 절대 블록하지 않습니다. 코드에서 항상 커서 루프를 처리하세요.

redis-cli
# SSCAN: cursor-based iteration for large sets
SSCAN myset 0 MATCH "pre*" COUNT 100
# returns: [nextCursor, [member1, member2, ...]]

# continue until cursor returns to 0
SSCAN myset <nextCursor> MATCH "pre*" COUNT 100

# iterate all members safely
cursor=0
while true:
  cursor, members = SSCAN myset cursor COUNT 100
  process(members)
  if cursor == 0: break

# scan with type filtering (7.0+ for SCAN, sets always same type)
# COUNT is a hint, not exact (may return more or fewer)

# MATCH pattern supports glob: *, ?, [abc]
SSCAN myset 0 MATCH "user:*" COUNT 1000

# for small sets, SMEMBERS is fine
# for large sets (>10k), always use SSCAN

집합 활용 사례

집합은 고유성과 관계 표현에 최적입니다. 상호 팔로워/친구를 구하는 SINTER 패턴은 고전적입니다. 카디널리티가 큰 '일별 방문자'에는 HyperLogLog(근사치지만 12KB 고정)를 고려하세요. 순서가 있는 고유 데이터(리더보드)에는 정렬된 집합을 사용하세요. 집합은 순서가 없으므로 순서가 중요하면 리스트나 정렬된 집합을 쓰세요.

redis-cli
# 1. Tags / categories
SADD post:1:tags "redis" "db"
SADD post:2:tags "redis" "cache"
SINTER post:1:tags post:2:tags   # posts sharing "redis"

# 2. Unique visitors per day
SADD visitors:2025-01-01 "user:1" "user:2"
SCARD visitors:2025-01-01        # visitor count

# 3. Followers / following (mutual friends)
SADD user:1:following "user:2" "user:3"
SADD user:2:following "user:1" "user:3"
SINTER user:1:following user:2:following  # mutual follows

# 4. Blacklist / whitelist
SADD blacklist "ip:1.2.3.4"
SISMEMBER blacklist "ip:1.2.3.4"   # 1 = blocked

# 5. Lottery / random selection
SADD participants "u1" "u2" "u3" "u4"
SPOP participants 1        # draw a winner
05

정렬된 집합

ZADD, ZSCORE, ZRANK

정렬된 집합(zset)은 Redis에서 가장 강력한 구조입니다. 고유 멤버를 점수순으로 정렬하며 연산은 O(log N)입니다. ZADD 옵션(NX/XX/GT/LT)으로 조건부 갱신이 가능합니다. GT는 새 점수가 더 클 때만 갱신하므로 '최고 점수' 추적에 좋습니다. 점수는 double이고 멤버는 고유합니다. 점수가 같으면 사전순으로 정렬됩니다.

redis-cli
# sorted set: unique members ordered by a float score
ZADD leaderboard 100 "alice" 200 "bob" 150 "carol"

# update a score (re-add with new score)
ZADD leaderboard 250 "alice"   # alice's score becomes 250

# add with options (NX: only new, XX: only existing, GT/LT)
ZADD leaderboard NX 300 "new"        # only if new
ZADD leaderboard GT 300 "alice"      # only if new score > current
ZADD leaderboard LT 50 "alice"       # only if new score < current

# get a member's score
ZSCORE leaderboard "alice"      # "250"

# get a member's rank (0-based, ascending)
ZRANK leaderboard "alice"       # rank from lowest
ZREVRANK leaderboard "alice"    # rank from highest (0 = top)

# get the number of members
ZCARD leaderboard               # 3

# get multiple scores at once (6.2+)
ZMSCORE leaderboard "alice" "bob"  # ["250", "200"]

ZRANGE와 ZREVRANGE

ZRANGE는 순위(인덱스)로 반환하고, BYSCORE를 붙이면 점수 범위로 반환합니다. Redis 6.2는 ZRANGEBYSCORE/ZREVRANGE를 ZRANGE의 BYSCORE/BYLEX/REV 옵션으로 통합했습니다. WITHSCORES는 출력에 점수를 포함합니다. 리더보드에서는 ZRANGE 0 9 REV로 상위 10개를 얻습니다. ZRANGESTORE(6.2+)는 결과를 새 키에 저장해 나중에 처리할 수 있습니다.

redis-cli
# get members by index range (ascending)
ZRANGE leaderboard 0 -1              # all, ascending
ZRANGE leaderboard 0 2               # first 3 (lowest scores)
ZRANGE leaderboard -3 -1             # last 3 (highest scores)

# descending order
ZREVRANGE leaderboard 0 2            # top 3 (highest scores)

# with scores
ZRANGE leaderboard 0 -1 WITHSCORES

# Redis 6.2+: unified ZRANGE with BYSCORE/REV options
ZRANGE leaderboard 100 200 BYSCORE
ZRANGE leaderboard 200 100 BYSCORE REV

# store a range in a new key (6.2+)
ZRANGESTORE top3 leaderboard 0 2 REV

# get by rank with scores
ZRANGE leaderboard 0 9 REV WITHSCORES  # top 10

# limit results (pagination)
ZRANGE leaderboard 0 -1 BYSCORE LIMIT 0 10

ZRANGEBYSCORE와 ZCOUNT

ZRANGEBYSCORE는 점수 범위로 반환하며, '(' 접두사는 해당 점수를 제외합니다. ZCOUNT는 멤버를 가져오지 않고 범위 내 개수를 구합니다. ZINCRBY는 점수를 원자적으로 조정하고 재정렬하므로 실시간 리더보드에 완벽합니다. ZREMRANGEBYRANK는 zset 크기를 제한하는 데 좋습니다(예: 상위 1000개만 유지).

redis-cli
# get members by score range
ZRANGEBYSCORE leaderboard 100 200    # scores 100-200
ZRANGEBYSCORE leaderboard 100 +inf   # scores >= 100
ZRANGEBYSCORE leaderboard -inf 200   # scores <= 200
ZRANGEBYSCORE leaderboard (100 200   # scores > 100 (exclusive)

# with pagination
ZRANGEBYSCORE leaderboard 100 200 LIMIT 0 10

# count members in a score range
ZCOUNT leaderboard 100 200

# increment a member's score atomically
ZINCRBY leaderboard 50 "alice"     # alice += 50

# remove a member
ZREM leaderboard "bob"

# remove by rank range
ZREMRANGEBYRANK leaderboard 0 9    # remove lowest 10
ZREMRANGEBYSCORE leaderboard 0 100 # remove scores <= 100

ZUNIONSTORE와 ZINTERSTORE

ZUNIONSTORE/ZINTERSTORE는 집계 방식(SUM/MIN/MAX)과 가중치를 지정해 zset을 결합합니다. 가중 점수 계산에 강력합니다(예: 관련도 = 텍스트 일치*2 + 최신성*1). Redis 6.2는 저장 없이 결과를 반환하는 ZUNION/ZINTER/ZDIFF를 추가했습니다(명령 하나 절약). 이들은 O(N*M)이므로 큰 집합이 많을 때 주의하세요. 집합 개수를 집합 이름보다 먼저 지정해야 합니다.

redis-cli
# combine multiple sorted sets
ZADD set1 1 "a" 2 "b"
ZADD set2 2 "a" 3 "c"

# union: sum scores by default (a = 1+2 = 3)
ZUNIONSTORE result 2 set1 set2
ZRANGE result 0 -1 WITHSCORES   # a=3, b=2, c=3

# specify aggregation: SUM (default), MIN, MAX
ZUNIONSTORE result 2 set1 set2 AGGREGATE MAX   # a=2, b=2, c=3

# apply weights to each set's scores
ZUNIONSTORE result 2 set1 set2 WEIGHTS 2 1     # set1 scores * 2

# intersection (only members in ALL sets)
ZINTERSTORE result 2 set1 set2                 # only "a"

# Redis 6.2+: return without storing
ZUNION 2 set1 set2 WITHSCORES
ZINTER 2 set1 set2 WITHSCORES
ZDIFF 2 set1 set2 WITHSCORES

# count intersection (7.0+)
ZINTERCARD 2 set1 set2 LIMIT 0

사전순 범위(BYLEX)

BYLEX는 점수가 모두 같을 때 멤버에 대한 범위 쿼리를 가능하게 하여, 정렬된 집합을 자동 정렬 문자열 인덱스로 바꿉니다. 활용 예: 자동 완성(단어를 점수 0으로 저장하고 접두사 범위 조회), 정렬된 사전. '[a'는 포함, '(a'는 제외, '-'는 시작, '+'는 끝을 뜻합니다. 모든 점수가 동일할 때만 의미 있게 동작합니다.

redis-cli
# when all scores are equal, sorted sets act as a sorted string set
ZADD myset 0 "apple" 0 "banana" 0 "cherry" 0 "date"

# range by lexicographical order
ZRANGEBYLEX myset "[a" "[c"        # apple, banana, cherry
ZRANGEBYLEX myset "(a" "[c"        # banana, cherry (a exclusive)
ZRANGEBYLEX myset "-" "[b"         # from start to banana
ZRANGEBYLEX myset "[c" "+"         # cherry to end

# count in a lex range
ZLEXCOUNT myset "[a" "[c"          # 3

# remove by lex range
ZREMRANGEBYLEX myset "[a" "[b"

# Redis 6.2+: use ZRANGE with BYLEX
ZRANGE myset "[a" "[c" BYLEX

# limit results (pagination)
ZRANGEBYLEX myset "[a" "[c" LIMIT 0 10

리더보드 패턴

정렬된 집합으로 리더보드는 간단해집니다. ZADD로 점수를 갱신하고, ZREVRANGE로 상위 N개를, ZREVRANK로 플레이어 순위를 얻습니다. ZINCRBY는 점수를 원자적으로 갱신합니다. 기간별 리더보드(일간/주간)에는 기간마다 키를 만들고 TTL을 설정하세요. 페이지네이션은 오프셋과 ZREVRANGE를 사용합니다. Redis의 가장 자연스럽고 강력한 활용 사례 중 하나입니다.

redis-cli
# build a leaderboard
ZADD leaderboard 100 "alice" 250 "bob" 150 "carol"

# top 10 players (highest scores)
ZREVRANGE leaderboard 0 9 WITHSCORES

# a player's rank (0 = top)
ZREVRANK leaderboard "alice"

# update a score (atomic)
ZINCRBY leaderboard 50 "alice"

# players within a score range (e.g., silver tier 100-199)
ZRANGEBYSCORE leaderboard 100 199

# percentile rank
total = ZCARD(leaderboard)
rank = ZREVRANK(leaderboard "alice")
# percentile = (total - rank) / total * 100

# pagination (page 3, 10 per page)
ZREVRANGE leaderboard 20 29 WITHSCORES

# time-bucketed leaderboards (weekly)
ZADD leaderboard:2025-W01 100 "alice"
EXPIRE leaderboard:2025-W01 604800   # 1 week TTL
06

해시

HSET, HGET, HGETALL

해시는 객체 저장에 이상적입니다. 객체마다 키 하나, 속성마다 필드 하나를 둡니다. 이는 JSON 직렬화보다 낫습니다. 읽기-수정-쓰기 없이 개별 필드를 원자적으로 갱신(HSET)할 수 있기 때문입니다. HGETALL은 모든 필드를 반환하지만 큰 해시에는 HSCAN을 권장합니다. 해시는 작을 때(약 128개 필드 미만) listpack 인코딩을 사용해 메모리 효율이 좋습니다.

redis-cli
# a hash maps fields to values (like a small object)
HSET user:1 name "Alice" age 30 email "[email protected]"

# get a single field
HGET user:1 name            # "Alice"

# get all fields and values
HGETALL user:1
# 1) "name"   -> "Alice"
# 2) "age"    -> "30"
# 3) "email"  -> "[email protected]"

# get the number of fields
HLEN user:1                 # 3

# get the string length of a field's value
HSTRLEN user:1 name          # 5 (length of "Alice")

# set a field only if it doesn't exist
HSETNX user:1 status "new"   # 1 if set, 0 if existed

# delete a field
HDEL user:1 email            # removes the email field

HMGET(여러 필드 조회)

HMGET은 여러 필드를 한 번의 왕복으로 가져오므로 개별 HGET 호출보다 훨씬 빠릅니다. HSET은 4.0부터 여러 필드-값 쌍을 받으므로 HMSET은 폐기되었습니다. HKEYS/HVALS는 모든 필드 이름/값을 반환합니다. HRANDFIELD(6.2+)는 샘플링에 유용합니다(예: 무작위 기능 플래그). HGETALL은 큰 해시에서 블록되므로 운영 환경 반복에는 HSCAN을 사용하세요.

redis-cli
# get multiple fields at once
HMGET user:1 name age       # 1) "Alice" 2) "30"
HMGET user:1 name missing age  # 1) "Alice" 2) nil 3) "30"

# set multiple fields (HSET supports multiple field-value pairs)
HSET user:1 name "Bob" age 25 email "[email protected]"

# HMSET is deprecated (use HSET with multiple fields)
# HMSET still works but returns OK instead of count

# get all field names
HKEYS user:1                # 1) "name" 2) "age" 3) "email"

# get all values
HVALS user:1                # 1) "Alice" 2) "30" 3) "[email protected]"

# check if a field exists
HEXISTS user:1 name          # 1 if exists, 0 if not

# get a random field (6.2+)
HRANDFIELD user:1            # one random field name
HRANDFIELD user:1 3 WITHVALUES  # 3 random fields + values

HINCRBY(숫자 필드)

해시 필드의 HINCRBY는 원자적이므로 사용자별 카운터(로그인 수, 조회 수, 장바구니 수량)에 완벽합니다. HINCRBYFLOAT은 소수를 지원합니다. 해시는 마지막 필드가 제거되면(HDEL) 자동 삭제됩니다. 따라서 해시는 숫자 카운터가 있는 객체에 이상적인 구조이며, 카운터마다 문자열 키를 두는 것보다 훨씬 효율적입니다.

redis-cli
# increment a numeric field atomically
HSET user:1:stats logins 0
HINCRBY user:1:stats logins 1    # logins = 1
HINCRBY user:1:stats logins 1    # logins = 2
HINCRBY user:1:stats logins -1   # logins = 1

# increment by a specific amount
HINCRBY user:1:stats page_views 10

# floating point increment
HINCRBYFLOAT user:1:stats score 0.5

# all HINCRBY operations are atomic
# perfect for per-user/per-object counters

# use case: shopping cart (product_id -> quantity)
HSET cart:user:1 product:100 2
HINCRBY cart:user:1 product:100 1   # now 3
HINCRBY cart:user:1 product:100 -1  # now 2
HDEL cart:user:1 product:100        # remove item

HSCAN(해시 반복)

HGETALL은 큰 해시에서 서버를 막으므로 운영 환경 반복에는 HSCAN을 사용하세요. HSCAN은 커서 기반이라 커서가 0으로 돌아올 때까지 반복 호출합니다. COUNT는 힌트입니다. 결과는 [field, value, field, value, ...] 형태의 평면 배열로 오므로 코드에서 쌍으로 묶어야 합니다. 필드가 수백만 개인 해시는 여러 키로 샤딩하는 것을 고려하세요.

redis-cli
# HSCAN: cursor-based iteration (for large hashes)
HSCAN user:1 0 MATCH "na*" COUNT 10
# returns [cursor, [field, value, field, value, ...]]

# iterate all fields safely
cursor=0
while true:
  cursor, fields = HSCAN user:1 cursor COUNT 100
  process(fields)
  if cursor == 0: break

# HGETALL is fine for small hashes (< 100 fields)
# HSCAN is required for large hashes to avoid blocking

# match field names with glob patterns
HSCAN user:1 0 MATCH "user:*" COUNT 1000

# no VALUES-only option; results are [field, value, field, value, ...]
# pair them up in your code

# COUNT is a hint — may return more or fewer than requested

# HSCAN never blocks; safe for production use

해시 활용 사례

해시는 객체와 그룹화된 카운터에 강합니다. 강력한 메모리 기법: 작은 문자열 키가 많을 때 하나의 해시로 묶으면 listpack 인코딩이 수천 개 개별 키(각각 메타데이터 포함)보다 오버헤드가 훨씬 적습니다. 이 '키 버킷팅'은 작은 값에서 메모리 사용량을 5-10배 줄일 수 있습니다. 필드 수준 TTL(7.4+)은 중요한 추가 기능입니다.

redis-cli
# 1. Store an object (user profile, config)
HSET config:app name "MyApp" version "2.0" debug "off"

# 2. Per-user counters
HINCRBY user:1:stats logins 1
HINCRBY user:1:stats page_views 1
HGET user:1:stats logins

# 3. Shopping cart (product_id -> quantity)
HSET cart:user:1 product:100 2
HINCRBY cart:user:1 product:100 1
HDEL cart:user:1 product:100

# 4. Feature flags
HSET feature_flags user:1 new_ui 1 beta 0
HGET feature_flags user:1 new_ui   # 1

# 5. Session store with TTL
HSET session:abc user_id 1 data "..."
EXPIRE session:abc 1800   # 30 min

# 6. Hash field expiration (Redis 7.4+)
HEXPIRE user:1 60 FIELDS 1 session_token
HPTTL user:1 FIELDS 1 session_token
07

키 관리

EXISTS, TYPE, DEL

EXISTS에 여러 키를 넘기면 존재하는 키의 개수를 반환합니다. TYPE은 데이터 구조 타입을 반환하므로 작업 전에 항상 확인해 WRONGTYPE 오류를 피하세요(키 타입은 수명 동안 불변). DEL은 블로킹이며 큰 구조에서 서버를 멈출 수 있으므로 큰 키에는 UNLINK를 권장합니다. TYPE은 없는 키에 'none'을 반환합니다.

redis-cli
# check if a key exists
SET mykey "hello"
EXISTS mykey             # 1
EXISTS missing           # 0
EXISTS key1 key2 key3    # count of existing keys (multiple)

# get the type of a value
TYPE mykey               # "string"
TYPE mylist              # "list"
TYPE missing             # "none"

# delete one or more keys
DEL mykey                # 1 if deleted, 0 if not
DEL key1 key2 key3       # number of keys deleted

# delete is blocking for large keys — use UNLINK instead
# UNLINK deletes in a background thread

# check type before operating to avoid WRONGTYPE errors
TYPE mykey
# returns: string | list | hash | set | zset | stream | none

UNLINK(비동기 삭제)

UNLINK(4.0+)는 큰 키에 대한 DEL의 비블로킹 대안입니다. 키를 키스페이스에서 즉시 제거하지만 메모리는 백그라운드 스레드에서 해제해 서버 정지를 막습니다. 요소가 수백만 개인 키에는 항상 UNLINK를 사용하세요. FLUSHDB ASYNC / FLUSHALL ASYNC도 대량 삭제에 같은 방식을 씁니다. lazyfree 스레드 풀이 실제 해제를 담당합니다.

redis-cli
# UNLINK: non-blocking delete (large keys)
UNLINK biglist bighash   # returns count of deleted keys

# UNLINK removes the key from the keyspace immediately
# but frees the memory in a background thread

# compare:
DEL biglist              # blocks until fully freed
UNLINK biglist           # returns immediately, frees later

# for small keys, DEL and UNLINK are equivalent
# for large keys (millions of elements), UNLINK is essential

# flush database asynchronously (non-blocking)
FLUSHDB ASYNC
FLUSHALL ASYNC

# check what's being freed in background
INFO memory | grep lazyfree

RENAME과 RENAMENX

RENAME은 키를 새 이름으로 원자적으로 이동하며 기존 대상 키(와 값)를 덮어씁니다. RENAMENX(6.2+)는 대상이 없을 때만 이름을 바꿔 실수로 덮어쓰는 것을 막습니다. 이름을 바꿔도 TTL은 유지됩니다. RENAME은 원자적이라 다른 클라이언트가 중간 상태를 볼 수 없습니다. 데이터베이스 간 이름 변경은 지원되지 않으므로 MOVE나 DUMP/RESTORE를 사용하세요.

redis-cli
# rename a key (overwrites destination if it exists)
SET oldkey "value"
RENAME oldkey newkey     # OK; oldkey is gone, newkey has "value"

# rename only if destination doesn't exist (6.2+)
RENAMENX oldkey newkey   # 1 if renamed, 0 if newkey already exists

# rename preserves the type and TTL
SET tempkey "data" EX 3600
RENAME tempkey permkey   # permkey now has TTL of ~3600s
TTL permkey              # ~3600

# rename across databases is not supported
# use MOVE + RENAME, or DUMP/RESTORE for cross-db moves

# type is immutable — rename keeps the type
TYPE permkey             # "string"

# renaming is atomic

KEYS와 SCAN

KEYS는 전체 키스페이스를 스캔하는 동안 서버를 막으므로 큰 데이터셋이 있는 운영 환경에서는 절대 사용하지 마세요. SCAN은 운영 환경에서 안전한 대안입니다. 커서 기반이고 비블로킹이며, 0이 될 때까지 따라가는 커서를 반환합니다. SCAN은 중복을 반환하거나 반복 중 추가된 키를 놓칠 수 있지만 절대 블록하지 않습니다. COUNT는 힌트이며 더 많거나 적게 반환될 수 있습니다. 항상 커서 루프를 처리하세요.

redis-cli
# KEYS: blocks the server while scanning — NEVER in production
KEYS *                   # all keys (DANGEROUS on large DBs)
KEYS user:*              # keys matching pattern
KEYS session:*

# SCAN: cursor-based iteration (non-blocking, production-safe)
SCAN 0 MATCH user:* COUNT 100
# returns: [nextCursor, [key1, key2, ...]]

# continue until cursor returns to 0
SCAN <nextCursor> MATCH user:* COUNT 100

# scan by type (7.0+)
SCAN 0 TYPE hash
SCAN 0 MATCH user:* TYPE string COUNT 100

# SCAN is weakly consistent:
# - may return duplicates
# - may miss keys added during iteration
# - but NEVER blocks the server

# COUNT is a hint, not exact

RANDOMKEY와 DBSIZE

RANDOMKEY는 키를 제거하지 않고 무작위 키를 반환하므로 샘플링에 유용합니다. DBSIZE는 현재 데이터베이스의 정확한 키 개수를 반환합니다(O(1)). INFO keyspace는 데이터베이스별 키 개수와 만료 통계(keys, expires, avg_ttl)를 보여줍니다. 특정 타입의 무작위 키를 얻는 내장 명령은 없으므로 SCAN + TYPE을 루프로 사용하세요.

redis-cli
# get a random key (O(1), does not remove)
RANDOMKEY                # "user:1" or nil if db is empty

# get the number of keys in the current database
DBSIZE                   # 1234

# count keys across all databases (in a cluster)
# note: DBSIZE only counts the current db
SELECT 0; DBSIZE
SELECT 1; DBSIZE

# get keyspace info (keys per db with expiry info)
INFO keyspace
# db0:keys=1000,expires=500,avg_ttl=3600000
# db1:keys=50,expires=10,avg_ttl=60000

# scan with count for approximate size estimation
SCAN 0 COUNT 1           # get cursor + small sample

# find a random key of a specific type
# (no built-in; use SCAN + TYPE in a loop)

OBJECT 명령

OBJECT ENCODING은 내부 표현을 보여줍니다(메모리 디버깅). OBJECT IDLETIME은 콜드 키(제거 후보)를 찾습니다. OBJECT FREQ는 maxmemory-policy가 LFU일 때만 동작합니다. MEMORY USAGE는 SAMPLES 0으로 정확히 계산합니다(기본값은 큰 컬렉션을 샘플링). COMMAND DOCS(7.0+)는 구조화된 문서를 반환합니다. 이런 내부 조회 도구로 메모리 팽창을 디버깅하세요.

redis-cli
# OBJECT subcommands for introspection
OBJECT ENCODING mykey     # internal encoding (embstr, raw, int, listpack, etc.)
OBJECT REFCOUNT mykey     # reference count
OBJECT IDLETIME mykey     # seconds since last access
OBJECT FREQ mykey         # access frequency (LFU mode only)

# check memory usage of a key (bytes)
MEMORY USAGE mykey
MEMORY USAGE mykey SAMPLES 0   # exact count (slower for large keys)

# total memory used by the server
INFO memory | grep used_memory_human

# inspect a key's internal structure (debugging, can be slow)
DEBUG OBJECT mykey        # raw internal info

# the encoding changes automatically as the structure grows
# e.g., hash: listpack -> hashtable when fields exceed threshold

# help understand a command
COMMAND INFO GET
COMMAND DOCS SET          # structured docs (7.0+)
08

만료와 영속성

EXPIRE와 EXPIREAT

EXPIRE는 기존 키에 TTL을 설정하고, EX/PX/EXAT/PXAT를 붙인 SET은 이를 원자적으로 수행합니다(권장). NX/GT/LT 옵션(7.0+)은 조건부 TTL 설정을 가능하게 합니다('만료가 없을 때만 추가', '연장만 하고 단축은 안 함'). TTL은 만료가 없는 키에 -1, 없는 키에 -2를 반환합니다. 만료는 접근 시 확인하는 지연 방식과 주기적 백그라운드 스윕을 함께 사용합니다.

redis-cli
# set expiration on an existing key (seconds)
SET mykey "value"
EXPIRE mykey 60              # expires in 60 seconds
EXPIRE mykey 60 NX           # only set TTL if none exists (7.0+)
EXPIRE mykey 60 GT           # only set if new TTL > current (7.0+)
EXPIRE mykey 60 LT           # only set if new TTL < current (7.0+)

# set expiration in milliseconds
PEXPIRE mykey 60000

# set expiration at a Unix timestamp
EXPIREAT mykey 1700000000       # seconds
PEXPIREAT mykey 1700000000000    # milliseconds

# set value AND expiration atomically (preferred)
SET token "abc" EX 3600
SET token "abc" PX 3600000
SET token "abc" EXAT 1700000000

# get remaining TTL
TTL mykey          # seconds (-1 = no expiry, -2 = no key)
PTTL mykey         # milliseconds

PERSIST(TTL 제거)

PERSIST는 TTL을 제거해 키를 영구적으로 만듭니다(값은 유지). GETEX(6.2+)는 값을 원자적으로 반환하면서 TTL을 설정하거나 제거합니다. 읽을 때 세션 만료를 갱신하거나(GETEX key EX 3600), 임시 키를 영구 키로 바꿀 때(GETEX key PERSIST) 유용합니다. COPY(6.2+)는 GET+SET의 경쟁 조건 없이 키를 복사하며 데이터베이스 간 복사도 가능합니다.

redis-cli
# remove expiration (make key persistent)
SET session "data" EX 3600
TTL session               # 3600
PERSIST session           # 1 (success)
TTL session               # -1 (no expiry)

# PERSIST returns 1 if the TTL was removed, 0 if key had no TTL or doesn't exist

# copy a key with optional TTL handling (6.2+)
COPY source dest               # copy without TTL
COPY source dest REPLACE       # overwrite destination
COPY source dest DB 1          # copy to another database

# GETEX: get value and optionally set/remove TTL (6.2+)
GETEX mykey EX 3600       # returns value, sets 3600s TTL
GETEX mykey PERSIST       # returns value, removes TTL

# note: PERSIST only removes TTL; the key and value remain

SAVE와 BGSAVE(RDB)

SAVE는 스냅샷이 끝날 때까지 서버를 막으므로 운영 환경에서는 절대 사용하지 마세요. BGSAVE는 프로세스를 포크(기록 중 복사)해 메인 스레드를 막지 않지만, 큰 데이터셋은 포크 중 메모리 급증을 일으킬 수 있습니다. 'save' 규칙은 변경 빈도에 따라 자동 스냅샷을 트리거합니다. RDB는 압축적이고 백업에 이상적이지만 마지막 스냅샷 이후 기록된 데이터를 잃을 위험이 있습니다.

redis-cli
# SAVE: synchronous snapshot (BLOCKS the server until done)
SAVE                     # blocks — use only in maintenance windows

# BGSAVE: background snapshot (non-blocking, forks a child)
BGSAVE                   # returns immediately, saves in background
LASTSAVE                 # Unix timestamp of the last successful save

# check if a BGSAVE is in progress
INFO persistence | grep rdb_bgsave_in_progress

# configure automatic snapshots in redis.conf:
#   save 3600 1     # save if >= 1 key changed in 3600s
#   save 300 100    # save if >= 100 keys changed in 300s
#   save 60 10000   # save if >= 10000 keys changed in 60s
#   save ""         # disable RDB entirely

# RDB file location
CONFIG GET dbfilename    # "dump.rdb"
CONFIG GET dir           # "/var/lib/redis"

# RDB pros: compact, fast restart, great for backups
# RDB cons: potential data loss between snapshots

BGREWRITEAOF(AOF 압축)

AOF는 모든 쓰기 명령을 로그에 추가하므로 RDB보다 훨씬 내구성이 좋습니다(everysec이면 최대 1초 데이터 손실). 'always'는 매 쓰기마다 fsync하므로 매우 느려 중요한 데이터에만 사용하세요. BGREWRITEAOF는 로그를 최소 명령 집합으로 다시 작성해 압축합니다. Redis 7은 다중 파트 AOF 형식(기본 RDB + 증분 로그)을 사용하며 appenddirname에 파트가 저장됩니다.

redis-cli
# AOF: logs every write command (durable, replayable)
# enable in redis.conf:
#   appendonly yes
#   appendfilename "appendonly.aof"

# fsync policies:
#   appendfsync always    # fsync every write (safest, slowest)
#   appendfsync everysec  # fsync once per second (default, balanced)
#   appendfsync no        # let OS decide (fastest, risk of data loss)

# trigger AOF rewrite (compacts the log)
BGREWRITEAOF             # non-blocking, rewrites in background

# AOF auto-rewrite thresholds:
#   auto-aof-rewrite-percentage 100
#   auto-aof-rewrite-min-size 64mb

# check AOF status
INFO persistence | grep aof

# AOF pros: minimal data loss (1 sec max with everysec)
# AOF cons: larger files, slower load on restart

# Redis 7: multi-part AOF (base + incremental files)
CONFIG GET appenddirname   # "appendonlydir"

영속성 설정

CONFIG SET은 재시작 없이 런타임에 설정을 바꾸고, CONFIG REWRITE는 이를 redis.conf에 영구 저장합니다. 권장 운영 구성은 RDB + AOF 하이브리드입니다. 빠른 재시작과 백업에는 RDB, 최소 데이터 손실에는 AOF를 사용합니다. Redis 7부터 AOF는 RDB 기본 스냅샷 뒤에 증분 명령이 이어지는 형태로 시작해 빠른 로드와 내구성을 결합합니다.

redis-cli
# view current persistence settings
CONFIG GET save
CONFIG GET appendonly
CONFIG GET appendfsync
CONFIG GET dir
CONFIG GET dbfilename
CONFIG GET appendfilename

# enable AOF at runtime
CONFIG SET appendonly yes

# change fsync policy at runtime
CONFIG SET appendfsync everysec

# disable RDB snapshots
CONFIG SET save ""

# persist config changes to redis.conf
CONFIG REWRITE

# hybrid persistence (recommended):
# RDB for fast restart + AOF for durability
# redis.conf:
#   save 3600 1
#   appendonly yes
#   aof-use-rdb-preamble yes   # RDB header in AOF (faster load)

# check persistence status
INFO persistence

백업과 복원

RDB 파일(압축적이고 빠름)을 정기적으로 백업하세요. Redis가 실행 중이어도 일관된 스냅샷입니다(기록 중 복사). AOF는 appendonly 디렉터리 전체(Redis 7 다중 파트)를 백업하세요. 복원은 Redis를 중지하고 파일을 교체한 뒤 재시작합니다. 잘못된 명령에서 복구하려면 재시작 전에 AOF에서 해당 명령을 편집해 제거하세요. redis-cli --rdb는 파일 시스템을 직접 건드리지 않고 온라인 백업을 수행합니다.

redis-cli
# backup: copy the RDB file while Redis runs
BGSAVE
# wait for LASTSAVE to update, then copy the file
cp /var/lib/redis/dump.rdb /backup/dump-$(date +%F).rdb

# AOF backup: copy the AOF manifest + files (Redis 7)
cp -r /var/lib/redis/appendonlydir /backup/

# restore: stop Redis, replace data files, restart
redis-cli SHUTDOWN
cp /backup/dump.rdb /var/lib/redis/dump.rdb
redis-server /etc/redis/redis.conf

# for point-in-time recovery from AOF:
# edit the AOF file to remove unwanted commands, then restart

# RDB file analysis (offline, safe)
redis-check-rdb /var/lib/redis/dump.rdb
redis-check-aof /var/lib/redis/appendonly.aof

# fix a truncated AOF
redis-check-aof --fix /var/lib/redis/appendonly.aof

# online backup with --rdb (dumps RDB to stdout/file)
redis-cli --rdb /backup/dump.rdb
09

발행/구독

SUBSCRIBE와 UNSUBSCRIBE

SUBSCRIBE는 하나 이상의 채널에서 메시지를 받기 위해 클라이언트를 블록합니다. 구독 중인 클라이언트는 SUBSCRIBE/UNSUBSCRIBE/PSUBSCRIBE/PUNSUBSCRIBE/PING/QUIT만 호출할 수 있고 다른 명령은 불가합니다. PUBSUB은 발행/구독 상태(활성 채널, 구독자 수)를 조회합니다. 메시지는 발행 후 잊히는 방식이라 구독자가 없으면 사라집니다. 신뢰성 있는 전달에는 Streams를 사용하세요.

redis-cli
# subscribe to channels (in one client, blocks)
SUBSCRIBE news alerts

# the client now listens for messages:
# 1) "subscribe" 2) "news" 3) 1
# 1) "subscribe" 2) "alerts" 3) 2

# unsubscribe from specific channels
UNSUBSCRIBE news
UNSUBSCRIBE news alerts

# unsubscribe from ALL channels
UNSUBSCRIBE

# note: published messages are NOT persisted
# if no subscriber is listening, the message is lost
# for persistent messaging, use Streams instead

# count active subscriptions (in another client)
PUBSUB CHANNELS           # list active channels
PUBSUB NUMSUB news        # subscriber count for "news"

PUBLISH

PUBLISH는 메시지를 받은 구독자 수를 반환합니다(없으면 0). 발행된 메시지를 나중에 검색할 방법은 없으므로 구독자가 없으면 사라집니다. PUBSUB CHANNELS는 활성 채널(구독자가 하나 이상 있는 채널)을 나열하고, PUBSUB NUMSUB은 구독자 수를 반환합니다. 신뢰성 있고 재생 가능한 메시징에는 Streams(XADD/XREAD)를 사용하세요.

redis-cli
# publish a message to a channel (from another client)
PUBLISH news "Breaking: Redis 7.4 released"
# returns: number of subscribers that received the message

# publish to a channel with no subscribers
PUBLISH empty "hello"
# returns: 0 (message is lost)

# publish to multiple channels (separate PUBLISH calls)
PUBLISH news "msg1"
PUBLISH alerts "msg2"

# pub/sub has no persistence, no replay, no consumer groups
# subscribers must be connected to receive messages

# check how many clients are listening
PUBSUB NUMSUB news
PUBSUB NUMSUB news alerts    # multiple channels

# list active channels (with pattern)
PUBSUB CHANNELS              # all active channels
PUBSUB CHANNELS news:*       # channels matching pattern

PSUBSCRIBE(패턴 구독)

PSUBSCRIBE는 glob 패턴과 일치하는 채널을 구독하므로 이벤트 라우팅에 강력합니다(예: user:*:login은 모든 사용자 로그인 이벤트를 잡음). 직접 구독과 패턴 구독에 모두 일치하는 메시지는 두 번 전달됩니다. 패턴 구독자는 패턴, 채널, 메시지가 담긴 'pmessage' 이벤트를 받습니다. PUNSUBSCRIBE는 패턴 구독을 취소합니다.

redis-cli
# subscribe to channels matching a glob pattern
PSUBSCRIBE news.*
PSUBSCRIBE user:*:login
PSUBSCRIBE events:*

# patterns use glob syntax:
#   *    matches any sequence
#   ?    matches one character
#   [ab] matches 'a' or 'b'

# unsubscribe from patterns
PUNSUBSCRIBE news.*
PUNSUBSCRIBE               # unsubscribe from ALL patterns

# a message matching both a direct subscription and a pattern
# is delivered twice (once for each)

# pattern subscribers receive:
# 1) "pmessage" 2) "news.*" 3) "news.tech" 4) "the message"

# use case: event routing
PSUBSCRIBE user:*:login       # all user logins
PSUBSCRIBE order:*:created    # all order creations
PSUBSCRIBE cache:*:invalidate # cache invalidation events

샤드 발행/구독(7.0+)

샤드 발행/구독(7.0+)은 클러스터 모드의 문제를 해결합니다. 일반 발행/구독은 모든 PUBLISH를 클러스터의 모든 노드에 브로드캐스트해 대역폭을 낭비합니다. 샤드 발행/구독은 채널 키를 소유한 샤드에만 메시지를 라우팅하므로 큰 클러스터에서 훨씬 효율적입니다. 클러스터 배포에서는 SSUBSCRIBE/SPUBLISH를 사용하세요. 채널 이름이 키처럼 샤드를 결정합니다.

redis-cli
# regular Pub/Sub broadcasts to ALL cluster nodes (expensive)
# sharded Pub/Sub routes messages only to the shard owning the channel

# subscribe to a shard channel
SSUBSCRIBE mychannel

# publish to a shard channel
SPUBLISH mychannel "hello"

# sharded pub/sub uses the channel name for shard routing
# so messages only travel within one shard (more efficient)

# use sharded pub/sub in a Redis Cluster to avoid
# broadcasting messages to every node

# regular SUBSCRIBE/PUBLISH still work in cluster mode
# but they broadcast to all shards (cluster-wide overhead)

# check shard channel subscribers (7.0+)
PUBSUB SHARDCHANNELS
PUBSUB SHARDNUMSUB mychannel

키스페이스 알림

키스페이스 알림을 사용하면 클라이언트가 키 수명 주기 이벤트(set, delete, expire, evict)에 반응할 수 있습니다. notify-keyspace-events로 설정합니다. 이 알림은 발행 후 잊히는 방식(영속성 없음)이라 신뢰할 수 없습니다. Redis 서버가 재시작하면 대기 중인 이벤트는 사라집니다. 신뢰성 있는 이벤트 처리에는 Streams를 사용하세요. 키스페이스 알림은 정리나 캐시 워밍 같은 부수 효과에 좋습니다.

redis-cli
# enable keyspace notifications (disabled by default)
CONFIG SET notify-keyspace-events "KEA"
# K = keyspace events, E = keyevent events
# g = generic (DEL, EXPIRE, ...), $ = string, l = list
# h = hash, s = set, z = sorted set, x = expired, e = evicted
# A = all except m (m = keymiss)

# subscribe to events on a specific key
SUBSCRIBE __keyspace@0__:mykey
# publishes "set", "del", "expire", etc.

# subscribe to events of a specific type
SUBSCRIBE __keyevent@0__:del
# publishes the key name that was deleted

# example: react when a key expires
SUBSCRIBE __keyspace@0__:session:abc
# receives "expired" when the key TTL ends

# example: react to all expired keys
SUBSCRIBE __keyevent@0__:expired

# check current setting
CONFIG GET notify-keyspace-events
10

트랜잭션

MULTI와 EXEC

MULTI/EXEC은 명령을 원자적이고 순차적인 블록으로 묶어 다른 클라이언트가 끼어들 수 없게 합니다. 명령은 큐에 쌓이고(QUEUED 반환) EXEC에서 함께 실행됩니다. 큐잉 오류(잘못된 명령 이름)는 전체 트랜잭션을 중단합니다. 런타임 오류(키 타입 불일치)는 해당 명령만 건너뛰고 나머지는 계속 실행됩니다. 이는 SQL 트랜잭션과 다릅니다.

redis-cli
# MULTI starts a transaction; commands are queued
MULTI
SET counter 1
INCR counter
INCR counter
GET counter
EXEC
# returns: 1) OK  2) 2  3) 3  4) "3"

# all queued commands execute atomically (no interleaving)
# other clients cannot run commands between MULTI and EXEC

# each queued command returns "QUEUED" until EXEC
MULTI
SET x 1
# "QUEUED"
INCR x
# "QUEUED"
EXEC
# 1) OK 2) 2

# the transaction is atomic: all or nothing (at queuing time)

DISCARD(트랜잭션 취소)

DISCARD는 트랜잭션을 취소해 대기 중인 모든 명령을 지우고 연결을 트랜잭션 모드에서 해제합니다. WATCH한 키도 모두 지웁니다. DISCARD 후에는 다시 일반 명령을 실행할 수 있습니다. DISCARD는 '롤백'에 해당하지만, Redis는 EXEC 내부의 부분 롤백을 지원하지 않습니다. 런타임 오류가 난 명령만 건너뛰고 나머지는 커밋됩니다.

redis-cli
# DISCARD cancels a transaction (clears all queued commands)
MULTI
SET x 1
INCR x
DISCARD
# OK — no commands are executed

# after DISCARD, the connection returns to normal mode
GET x
# (nil) or the previous value — nothing changed

# DISCARD also clears all WATCHed keys
WATCH counter
MULTI
INCR counter
DISCARD
# counter is no longer watched

# you must call MULTI before DISCARD
DISCARD
# ERR DISCARD without MULTI

WATCH(낙관적 잠금)

WATCH는 낙관적 잠금을 구현합니다. WATCH와 EXEC 사이에 감시한 키가 바뀌면 트랜잭션이 중단됩니다(EXEC가 nil 반환). Redis에는 행 잠금이 없으므로 읽기-수정-쓰기 원자성을 위한 표준 패턴입니다. nil이 나오면 항상 재시도하세요. WATCH는 EXEC 시점에 확인됩니다. UNWATCH는 감시를 취소하며 연결 종료 시에도 취소됩니다. 같은 클라이언트가 감시한 키를 수정해도 중단됩니다.

redis-cli
# WATCH monitors keys; if any change before EXEC, transaction aborts
WATCH counter
val = GET counter          # read current value
MULTI
INCR counter               # queue the update
EXEC                       # nil if counter changed -> retry

# typical pattern: read-modify-write with retry
WATCH key
current = GET key
new_value = compute(current)
MULTI
SET key new_value
EXEC
# if EXEC returns nil, the key changed — loop and retry

# UNWATCH cancels all watches
UNWATCH

# WATCH is checked at EXEC time, not during queuing
# if a watched key is modified (by any client, including yourself),
# EXEC returns nil and the transaction is not executed

UNWATCH와 WATCH 주의점

EXEC 후에는 트랜잭션이 커밋되었든 WATCH 때문에 중단되었든 모든 감시가 자동으로 해제됩니다. DISCARD도 마찬가지입니다. 낙관적 잠금 루프를 재시도하려면 다음 MULTI 전에 WATCH를 다시 호출해야 합니다. MULTI 안에서 WATCH를 쓰면 오류입니다. WATCH는 항상 MULTI보다 먼저 와야 합니다. UNWATCH는 주로 트랜잭션에 들어가지 않고 감시를 취소할 때 사용합니다.

redis-cli
# UNWATCH cancels all watches
WATCH key1 key2
UNWATCH                    # both keys are no longer watched

# WATCH inside a MULTI is not allowed (error)
MULTI
WATCH key
# ERR WATCH inside MULTI is not allowed

# after EXEC (success or abort), watches are cleared
WATCH key
MULTI
SET key "new"
EXEC
# key is no longer watched after EXEC

# after DISCARD, watches are cleared
WATCH key
MULTI
DISCARD
# key is no longer watched

# re-WATCH after EXEC to retry the optimistic lock loop
WATCH key
val = GET key
MULTI
SET key newval
EXEC
# if nil, loop: WATCH key again, GET, MULTI, SET, EXEC

트랜잭션 오류 처리

Redis 트랜잭션에는 두 가지 오류 유형이 있습니다. 큐잉 오류(잘못된 명령 이름/인자 수)는 EXEC 시점에 전체 트랜잭션을 중단합니다(EXECABORT). 아무것도 실행되지 않습니다. 런타임 오류(예: 정수가 아닌 값에 INCR)는 실패한 명령만 건너뛰고 나머지는 실행됩니다. 롤백은 없습니다. SQL 데이터베이스와의 중요한 차이입니다. 런타임 오류를 피하려면 MULTI 전에 데이터를 검증하세요.

redis-cli
# two types of errors in transactions:

# 1. Queuing errors (bad command syntax) — aborts the WHOLE transaction
MULTI
SET key "value"
INCRBY key "notanumber"   # error during queuing (wrong arity/type at parse)
GET key
EXEC
# EXECABORT Transaction discarded because of previous errors.
# NOTHING executes — not even the SET

# 2. Runtime errors (wrong type at execution) — skips ONLY that command
SET key "stringvalue"
MULTI
INCR key                  # queues fine (syntax OK)
SET otherkey "ok"
EXEC
# 1) (error) ERR value is not an integer
# 2) OK
# the INCR failed but SET otherkey succeeded — no rollback!

# lesson: Redis transactions do NOT have rollback like SQL
11

파이프라이닝

파이프라인 기초

파이프라이닝은 명령을 묶어 네트워크 왕복을 줄이므로 네트워크 환경에서 개별 명령보다 훨씬 빠릅니다. 왕복마다 네트워크 지연(약 0.1-1ms)이 들기 때문에 명령 1000개는 100-1000ms가 걸리지만, 파이프라인을 쓰면 약 1ms입니다. 대부분의 클라이언트 라이브러리가 파이프라인/멀티 메서드를 제공합니다. redis-cli는 stdin으로 파이프라인할 수 있습니다. 파이프라이닝은 원자성을 보장하지 않으며 다른 클라이언트가 끼어들 수 있습니다.

redis-cli
# pipelining sends multiple commands in one network round-trip
# (no atomicity guarantee, just reduced latency)

# using redis-cli with stdin (simple pipeline):
printf '%s\n' "SET k1 v1" "SET k2 v2" "GET k1" | redis-cli
# OK
# OK
# "v1"

# using redis-cli --pipe (raw RESP, fastest for bulk loads):
# (see the data-import-export section for details)

# in a client library (e.g., Node.js with ioredis):
const pipe = redis.pipeline()
pipe.set("k1", "v1")
pipe.set("k2", "v2")
pipe.incr("counter")
const results = await pipe.exec()

# vs individual commands:
await redis.set("k1", "v1")    # round-trip 1
await redis.set("k2", "v2")    # round-trip 2
await redis.incr("counter")    # round-trip 3

MULTI와 파이프라이닝

MULTI/EXEC은 원자성을 보장하고(다른 클라이언트가 끼어들 수 없음), 대부분의 클라이언트 라이브러리가 자동으로 파이프라인 처리하므로 왕복도 줄어듭니다. 단순 파이프라이닝은 왕복만 줄이며 다른 클라이언트가 중간에 명령을 실행할 수 있습니다. 원자성이 필요하면(예: WATCH를 사용한 읽기-수정-쓰기) MULTI/EXEC을, 순서나 원자성이 중요하지 않은 대량 작업에는 단순 파이프라이닝을 사용하세요.

redis-cli
# MULTI/EXEC: atomic (no interleaving), pipelined automatically
MULTI
SET k1 v1
SET k2 v2
INCR counter
EXEC
# all 3 commands run atomically as one block

# Pipelining: NOT atomic, just batched (other clients can interleave)
# (in client code)
pipe.set("k1", "v1")
pipe.set("k2", "v2")
pipe.incr("counter")
pipe.exec()
# commands may interleave with other clients

# when to use which:
# - need atomicity (all-or-nothing)?      -> MULTI/EXEC
# - just want speed (bulk operations)?    -> pipelining
# - both?                                  -> MULTI/EXEC (auto-pipelined)

# MULTI/EXEC is automatically pipelined by most clients
# so you get atomicity + batch round-trips in one

RESP 프로토콜

RESP는 Redis의 통신 프로토콜로 단순하고 텍스트 기반이며 빠릅니다. *N은 N개 요소의 배열, $N은 N바이트 벌크 문자열, +는 단순 문자열, :는 정수, -는 오류를 뜻합니다. redis-cli --pipe 모드는 원시 RESP를 받아 최고 속도로 대량 적재합니다(stdin 텍스트 명령보다 훨씬 빠름). RESP를 이해하면 디버깅과 사용자 클라이언트 구현에 도움이 됩니다.

redis-cli
# RESP (REdis Serialization Protocol) is the wire format
# redis-cli sends RESP; you can also send it raw with --pipe

# simple command (PING) in RESP:
# *1\r\n$4\r\nPING\r\n

# SET key value in RESP:
# *3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n

# RESP types:
#   +OK      simple string
#   -ERR     error
#   :42      integer
#   $5\r\nhello   bulk string
#   *2\r\n...     array

# raw pipeline with RESP (fastest bulk insert):
# generate a RESP file and pipe it:
cat commands.resp | redis-cli --pipe

# --pipe mode expects raw RESP; checks reply counts
# output: "Last reply received from server: ..."
# "errors: 0, replies: N"

셸 스크립트에서 파이프라인

redis-cli를 사용한 셸 스크립팅은 데이터를 대량 적재하거나 배치 작업을 실행하는 흔한 방법입니다. 가장 간단한 방법은 stdin으로 텍스트 명령을 파이프하는 것입니다(echo/cat | redis-cli). 최고 속도를 원하면 RESP를 생성해 --pipe 모드를 사용하세요(대량 적재에서 훨씬 빠름). 아래 bash 루프 예제는 두 방식을 모두 보여주니 데이터 양과 성능 요구에 따라 선택하세요.

redis-cli
# pipeline multiple commands via stdin
echo -e "SET k1 v1\nSET k2 v2\nGET k1\nGET k2" | redis-cli

# pipeline from a file
cat commands.txt | redis-cli

# pipeline with --pipe-mode (raw RESP, fastest)
# first generate RESP, then pipe:
redis-cli --pipe < commands.resp

# bulk insert example (bash, generate RESP):
for i in $(seq 1 1000); do
  printf '*3\r\n$3\r\nSET\r\n$4\r\nkey:\r\n$1\r\n%s\r\n' "$i"
done | redis-cli --pipe

# or simpler (text mode, slightly slower):
for i in $(seq 1 1000); do
  echo "SET key:$i value$i"
done | redis-cli

# --pipe-mode reports errors and throughput

파이프라인 한계와 모범 사례

파이프라이닝은 Redis 성능을 좌우하는 가장 큰 요소지만 과도하게 쓰면 안 됩니다. 대기 중인 응답이 클라이언트와 서버 양쪽의 메모리를 소모합니다. 100-1000개 단위로 묶으세요. redis-benchmark -P로 최적점을 찾으세요(처리량이 정체되고 지연이 커짐). 이전 결과에 의존하는 명령에는 여러 번의 파이프라인 호출 대신 Lua 스크립트(원자적, 단일 왕복)를 사용하세요.

redis-cli
# don't pipeline too many commands at once
# (queued replies consume memory on both client and server)

# bad: 1 million commands in one pipeline
# -> huge memory buffer, potential timeout

# good: batch in groups of 100-1000
for batch in chunks(data, 500):
  pipe = redis.pipeline()
  for item in batch:
    pipe.set(item.key, item.value)
  pipe.exec()

# benchmark pipelining
redis-benchmark -t set -n 100000 -P 16   # -P = pipeline size
# try -P 1, 10, 100, 1000 to find the sweet spot

# use pipelining for:
# - bulk imports
# - batch reads (MGET is better for simple multi-get)
# - pre-warming cache
# - reducing latency in high-RTT environments

# avoid pipelining for:
# - commands that depend on previous results (use Lua instead)
# - very large batches (split into chunks)
12

Lua 스크립팅

EVAL 기초

EVAL은 Lua 스크립트를 원자적으로 실행합니다. 스크립트가 실행되는 동안 다른 명령은 실행되지 않으므로 여러 단계의 원자적 작업에 이상적입니다. KEYS와 ARGV로 호출자에서 데이터를 전달합니다. 스크립트에서 문자열 연결로 키를 만들지 마세요(클러스터 규칙 위반, 모든 키는 KEYS에 있어야 함). redis.call은 오류를 발생시키고(중단), redis.pcall은 반환합니다. 스크립트는 SHA1 해시로 캐시되어 EVALSHA에 사용됩니다.

redis-cli
# EVAL: run a Lua script inline
# EVAL "script" numkeys key1 key2 ... arg1 arg2 ...
EVAL "return redis.call('GET', KEYS[1])" 1 mykey
# 1 = number of keys
# mykey = KEYS[1]

# run a simple script (no keys)
EVAL "return 42" 0
EVAL "return {1, 2, 3}" 0
EVAL "return 'hello'" 0

# a check-and-set script:
EVAL "
  local cur = redis.call('GET', KEYS[1])
  if cur == ARGV[1] then
    return redis.call('SET', KEYS[1], ARGV[2])
  end
  return 0
" 1 mykey "expected" "newvalue"

# redis.call() raises error if command fails (stops script)
# redis.pcall() returns error as a table (can handle)
EVAL "local ok, err = pcall(redis.call, 'GET', 'missing'); return err" 0

EVALSHA와 SCRIPT LOAD

EVALSHA는 미리 로드한 스크립트를 SHA1 해시로 실행해 호출마다 스크립트 본문을 다시 보내지 않으므로, 같은 스크립트를 반복 실행하는 앱에서 대역폭을 크게 절약합니다. 캐시 미스(SCRIPT FLUSH나 재시작 후)에는 NOSCRIPT를 반환하므로 클라이언트가 이를 잡아 EVAL + SCRIPT LOAD로 폴백합니다. 이를 투명하게 처리하는 라이브러리(redis-py, ioredis)를 사용하세요.

redis-cli
# load a script once, get its SHA1
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
# returns: "fa00d1f0..." (the SHA1 hash)

# execute by hash (saves bandwidth on repeated calls)
EVALSHA "fa00d1f0..." 1 mykey

# check if a script is cached
SCRIPT EXISTS "fa00d1f0..." "abcd1234..."
# 1) 1  2) 0   (1 = exists, 0 = not cached)

# flush the script cache
SCRIPT FLUSH

# list all running scripts (during debug)
SCRIPT DEBUG SYNC   # blocking debug mode
SCRIPT DEBUG NO     # disable debugger

# typical client library pattern:
# 1. SCRIPT LOAD the script on startup
# 2. EVALSHA to run it (falls back to EVAL on NOSCRIPT error)

SCRIPT LOAD, FLUSH, EXISTS

SCRIPT LOAD는 스크립트를 캐시하고 SHA1을 반환합니다. SCRIPT EXISTS는 스크립트가 캐시되었는지 확인합니다(재시작 후 유용). SCRIPT FLUSH는 캐시된 스크립트를 모두 지우므로 이후 EVALSHA는 NOSCRIPT를 반환합니다. SCRIPT KILL은 오래 실행되는 스크립트를 중지하지만 아직 쓰기를 하지 않았을 때만 가능합니다(일관성 유지). 쓰기를 했다면 SHUTDOWN NOSAVE가 필요합니다. 스크립트는 휘발성이므로 영속성이 필요하면 Functions(7.0+)를 사용하세요.

redis-cli
# SCRIPT LOAD: load a script without running it
SCRIPT LOAD "return redis.call('SET', KEYS[1], ARGV[1])"
# returns the SHA1 hash

# SCRIPT EXISTS: check if scripts are cached (after load or restart)
SCRIPT EXISTS "abc123..." "def456..."
# 1) 1  2) 0

# SCRIPT FLUSH: clear the script cache
SCRIPT FLUSH
# all EVALSHA calls will now return NOSCRIPT until scripts are reloaded

# SCRIPT KILL: stop a running script (only if it hasn't written yet)
SCRIPT KILL

# if the script has already executed a write command:
# SHUTDOWN NOSAVE is the only way to stop it (extreme measure)

# scripts are ephemeral — they don't survive a restart
# use Redis Functions (7.0+) for persistent scripts

# check the script cache size
INFO memory | grep script_cache

KEYS와 ARGV

KEYS[]는 키 이름을 담습니다(클러스터 라우팅에 필수, 클러스터가 이를 보고 어떤 샤드가 스크립트를 처리할지 결정). ARGV[]는 값과 매개변수를 담습니다. 스크립트 안에 키 이름을 하드코딩하지 마세요(예: redis.call('GET', 'mykey')). 클러스터가 'mykey'가 어느 샤드에 있는지 알 수 없어 라우팅이 깨집니다. 항상 KEYS[]로 키를 전달하세요. numkeys 인자는 Redis에 KEYS 개수를 알려줍니다.

redis-cli
# KEYS[]: key names passed to the script
# ARGV[]: additional arguments (values, options)

# example: atomic increment with cap
EVAL "
  local current = tonumber(redis.call('GET', KEYS[1]) or 0)
  local max = tonumber(ARGV[1])
  if current >= max then
    return -1  -- cap reached
  end
  return redis.call('INCR', KEYS[1])
" 1 counter 100
# KEYS[1] = counter, ARGV[1] = 100

# example: move item between lists atomically
EVAL "
  local item = redis.call('RPOP', KEYS[1])
  if item then
    redis.call('LPUSH', KEYS[2], item)
  end
  return item
" 2 source_list dest_list

# NEVER hardcode key names in scripts (breaks cluster routing)
# always pass keys via KEYS[] so the cluster can route correctly

Lua로 원자적 연산

Lua 스크립트는 Redis에서 원자적 다중 명령 연산을 수행하는 표준 방법입니다(MULTI/EXEC 경쟁 없음). 비교 후 설정, 세마포어 획득, 큐 마이그레이션, 속도 제한에 모두 유리합니다. 스크립트는 실행 중 서버를 블록하므로 짧게 유지하고 많은 키를 순회하는 루프는 피하세요(다른 클라이언트가 지연될 수 있음). 아주 긴 작업에는 저장 프로시저처럼 선언하고 버전 관리하는 Redis Functions(7.0+)를 사용하세요.

redis-cli
# atomic compare-and-set (only update if value matches)
EVAL "
  local cur = redis.call('GET', KEYS[1])
  if cur == ARGV[1] then
    return redis.call('SET', KEYS[1], ARGV[2])
  end
  return 0
" 1 mykey "expected" "newvalue"

# atomic 'decrement if positive' (semaphore / rate limit)
EVAL "
  local val = tonumber(redis.call('GET', KEYS[1]) or 0)
  if val > 0 then
    redis.call('DECR', KEYS[1])
    return 1
  end
  return 0
" 1 semaphore

# atomic list pop + push (move between queues)
EVAL "
  local item = redis.call('RPOP', KEYS[1])
  if item then
    redis.call('LPUSH', KEYS[2], item)
  end
  return item
" 2 source_queue dest_queue

# atomic rate limiter (fixed window)
EVAL "
  local count = redis.call('INCR', KEYS[1])
  if count == 1 then
    redis.call('EXPIRE', KEYS[1], ARGV[1])
  end
  return count
" 1 rate:user:1 60

Redis Functions(7.0+)

Functions(7.0+)는 EVAL 스크립트를 개선합니다. 이름이 있고(해시뿐 아니라), 라이브러리로 구성되며, 재시작 후에도 유지됩니다(EVAL 스크립트는 휘발성). 관리와 배포가 더 쉽습니다. FCALL은 이름으로 함수를 호출합니다. Functions는 서버 측 원자적 로직을 추가하는 현대적 방법입니다. 스크립트처럼 복제를 위해 결정적이어야 합니다. FUNCTION DUMP/RESTORE로 백업과 마이그레이션이 가능합니다.

redis-cli
# FUNCTIONS are named, versioned Lua scripts (better than EVAL)
# register a function library
FUNCTION LOAD '#!lua name=mylib
redis.register_function("my_set",
  function(keys, args)
    return redis.call("SET", keys[1], args[1])
  end
)'

# call a function by name
FCALL my_set 1 mykey "hello"

# list loaded libraries
FUNCTION LIST
FUNCTION LIST WITHCODE   # include source

# get the function's code (for backup)
FUNCTION DUMP

# delete a library
FUNCTION DELETE mylib

# restore from a dump (for migration)
FUNCTION RESTORE <payload>

# functions persist across restarts (unlike EVAL scripts)
# they're saved in RDB/AOF
13

연결 관리

CLIENT LIST

CLIENT LIST는 연결된 모든 클라이언트의 주소, 연결 시간, 유휴 시간, 현재 명령, 플래그를 보여주므로 누수나 멈춘 클라이언트를 찾는 데 유용합니다. 'idle' 필드는 버려진 연결을 찾는 데 도움이 됩니다. 'cmd'는 마지막 명령을 보여주므로 느린 명령을 실행 중인 클라이언트를 찾을 수 있습니다. 'flags'는 클라이언트 유형을 나타냅니다(N=일반, M=마스터, S=슬레이브/복제본, P=pubsub, b=블록). 7.0+에서는 TYPE으로 필터링할 수 있습니다.

redis-cli
# list all connected clients
CLIENT LIST
# fields: id, addr, laddr, fd, name, age, idle, flags, db, cmd, ...

# filter by type (7.0+)
CLIENT LIST TYPE normal    # normal clients only
CLIENT LIST TYPE replica   # replicas
CLIENT LIST TYPE pubsub    # pub/sub subscribers

# filter by ID (7.0+)
CLIENT LIST ID 1 2 3

# output includes useful fields:
#   addr=10.0.0.1:12345   remote address
#   age=3600              seconds since connected
#   idle=0                seconds since last command
#   cmd=get               last command executed
#   db=0                  current database
#   flags=N               N=normal, M=master, S=slave, P=pubsub

# count connected clients
CLIENT LIST | wc -l

CLIENT SETNAME과 GETNAME

CLIENT SETNAME은 연결에 라벨을 붙여 CLIENT LIST에서 식별할 수 있게 합니다. 다중 서비스 환경에서 연결 누수를 디버깅하는 데 필수입니다. 앱에서 연결 직후 이름을 설정하세요(예: 'api-server:pid12345:pool1'). 이름은 CLIENT LIST의 'name' 필드에 나타나므로 멈추거나 누수된 연결이 어느 서비스 소유인지 쉽게 찾을 수 있습니다.

redis-cli
# name your connection (for identification in CLIENT LIST)
CLIENT SETNAME "my-app-worker-1"

# get the current connection's name
CLIENT GETNAME

# in application code, set the name immediately after connecting:
# redis-cli example:
redis-cli CLIENT SETNAME "debug-session"

# names appear in CLIENT LIST output:
CLIENT LIST
# ... name=my-app-worker-1 ...

# names are useful for:
# - identifying which app/pool a connection belongs to
# - finding leaks (connections that should have been closed)
# - debugging stuck clients
# - naming conventions: app:hostname:pid or pool:name

# names are limited to a reasonable length and cannot contain spaces

CLIENT KILL

CLIENT KILL은 클라이언트 연결을 강제로 끊어 멈추거나 누수된 연결을 제거합니다. ADDR(ip:port), ID, TYPE, USER(ACL)로 종료할 수 있습니다. MAXAGE(7.0+)는 N초 이상 유휴 상태인 클라이언트를 종료합니다. SKIPME yes(기본값)는 자신의 연결을 종료하지 않습니다. 먼저 CLIENT LIST로 대상을 찾은 뒤 CLIENT KILL로 끊으세요. 종료는 즉시 이루어집니다(정상 종료 절차 없음).

redis-cli
# kill a client by address
CLIENT KILL ADDR 10.0.0.1:12345

# kill a client by ID
CLIENT KILL ID 42

# kill by type (7.0+)
CLIENT KILL TYPE normal    # kill all normal clients
CLIENT KILL TYPE pubsub    # kill all pub/sub clients

# kill by user (ACL, 6.0+)
CLIENT KILL USER appuser

# kill by address with skip-me
CLIENT KILL ADDR 10.0.0.1:0 SKIPME yes   # don't kill myself

# kill all clients matching filters (7.0+)
CLIENT KILL TYPE normal MAXAGE 3600      # kill idle > 1h

# kill returns the number of clients killed
# use with caution — kills are immediate, no graceful shutdown

# common use: disconnect a stuck client consuming resources
CLIENT LIST
CLIENT KILL ID <id>

CLIENT ID와 INFO

CLIENT ID는 연결마다 재사용되지 않는 고유 정수를 반환하므로 로깅과 상관관계 추적에 유용합니다. CLIENT INFO는 자신의 연결에 대한 상세 정보를 제공합니다. CLIENT NO-EVICT(6.0+)는 클라이언트의 쓰기가 제거를 유발하지 않도록 보호합니다(중요한 쓰기에 유용). CLIENT REPLY는 서버 응답 여부를 제어합니다(대량 적재 시 OFF, 한 명령만 SKIP).

redis-cli
# get the current client's unique ID (never reused)
CLIENT ID

# get the current client's info (detailed)
CLIENT INFO
# id=42 addr=127.0.0.1:12345 laddr=127.0.0.1:6379 name= db=0 ...

# the ID is a monotonically increasing integer
# it's unique per connection and never reused
# useful for logging and tracking

# CLIENT NO-EVICT (6.0+): this client's writes won't trigger eviction
CLIENT NO-EVICT ON    # protect this client from eviction
CLIENT NO-EVICT OFF   # normal behavior

# CLIENT REPLY (6.0+): control reply mode
CLIENT REPLY ON       # normal replies
CLIENT REPLY OFF      # no replies
CLIENT REPLY SKIP     # skip reply for next command only

# CLIENT UNPAUSE: resume processing after CLIENT PAUSE
CLIENT UNPAUSE

CLIENT PAUSE

CLIENT PAUSE는 다른 모든 클라이언트의 명령 실행을 N밀리초 동안 막습니다. 안전한 스냅샷, 마이그레이션, 클러스터 페일오버에 유용합니다. WRITE 모드(7.0+)는 쓰기만 일시 중지하고 읽기는 계속 허용합니다(영향이 적음). 일시 중지한 클라이언트 자신은 블록되지 않습니다. 중지 중에는 대기 명령이 메모리를 소모하므로 짧게 유지하세요. CLIENT UNPAUSE는 즉시 재개합니다.

redis-cli
# pause all client processing for N milliseconds
CLIENT PAUSE 10000         # pause for 10 seconds
# all other clients' commands are queued, not executed

# pause modes (7.0+):
CLIENT PAUSE 10000 ALL        # pause all commands (default)
CLIENT PAUSE 10000 WRITE      # pause only writes (reads continue)

# resume processing immediately
CLIENT UNPAUSE

# use cases:
# - safe snapshot/migration (pause writes, take consistent backup)
# - cluster failover (pause to ensure clean handoff)
# - debugging (pause to inspect state)

# during pause:
# - commands from OTHER clients are queued (memory grows)
# - the pausing client can still run commands
# - paused commands execute when the pause ends

# check if a pause is active
CLIENT INFO | grep flags
# 'P' flag = paused

연결 제한과 타임아웃

maxclients는 동시 연결 수를 제한합니다(기본 10000). 앱 서버나 연결 풀이 많으면 늘리세요. timeout은 유휴 클라이언트를 끊습니다(0은 무제한, 안전을 위해 300초 권장). tcp-keepalive는 죽은 TCP 연결을 감지합니다(기본 300초). 각 클라이언트는 출력 버퍼 메모리를 소모하므로 INFO clients로 모니터링하세요. client-output-buffer-limit는 느린 클라이언트 하나가 서버 메모리를 모두 소모하지 않게 막습니다(pub/sub과 복제본에서 특히 중요).

redis-cli
# max concurrent clients
CONFIG GET maxclients        # default 10000
CONFIG SET maxclients 50000  # increase limit

# timeout: disconnect idle clients after N seconds
CONFIG GET timeout           # default 0 (never)
CONFIG SET timeout 300       # 5 minutes

# TCP keepalive (detect dead connections)
CONFIG GET tcp-keepalive     # default 300
CONFIG SET tcp-keepalive 60

# when maxclients is reached, new connections are rejected
# error: "ERR max number of clients reached"

# check current client count vs limit
INFO clients
# connected_clients:150
# blocked_clients:5
# maxclients:10000

# each connection uses memory (~a few KB for the output buffer)
# monitor for output buffer growth:
INFO clients | grep client_recent_max_output_buffer

# set output buffer limits (prevent one client from using all memory)
CONFIG GET client-output-buffer-limit
14

서버 관리

INFO 섹션

INFO는 기본 모니터링 명령으로 메모리, 클라이언트, 복제, 영속성, 통계를 한 번에 보고합니다. 출력을 줄이려면 섹션을 지정하세요(INFO memory). 주요 지표: used_memory_rss(실제 점유), mem_fragmentation_ratio(이상적 약 1.0-1.5), connected_clients, instantaneous_ops_per_sec, keyspace_hits/misses(캐시 적중률). TIME은 시계 동기화용 서버 시간을 반환합니다.

redis-cli
# comprehensive server information
INFO                  # all sections
INFO server           # version, uptime, config
INFO clients          # connected clients
INFO memory           # memory usage, fragmentation
INFO persistence      # RDB/AOF status
INFO stats            # ops/sec, hit rate, keyspace
INFO replication      # primary/replica state
INFO cpu              # CPU usage
INFO keyspace         # keys per database
INFO commandstats     # command frequency
INFO errorstats       # error frequency

# get a specific metric
INFO memory | grep used_memory_human
INFO stats | grep instantaneous_ops_per_sec
INFO replication | grep role

# check Redis version and mode
INFO server | grep redis_version
INFO server | grep redis_mode        # standalone, cluster, sentinel

# get server time
TIME                    # [unix_timestamp, microseconds]

CONFIG GET과 SET

CONFIG SET은 Redis를 재시작하지 않고 런타임에 설정을 바꾸므로 튜닝에 이상적입니다. CONFIG GET은 현재 값을 조회합니다(CONFIG GET *memory* 같은 패턴 사용). 흔한 런타임 조정: maxmemory + 제거 정책, slowlog 임계값, timeout, 인코딩 임계값. 모든 설정을 런타임에 바꿀 수 있는 것은 아닙니다(예: port, bind 주소는 재시작 필요). 운영 반영 전 스테이징에서 항상 테스트하세요.

redis-cli
# view config (runtime changes with CONFIG SET)
CONFIG GET maxmemory
CONFIG GET maxmemory-policy
CONFIG GET save
CONFIG GET appendonly
CONFIG GET requirepass

# change config at runtime (no restart needed)
CONFIG SET maxmemory 4gb
CONFIG SET maxmemory-policy allkeys-lru
CONFIG SET slowlog-log-slower-than 10000   # 10ms in microseconds
CONFIG SET timeout 300

# view all config (large output)
CONFIG GET *

# get a specific pattern
CONFIG GET *max*
CONFIG GET *timeout*

# common runtime tweaks:
CONFIG SET maxclients 20000
CONFIG SET hash-max-listpack-entries 256
CONFIG SET appendfsync everysec

CONFIG REWRITE

CONFIG REWRITE는 런타임 CONFIG SET 변경을 redis.conf에 영구 저장합니다. 파일이 제자리에서 갱신되며 주석과 구조가 유지됩니다. 런타임 변경과 재시작 후 유지 사이의 간극을 메웁니다. REWRITE 전에 redis.conf를 백업하세요(문제가 거의 없지만 안전이 우선). redis.conf를 버전 관리하면 시간에 따른 변경을 추적하고 감사할 수 있습니다.

redis-cli
# persist config changes to redis.conf
CONFIG REWRITE

# after CONFIG SET maxmemory 4gb
# CONFIG REWRITE updates redis.conf to include:
#   maxmemory 4gb

# the original redis.conf is updated in-place
# comments and structure are preserved

# view the config file path
CONFIG GET *

# typical redis.conf (production):
# bind 127.0.0.1
# protected-mode yes
# port 6379
# maxmemory 4gb
# maxmemory-policy allkeys-lru
# save 3600 1
# appendonly yes
# appendfsync everysec
# tcp-keepalive 300
# timeout 0

# always back up redis.conf before CONFIG REWRITE

SLOWLOG

SLOWLOG는 설정한 임계값(기본 10ms = 10000us)보다 느린 명령을 기록하므로 지연 원인을 찾는 데 유용합니다. 임계값을 SLO에 맞추세요(예: 5ms). 흔한 느린 명령: KEYS, 거대한 집합의 SMEMBERS, 거대한 해시의 HGETALL, 큰 데이터의 SORT. slowlog-max-len은 로그 크기를 제한합니다(기본 128). 임계값을 0으로 두면 모든 명령을 기록합니다(디버깅 전용, 오버헤드 큼).

redis-cli
# configure slow log (threshold in microseconds)
CONFIG SET slowlog-log-slower-than 10000   # 10ms (10000 us)
CONFIG SET slowlog-max-len 128             # keep last 128 entries

# view slow commands
SLOWLOG GET          # last 10 (default)
SLOWLOG GET 5        # last 5
SLOWLOG GET 0        # all entries

# each entry:
# 1) id              unique ID
# 2) timestamp       Unix time
# 3) duration        microseconds
# 4) command         the command and args
# 5) client          address:port
# 6) client name     if set

# slowlog length
SLOWLOG LEN

# reset (clear all entries)
SLOWLOG RESET

# set threshold to 0 to log ALL commands (debugging)
# set to -1 to disable
CONFIG SET slowlog-log-slower-than 0

MONITOR

MONITOR는 모든 클라이언트의 모든 명령을 실시간으로 스트리밍합니다. 강력한 디버깅 도구지만 성능에 매우 큰 영향을 줍니다(처리량이 대략 절반으로 줄어듦). 꼭 필요한 경우가 아니면 운영 환경에서 MONITOR를 사용하지 말고, 사용하더라도 짧게 끝내세요. 스테이징에는 완벽합니다. MONITOR를 연결하고 문제를 재현해 앱이 실제로 보내는 명령을 확인하세요. 운영 환경에서는 SLOWLOG, LATENCY MONITOR, INFO commandstats를 사용하세요.

redis-cli
# MONITOR: real-time log of ALL commands (debugging only!)
MONITOR
# every command from every client is printed:
# 1700000000.123456 [0 10.0.0.1:12345] "SET" "key" "value"
# 1700000000.123567 [0 10.0.0.1:12345] "GET" "key"

# to stop monitoring, send any non-MONITOR command or disconnect
# press Ctrl+C in redis-cli

# WARNING: MONITOR has a HUGE performance impact
# it roughly halves throughput — use only for debugging

# use cases:
# - debugging what commands an app is sending
# - auditing command patterns
# - finding the source of unexpected writes

# safer alternatives for production:
# - SLOWLOG (only slow commands)
# - LATENCY MONITOR (specific events)
# - COMMANDSTATS in INFO (command frequency)

# MONITOR is best used in a staging/dev environment

LATENCY 모니터링

LATENCY MONITOR는 지연 이벤트를 추적합니다(임계값 설정, 예: 100ms). LATENCY DOCTOR는 최근 이벤트를 분석하고 해결책을 제안하므로 진단의 좋은 출발점입니다. 흔한 이벤트: 'command'(느린 명령), 'fork'(BGSAVE 포크 지연), 'expire-cycle'(만료 스윕), 'aof-write'(AOF fsync 지연). LATENCY GRAPH는 ASCII 타임라인을 보여줍니다. 임계값을 SLO에 맞추고 정기적으로 모니터링하세요.

redis-cli
# enable latency monitoring (threshold in ms)
CONFIG SET latency-monitor-threshold 100   # 100ms

# view latency events
LATENCY HISTORY event-name
LATENCY LATEST                            # most recent events
LATENCY HISTORY command
LATENCY HISTORY expire-cycle

# ASCII art graph of an event
LATENCY GRAPH command

# human-readable diagnosis and recommendations
LATENCY DOCTOR

# reset latency data
LATENCY RESET
LATENCY RESET event-name

# common events to monitor:
#   command         slow commands
#   fast-command    slow O(1) commands
#   expire-cycle    expiration cycle taking too long
#   fork            BGSAVE/BGREWRITEAOF fork taking too long
#   aof-write       AOF write delays
#   unlink          async delete delays

# check current threshold
CONFIG GET latency-monitor-threshold
15

클러스터

CLUSTER INFO

CLUSTER INFO는 클러스터 상태 요약을 제공합니다. cluster_state는 'ok'여야 하고(16384개 슬롯 모두 커버), cluster_slots_ok도 16384여야 합니다. cluster_known_nodes는 전체 노드 수, cluster_size는 프라이머리 수입니다. cluster_state가 'fail'이면 일부 슬롯을 사용할 수 없다는 뜻입니다(프라이머리와 복제본이 모두 다운된 경우가 많음). 어느 노드에서든 확인할 수 있으며 정보는 클러스터 전체에 해당합니다.

redis-cli
# cluster-wide health
CLUSTER INFO
# key fields:
#   cluster_state:ok              # ok or fail
#   cluster_slots_assigned:16384  # total slots
#   cluster_slots_ok:16384        # slots covered
#   cluster_known_nodes:6         # total nodes
#   cluster_size:3                # number of primaries
#   cluster_current_epoch:7
#   cluster_my_epoch:1

# cluster_state:ok means all slots are covered
# cluster_state:fail means some slots are unavailable

# check from any node in the cluster
redis-cli -p 7000 CLUSTER INFO

# other cluster commands require being in cluster mode
# (redis-server --cluster-enabled yes)

CLUSTER NODES

CLUSTER NODES는 확정적인 토폴로지 뷰로, 노드마다 한 줄에 ID, 주소, 역할(master/slave), 따르는 마스터(복제본의 경우), 슬롯 범위를 보여줍니다. 비정상 노드를 나타내는 'fail' 또는 'fail?' 플래그를 찾으세요. 슬롯 범위는 어느 프라이머리가 어떤 해시 슬롯(0-16383)을 소유하는지 보여줍니다. CLUSTER SHARDS(7.0+)는 샤드(프라이머리 + 복제본)별로 노드를 묶습니다.

redis-cli
# view the full cluster topology
CLUSTER NODES
# each line is a node:
# <id> <addr:port@cport> <flags> <master> <ping-sent> <pong-recv> <epoch> <link> <slots>

# flags include:
#   M  = master (primary)
#   S  = slave (replica)
#   mymaster = the node this replica follows
#   fail? = suspected down
#   fail  = confirmed down
#   handshake = new node joining
#   nofailover = failover disabled

# example output:
# 1a2b... 127.0.0.1:7000@17000 myself,master - 0 0 1 connected 0-5460
# 3c4d... 127.0.0.1:7001@17001 master - 0 0 2 connected 5461-10922
# 5e6f... 127.0.0.1:7002@17002 master - 0 0 3 connected 10923-16383
# 7g8h... 127.0.0.1:7003@17003 slave 1a2b... 0 0 4 connected

# count nodes by type
CLUSTER NODES | grep -c master
CLUSTER NODES | grep -c slave

# Redis 7.0+: shard view
CLUSTER SHARDS

CLUSTER KEYSLOT과 COUNTKEYSINSLOT

CLUSTER KEYSLOT은 키가 매핑되는 슬롯을 보여줍니다(CRC16 % 16384). 해시 태그({...})는 관련 키를 같은 슬롯으로 강제하므로 클러스터에서 다중 키 연산(MGET, 트랜잭션, Lua 스크립트)에 필수입니다. redis-cli -c(클러스터 모드)를 쓰면 MOVED 리다이렉트를 자동으로 따라갑니다. CLUSTER GETKEYSINSLOT은 슬롯 내 키를 조회합니다(리샤딩 중 사용).

redis-cli
# get the hash slot for a key
CLUSTER KEYSLOT mykey       # e.g., 1234
# CRC16(key) % 16384

# count keys in a specific slot (on the owning node)
CLUSTER COUNTKEYSINSLOT 1234

# get keys in a slot (must be run on the slot's owning node)
CLUSTER GETKEYSINSLOT 1234 10   # up to 10 keys

# in a cluster, keys must be on the same slot for multi-key ops
# use hash tags to force keys to the same slot:
SET {user:1}:profile "alice"
SET {user:1}:cart "items"
# both map to the same slot (the part inside {})

# CLUSTER KEYSLOT {user:1}:profile
# CLUSTER KEYSLOT {user:1}:cart
# same result -> same slot -> same shard

# if you access a key on the wrong node, you get a MOVED redirect:
# (error) MOVED 1234 127.0.0.1:7000
# redis-cli -c follows redirects automatically

해시 태그

해시 태그({...})는 키를 같은 슬롯으로 강제해 클러스터에서 다중 키 연산을 가능하게 합니다. 하지만 신중히 사용하세요. 하나의 태그를 과도하게 쓰면(예: {users}:1, {users}:2) 한 샤드에 핫스팟이 생깁니다. 접근 패턴에 맞춰 해시 태그를 설계하세요. 함께 접근하는 키(사용자 데이터, 주문 항목)는 묶고 관련 없는 키는 분리하세요. 이것이 클러스터 데이터 모델링의 핵심 과제입니다.

redis-cli
# hash tags: the substring inside {} determines the slot
# {user:1}:profile and {user:1}:cart share a slot

# enabling multi-key operations in a cluster:
MSET {user:1}:name "Alice" {user:1}:age 30   # OK (same slot)
MSET user:1:name "Alice" user:2:age 30       # CROSSSLOT error

# transactions across keys (must be same slot)
WATCH {order:1}:items
MULTI
HINCRBY {order:1}:items product:1 1
HINCRBY {order:1}:total 10
EXEC

# Lua scripts accessing multiple keys (all keys must share a slot)
EVAL "..." 2 {user:1}:a {user:1}:b

# design hash tags carefully:
# - too broad -> hotspots (one shard overloaded)
#   e.g., {users}:1, {users}:2 -> all on one shard (bad!)
# - too narrow -> can't do multi-key ops
#   e.g., user:1:a, user:1:b -> different slots (can't MGET)

# good: {user:1}:* groups one user's data on one shard
# bad:  {all-users}:* puts everyone on one shard

CLUSTER FAILOVER

프라이머리에 cluster-node-timeout(기본 15초) 이상 접근할 수 없으면 클러스터 페일오버가 자동으로 일어납니다. 수동 페일오버는 유지보수(무중단 업그레이드)용입니다. FAILOVER는 정상 방식(복제 동기화 대기), FORCE는 동기화 생략(빠르지만 약간의 데이터 손실 위험), TAKEOVER는 합의 우회(비상시에만, 스플릿 브레인 위험)입니다. 페일오버 후 이전 프라이머리는 복귀 시 복제본이 됩니다. 운영 환경에서는 항상 복제본과 함께 실행하세요.

redis-cli
# when a primary fails, its replica is promoted automatically
# manual failover (for maintenance), run on the REPLICA:
redis-cli -p 7001 CLUSTER FAILOVER         # graceful (waits for sync)
redis-cli -p 7001 CLUSTER FAILOVER FORCE   # without primary agreement (faster)
redis-cli -p 7001 CLUSTER FAILOVER TAKEOVER # force, may split brain (emergency)

# graceful failover steps:
# 1. replica stops syncing from master
# 2. master stops accepting writes
# 3. replica catches up on replication offset
# 4. replica is promoted to master
# 5. cluster is updated with new master info
# 6. old master becomes a replica when it returns

# CLUSTER RESET resets a node (HARD removes all data)
CLUSTER RESET HARD
CLUSTER RESET SOFT

# check failover status
CLUSTER INFO | grep cluster_state

# rolling upgrade pattern:
# for each replica: CLUSTER FAILOVER (becomes master), upgrade old master

redis-cli --cluster 도구

redis-cli --cluster 도구는 생성, 리샤딩, 리밸런싱, 노드 추가/제거, 상태 확인, 복구 같은 복잡한 클러스터 작업을 처리합니다. 변경 후 클러스터 상태 확인에는 --cluster check를 사용하세요. --cluster fix는 사소한 문제(고아 슬롯 등)를 자동 복구합니다. --cluster call은 모든 노드에서 명령을 실행합니다. 운영 작업에는 수동 CLUSTER 명령 대신 이 도구를 사용하세요.

redis-cli
# create a cluster (6 nodes: 3 primaries + 3 replicas)
redis-cli --cluster create \
  host1:7000 host2:7000 host3:7000 \
  host1:7001 host2:7001 host3:7001 \
  --cluster-replicas 1

# check cluster health
redis-cli --cluster check host1:7000

# repair issues
redis-cli --cluster fix host1:7000

# reshard (move slots between nodes)
redis-cli --cluster reshard host1:7000
# prompts for: how many slots, target node, source nodes

# rebalance slots across all nodes
redis-cli --cluster rebalance host1:7000

# add a new node
redis-cli --cluster add-node newhost:7000 host1:7000

# add a replica
redis-cli --cluster add-node newhost:7001 host1:7000 \
  --cluster-slave --cluster-master-id <nodeId>

# remove a node (migrates its slots first)
redis-cli --cluster del-node host1:7000 <nodeId>

# call a command on all nodes
redis-cli --cluster call host1:7000 INFO server
16

Sentinel(고가용성)

Sentinel 설정

Sentinel은 샤딩 없이 고가용성을 제공합니다. 프라이머리를 모니터링하고 장애 시 복제본을 승격하며 클라이언트를 재구성합니다. 쿼럼(마지막 숫자)은 프라이머리 다운에 동의해야 하는 Sentinel 수입니다. N개면 (N/2)+1로 설정하세요. 장애 허용을 위해 서로 다른 머신에 Sentinel 3개를 배포하세요. down-after-milliseconds는 네트워크 지터보다 커야 하며, 너무 작으면 잘못된 페일오버가 발생합니다.

redis-cli
# Sentinel monitors a primary + replicas, handles failover
# sentinel.conf (port 26379):
sentinel monitor mymaster 192.168.1.10 6379 2
# name, host, port, quorum (number of sentinels to agree on failure)

sentinel down-after-milliseconds mymaster 30000   # 30s to declare down
sentinel failover-timeout mymaster 180000         # 3min failover timeout
sentinel parallel-syncs mymaster 1                # replicas to resync in parallel

# start a sentinel:
redis-sentinel /etc/redis/sentinel.conf
# or:
redis-server /etc/redis/sentinel.conf --sentinel

# deploy at least 3 sentinels (odd number) for quorum
# sentinels communicate with each other and the Redis nodes

# connect to a sentinel to find the current primary:
redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster

# sentinel auto-discovers other sentinels and replicas

SENTINEL masters와 replicas

SENTINEL masters는 모니터링 중인 모든 프라이머리를 나열하고, SENTINEL master <name>은 세부 정보(num-slaves, num-other-sentinels 포함)를 제공합니다. SENTINEL replicas는 복제본을, SENTINEL sentinels는 피어 Sentinel을 보여줍니다. ckquorum은 쿼럼에 충분한 Sentinel이 있는지 확인하므로 모니터링에서 실행하세요. 모든 주요 Redis 클라이언트 라이브러리가 Sentinel을 기본 지원합니다(Sentinel에 질의해 현재 프라이머리를 찾음).

redis-cli
# query sentinel state
redis-cli -p 26379 SENTINEL masters          # all monitored primaries
redis-cli -p 26379 SENTINEL master mymaster  # details of one primary
# fields: name, ip, port, runid, role, ...
#   num-slaves, num-other-sentinels
#   quorum, down-after-milliseconds
#   failover-timeout, parallel-syncs

# list replicas of a master
redis-cli -p 26379 SENTINEL replicas mymaster

# list other sentinels monitoring the same master
redis-cli -p 26379 SENTINEL sentinels mymaster

# count monitoring sentinels (should be >= quorum)
redis-cli -p 26379 SENTINEL sentinels mymaster | grep -c name

# check the number of OK sentinels
SENTINEL ckquorum mymaster
# "OK 3 usable Sentinels. Quorum and failover authorization can be reached"
# or "NOQUORUM" warning (not enough sentinels)

SENTINEL get-master-addr-by-name

SENTINEL get-master-addr-by-name은 현재 프라이머리의 IP와 포트를 반환합니다. 클라이언트는 이를 호출해 프라이머리를 발견한 뒤 연결합니다. 페일오버가 일어나면 Sentinel은 새 프라이머리 주소를 반환합니다. 클라이언트는 +switch-master 이벤트를 구독해 페일오버를 즉시 알 수 있습니다. 이 발견 패턴은 모든 주요 Redis 클라이언트 라이브러리의 Sentinel 모드에 내장되어 있습니다.

redis-cli
# find the current primary address
redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster
# 1) "192.168.1.10"
# 2) "6379"

# clients use this to discover the current primary
# on failover, the sentinel returns the new primary's address

# clients should connect to sentinels, NOT directly to the primary
# libraries: redis-py, jedis, ioredis all support sentinel mode

# example client connection (pseudo-code):
# 1. connect to a sentinel
# 2. SENTINEL get-master-addr-by-name mymaster
# 3. connect to the returned primary
# 4. on connection error, repeat from step 1

# monitor for failover events
redis-cli -p 26379 SUBSCRIBE +switch-master
# publishes: mymaster 192.168.1.10 6379 192.168.1.11 6379

# other events:
redis-cli -p 26379 SUBSCRIBE +failover-state
redis-cli -p 26379 SUBSCRIBE +sdown
redis-cli -p 26379 SUBSCRIBE +odown

SENTINEL failover

SENTINEL failover는 수동 페일오버를 트리거합니다(롤링 업그레이드/유지보수용). 자동 페일오버는 프라이머리가 down-after-milliseconds보다 오래 다운되면 발생합니다. 페일오버는 자동이지만 몇 초의 쓰기 중단이 생깁니다. 선출된 Sentinel 리더가 가장 최신 복제본을 승격합니다. 이전 프라이머리가 복귀하면 복제본이 되며, 네트워크 분할 중 받은 쓰기는 사라집니다(스플릿 브레인 위험).

redis-cli
# force a manual failover (for maintenance)
SENTINEL failover mymaster
# triggers failover: promotes a replica to primary

# the failover process:
# 1. sentinels mark primary SDOWN (subjectively down)
# 2. quorum agrees -> ODOWN (objectively down)
# 3. a sentinel is elected leader
# 4. leader picks the best replica (most up-to-date)
# 5. promotes the replica: REPLICAOF NO ONE
# 6. reconfigures other replicas to follow the new primary
# 7. updates sentinel configs with the new primary address
# 8. clients reconnect via sentinel discovery

# during failover, writes fail briefly (seconds)
# reads from replicas continue (if the app uses them)

# the old primary, when it returns, is reconfigured as a replica
# of the new primary (its writes during partition are lost)

# monitor failover events:
redis-cli -p 26379 SUBSCRIBE +switch-master
redis-cli -p 26379 SUBSCRIBE +failover-*

Sentinel 쿼럼과 모니터링

쿼럼은 페일오버를 트리거하기 전에 프라이머리 다운에 동의해야 하는 Sentinel 수입니다. N개면 과반수(N/2+1)로 설정하세요. ckquorum은 충분한지 확인합니다. down-after-milliseconds는 네트워크 지터보다 커야 합니다(30초면 안전). failover-timeout은 페일오버 소요 시간을 제한합니다. parallel-syncs는 동시에 재동기화할 복제본 수를 제어합니다(1은 안전하지만 느림). Sentinel은 토폴로지 변경 시 설정을 자동 갱신합니다.

redis-cli
# quorum: number of sentinels that must agree a master is down
# set in sentinel monitor command:
sentinel monitor mymaster 192.168.1.10 6379 2
#                                          ^ quorum = 2

# for 3 sentinels: quorum = 2 (majority)
# for 5 sentinels: quorum = 3 (majority)

# check quorum status
SENTINEL ckquorum mymaster
# "OK 3 usable Sentinels" or "NOQUORUM"

# tune down-after-milliseconds (time before declaring down)
sentinel down-after-milliseconds mymaster 30000   # 30s default

# tune failover-timeout (max time for failover to complete)
sentinel failover-timeout mymaster 180000   # 3min default

# parallel-syncs: how many replicas resync simultaneously
sentinel parallel-syncs mymaster 1   # 1 at a time (safe, slow)

# view sentinel configuration
SENTINEL masters
SENTINEL master mymaster

# reset a master's state (clears discovered replicas/sentinels)
SENTINEL reset mymaster

# Sentinel automatically updates its config file when topology changes
17

모니터링

MONITOR 명령

MONITOR는 모든 클라이언트의 모든 명령을 실시간으로 스트리밍합니다. 출력 형식은 timestamp [db client_addr] "command" "args"입니다. 앱이 실제로 보내는 명령을 디버깅하는 데 유용합니다. 하지만 처리량이 대략 절반으로 줄므로 스테이징/개발 환경이나 짧은 운영 디버깅에만 사용하세요. grep으로 특정 패턴을 필터링할 수 있습니다. 운영 모니터링에는 SLOWLOG, INFO commandstats, LATENCY MONITOR를 사용하세요.

redis-cli
# MONITOR: real-time log of ALL commands (debugging only!)
MONITOR
# every command from every client is printed:
# 1700000000.123456 [0 10.0.0.1:12345] "SET" "key" "value"
# 1700000000.123567 [0 10.0.0.1:12345] "GET" "key"

# format: <unix_time> [<db> <addr>] "<cmd>" "<arg>" ...
# the [0 ...] shows which database and client

# to stop monitoring: Ctrl+C or send any command

# filter for specific patterns (in another terminal):
redis-cli MONITOR | grep "SET"
redis-cli MONITOR | grep "10.0.0.1"
redis-cli MONITOR | grep -E "(SET|DEL)"

# WARNING: MONITOR roughly halves throughput
# use only for debugging, never in production

# safer alternatives:
# - SLOWLOG (only slow commands)
# - INFO commandstats (command frequency)
# - LATENCY MONITOR (latency events)

LATENCY 모니터링

LATENCY MONITOR는 이벤트 유형별 지연 급증을 추적합니다. 임계값(예: 100ms)을 설정하면 Redis가 이를 초과한 이벤트를 기록합니다. LATENCY DOCTOR는 최근 이벤트를 분석하고 해결책을 제안하므로 진단의 좋은 출발점입니다. LATENCY GRAPH는 ASCII 타임라인을 보여줍니다. 흔한 원인: 'fork'(큰 데이터셋의 BGSAVE), 'expire-cycle'(대량 만료), 'aof-fsync-always'(AOF fsync). 임계값을 SLO에 맞추고 정기적으로 모니터링하세요.

redis-cli
# enable latency monitoring (threshold in ms)
CONFIG SET latency-monitor-threshold 100   # 100ms

# view recent latency events
LATENCY LATEST
# event, timestamp, last latency, max latency

# history of an event
LATENCY HISTORY command
LATENCY HISTORY expire-cycle
LATENCY HISTORY fork

# ASCII art graph
LATENCY GRAPH command

# human-readable diagnosis and recommendations
LATENCY DOCTOR

# reset latency data
LATENCY RESET
LATENCY RESET command

# common events:
#   command         slow commands (over threshold)
#   fast-command    slow O(1)/O(log N) commands
#   expire-cycle    key expiration sweep too slow
#   fork            BGSAVE/BGREWRITEAOF fork delay
#   aof-fsync-always  AOF fsync delay
#   unlink          async delete delay

# check threshold
CONFIG GET latency-monitor-threshold

MEMORY DOCTOR와 STATS

MEMORY USAGE는 한 키의 바이트를 보고합니다(정확히 하려면 SAMPLES 0). MEMORY STATS는 상세한 할당자 통계를 제공합니다. MEMORY DOCTOR는 자동 진단(단편화, 큰 키 등 탐지)을 제공합니다. mem_fragmentation_ratio를 주시하세요. 1.5 초과는 메모리 낭비(단편화), 1 미만은 Redis가 스와핑 중(지연에 치명적)이라는 뜻입니다. MEMORY PURGE는 OS에 메모리를 반환하려 시도합니다. 능동 조각 모음(4.0+)은 단편화된 메모리를 자동 회수합니다.

redis-cli
# MEMORY USAGE: bytes used by a single key
MEMORY USAGE mykey
MEMORY USAGE bigset SAMPLES 0   # exact (default samples for large keys)

# MEMORY STATS: detailed allocator stats
MEMORY STATS

# MEMORY DOCTOR: automated memory diagnosis
MEMORY DOCTOR

# MEMORY MALLOC-STATS: low-level allocator stats (jememalloc)
MEMORY MALLOC-STATS

# check total memory used
INFO memory | grep used_memory_human

# key metrics to watch:
#   used_memory             logical bytes used
#   used_memory_rss         RSS from OS (real footprint)
#   used_memory_peak        peak usage
#   mem_fragmentation_ratio >1.5 = fragmentation, <1 = swapping (bad!)

# MEMORY PURGE: attempt to free memory back to OS
MEMORY PURGE

# active defragmentation (4.0+)
CONFIG SET activedefrag yes

DEBUG 명령

DEBUG 명령은 진단과 테스트용이므로 주의해서 사용하세요. DEBUG SLEEP은 앱이 지연을 어떻게 처리하는지 테스트합니다(서버 블록). DEBUG OBJECT는 키의 내부 인코딩과 참조 수를 보여줍니다. DEBUG RELOAD는 데이터셋을 저장, 플러시, 재로드합니다(영속성 테스트에 유용). 강력하지만 위험하므로 운영 환경에서는 ACL로 제한하세요(-@admin 또는 -@dangerous 카테고리). 영향을 이해하지 못한 채 운영 프라이머리에서 DEBUG를 실행하지 마세요.

redis-cli
# DEBUG SLEEP: block the server for N seconds (testing only!)
DEBUG SLEEP 2             # blocks for 2 seconds (testing latency)

# DEBUG OBJECT: raw internal info about a key
DEBUG OBJECT mykey
# Value at:0x7f... refcount:1 encoding:embstr serializedlength:12 ...

# DEBUG SET-ACTIVE-EXPIRE: toggle expiration sweeps
DEBUG SET-ACTIVE-EXPIRE 0  # disable expiration sweeps (debugging)
DEBUG SET-ACTIVE-EXPIRE 1  # re-enable

# DEBUG JMAP: memory map (jemalloc)
DEBUG JMAP

# DEBUG CHANGE-REPL-ID: change replication ID (advanced)
DEBUG CHANGE-REPL-ID

# DEBUG RELOAD: save RDB, flush, reload from RDB (testing)
DEBUG RELOAD

# DEBUG LOADAOF: reload from AOF (testing)
DEBUG LOADAOF

# WARNING: DEBUG commands can be dangerous
# use ACL to restrict them in production:
# ACL SETUSER default -@admin

redis-cli --latency

redis-cli --latency는 왕복 시간을 계속 측정하므로 네트워크 성능 기준선을 잡는 데 필수입니다. --latency-history는 15초마다 롤링 통계를 기록합니다(-i로 간격 변경). --latency-dist는 히스토그램을 보여줍니다(지터와 꼬리 지연 시각화). 클러스터 모드에서는 각 노드의 지연을 따로 확인하세요. 기준선을 잡은 뒤 급증을 모니터링하세요. localhost에서 1ms 초과 지연은 문제(CPU, 메모리 압박, 느린 명령)를 뜻합니다.

redis-cli
# continuous latency measurement (round-trip time)
redis-cli --latency
# output: min: 0, max: 1, avg: 0.27 (3421 samples)

# latency history (rolling, every N seconds)
redis-cli --latency-history
# default interval: 15 seconds
# output: min: 0, max: 2, avg: 0.31 (1500 samples) -- 15.01 seconds

# custom interval (1 second)
redis-cli --latency-history -i 1

# latency distribution (histogram)
redis-cli --latency-dist
# shows a visual histogram of latency distribution

# latency to a remote host
redis-cli -h remote-host --latency

# use cases:
# - baseline your network latency
# - detect network issues (jitter, spikes)
# - compare latency before/after config changes
# - monitor latency over time with --latency-history

# for cluster mode, check latency to each node:
redis-cli -h node1 -p 7000 --latency &
redis-cli -h node2 -p 7000 --latency &

redis-cli --stat

redis-cli --stat는 Redis용 'top'과 같습니다. 키, 메모리, 클라이언트, 블록된 클라이언트, 초당 요청, 연결을 갱신하며 요약해 보여줍니다. 요청 옆의 (+N)은 마지막 샘플 이후 증가분입니다. 빠른 상태 확인과 이상 징후(메모리 증가, 클라이언트 누수, 요청 급증) 발견에 사용하세요. 'child' 열은 BGSAVE/BGREWRITEAOF 자식 프로세스 실행 여부를 보여줍니다.

redis-cli
# --stat: continuous server stats (like top for Redis)
redis-cli --stat
# output (refreshes every second):
# ------- data ------ --------------------- load -------------------- - child -
# keys       mem      clients blocked requests            connections
# 1000       1.50M    50      0       12345 (+12)         1000

# --stat shows:
#   keys       total keys in the db
#   mem        memory usage
#   clients    connected clients
#   blocked    blocked clients (BLPOP, etc.)
#   requests   total requests (+N since last sample)
#   connections total connections since start
#   child      child process info (BGSAVE/BGREWRITEAOF)

# custom interval (every 5 seconds)
redis-cli --stat -i 5

# monitor a remote server
redis-cli -h host --stat

# use cases:
# - quick health check (are clients/memory/keys growing?)
# - spot traffic spikes (requests/second)
# - monitor during load tests
# - detect connection leaks (clients increasing steadily)

# combine with --no-raw for machine-readable output
18

보안

AUTH(레거시 비밀번호)

AUTH는 레거시 단일 비밀번호 인증입니다(Redis 6 이전). Redis 6+에서는 ACL 사용자(AUTH username password)를 사용하세요. -a 플래그는 셸 히스토리에 비밀번호를 노출하므로 REDISCLI_AUTH 환경 변수를 권장합니다. 항상 강력한 비밀번호(무작위 64자 이상)를 사용하세요. 운영 환경에서는 심층 방어를 위해 AUTH를 TLS, 네트워크 제한(bind/firewall), ACL 기반 최소 권한과 함께 사용하세요.

redis-cli
# set a password (simple, legacy)
CONFIG SET requirepass "strongpassword"

# authenticate (legacy, before Redis 6)
AUTH "strongpassword"
# OK

# authenticate as a specific user (Redis 6+ ACL)
AUTH appuser "secretpassword"
# OK

# connect with password via CLI
redis-cli -a "strongpassword"
redis-cli -a "strongpassword" --no-auth-warning  # suppress warning

# safer: use environment variable
export REDISCLI_AUTH="strongpassword"
redis-cli   # reads REDISCLI_AUTH automatically

# remove password
CONFIG SET requirepass ""

# AUTH returns ERR if the password is wrong
# after AUTH, all commands work normally

ACL SETUSER

Redis 6+ ACL은 단일 비밀번호 모델을 대체하며 범위가 지정된 권한을 가진 사용자를 만듭니다. 문법: on(활성화), >password, ~pattern(키 패턴), +command/-command, +@category/-@category(예: +@read, -@dangerous). 앱마다 최소 권한 사용자를 만드세요. default 사용자는 항상 존재하므로 강력한 비밀번호를 설정하거나 제한하세요. 영속성을 위해 ACL을 파일에 저장하세요(ACL SAVE).

redis-cli
# Redis 6+: ACL system with users and permissions
# create a user with limited access
ACL SETUSER appuser on >secretpassword ~app:* +get +set +del -@dangerous
# on = enabled
# >password = set password
# ~pattern = key patterns this user can access
# +command = allowed commands
# -command = denied commands
# +@category / -@category = allow/deny command categories

# categories: @read, @write, @admin, @dangerous, @keyspace, @connection, etc.

# create a read-only user
ACL SETUSER readonly on >pass ~* +@read -@dangerous

# create an admin user
ACL SETUSER admin on >adminpass ~* +@all

# create a user for a specific app (restricted keys)
ACL SETUSER app1 on >pass ~app1:* +@read +@write +@connection -@dangerous

# the default user (always exists)
ACL SETUSER default on >defaultpass ~* +@all -@dangerous

ACL LIST와 GETUSER

ACL LIST는 모든 사용자를 간결한 규칙 형식으로 보여줍니다. ACL GETUSER는 한 사용자의 상세 권한(해시된 비밀번호, 허용/거부 명령, 키 패턴 포함)을 제공합니다. ACL WHOAMI는 현재 사용자를 반환합니다. ACL LOG(7.0+)는 거부된 명령과 인증 실패를 기록하므로 보안 감사에 유용합니다. ACL SAVE/LOAD는 재시작 후 유지를 위해 ACL 파일을 관리합니다.

redis-cli
# list all users (compact rules)
ACL LIST
# 1) "user default on nopass ~* +@all"
# 2) "user appuser on #abc123... ~app:* +get +set +del -@dangerous"

# view a user's detailed permissions
ACL GETUSER appuser
# flags, passwords, commands, keys, channels, selectors

# view current user
ACL WHOAMI
# "appuser"

# view all users (just names, 7.0+)
ACL USERS

# delete a user
ACL DELUSER appuser

# save ACLs to a file (persists across restarts)
ACL SAVE

# reload ACLs from file
ACL LOAD

# aclfile in redis.conf:
#   aclfile /etc/redis/users.acl

# view current user's rules
ACL LOG        # security audit log (7.0+)
ACL LOG RESET  # clear the audit log

ACL WHOAMI와 DELUSER

ACL WHOAMI는 현재 사용자를 식별합니다. ACL DELUSER는 사용자를 삭제하고 활성 연결도 끊습니다. 사용자를 'off'로 설정하면 규칙을 삭제하지 않고 일시적으로 비활성화하므로 접근을 정지시킬 때 유용합니다. ACL LOG는 보안 이벤트(거부된 명령, 인증 실패)를 기록하므로 의심스러운 활동을 모니터링하세요. ACL SETUSER >newpass로 비밀번호를 정기적으로 교체하세요.

redis-cli
# get the current authenticated user
ACL WHOAMI
# "appuser"

# switch user (re-authenticate)
AUTH adminuser "adminpass"
ACL WHOAMI
# "adminuser"

# delete a user (disconnects their clients)
ACL DELUSER tempuser

# temporarily disable a user (keeps the rules, blocks login)
ACL SETUSER appuser off
# the user cannot authenticate, but their rules are preserved
# re-enable:
ACL SETUSER appuser on

# rotate a user's password
ACL SETUSER appuser >newpassword

# remove a user's password
ACL SETUSER appuser <secretpassword  # remove this password
# or remove all passwords:
ACL SETUSER appuser resetpass

# view the audit log (denied commands, auth failures)
ACL LOG
ACL LOG COUNT 5  # last 5 entries
ACL LOG RESET    # clear the log

rename-command(명령 비활성화)

rename-command(redis.conf)는 위험한 명령을 비활성화하거나 이름을 바꿉니다. ""로 설정하면 비활성화되고, 문자열로 설정하면 이름이 바뀝니다. 재시작이 필요하며 런타임에는 바꿀 수 없습니다. Redis 6+에서는 런타임 변경과 사용자별 설정이 가능한 ACL(-flushall, -@dangerous)을 권장합니다. 제한할 만한 명령: FLUSHALL/FLUSHDB(데이터 손실), KEYS(서버 블록), CONFIG(보안), DEBUG(크래시 가능), SHUTDOWN(서버 중지).

redis-cli
# rename or disable dangerous commands (in redis.conf)
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command CONFIG "CONFIG_9f8a7b"
rename-command KEYS ""
rename-command DEBUG ""
rename-command SHUTDOWN "SHUTDOWN_7x9y"

# "" completely disables the command (returns error)
# a string renames it (must use the new name)

# Redis 6+: prefer ACLs instead of rename-command
# ACL SETUSER default -flushall -config -keys -@dangerous

# view available commands (after rename/restrictions)
COMMAND

# note: rename-command requires a restart (not changeable at runtime)
# ACLs are runtime-changeable and more flexible

# dangerous commands to restrict:
#   FLUSHALL, FLUSHDB  - delete all data
#   KEYS               - blocks server
#   CONFIG             - can change security settings
#   DEBUG              - can crash the server
#   SHUTDOWN           - stops the server
#   MONITOR            - performance impact

TLS/SSL 암호화

TLS는 전송 중 데이터를 암호화하므로 특히 신뢰할 수 없는 네트워크에서 운영 환경에 필수입니다. Redis 6+는 TLS를 기본 지원합니다. mTLS(tls-auth-clients yes)는 클라이언트가 인증서를 제시하도록 요구해 비밀번호 없이 상호 인증을 제공합니다. 클러스터/Sentinel에서는 노드 간 통신에도 TLS를 활성화하세요. 포트 0은 평문을 비활성화하며, 마이그레이션 중에는 두 포트를 임시로 함께 운영할 수 있습니다. 운영 환경에서는 항상 적절한 CA 서명 인증서를 사용하세요.

redis-cli
# enable TLS in redis.conf (Redis 6+)
port 0                       # disable plain-text port
tls-port 6379
tls-cert-file /etc/redis/redis.crt
tls-key-file /etc/redis/redis.key
tls-ca-cert-file /etc/redis/ca.crt

# connect with TLS
redis-cli --tls --cert client.crt --key client.key \
  --cacert ca.crt -h host -p 6379

# mutual TLS (mTLS) for client authentication
tls-auth-clients yes         # require client certs
tls-auth-clients no          # don't require (default)
tls-auth-clients optional    # verify if provided

# TLS for cluster and replication
tls-cluster yes              # TLS between cluster nodes
tls-replication yes          # TLS between primary/replica

# mix TLS and plain text (transition period)
# port 6380
# tls-port 6379

# generate self-signed certs for testing:
# openssl req -x509 -newkey rsa:4096 -keyout redis.key \
#   -out redis.crt -days 365 -nodes
19

데이터 가져오기와 내보내기

redis-cli --rdb(백업)

redis-cli --rdb는 온라인 백업을 수행합니다. 서버 파일 시스템을 직접 건드리지 않고 RDB를 파일로 스트리밍합니다. BGSAVE의 백그라운드 포크를 사용하므로 비블로킹이고 운영 환경에 안전합니다. SSH와 결합하면 원격 Redis를 로컬 파일로 백업할 수 있습니다. redis-check-rdb로 백업을 검증하고 cron으로 정기 백업하세요. 복원 절차를 항상 테스트하세요. 검증하지 않은 백업은 백업이 아닙니다.

redis-cli
# dump the RDB snapshot to a file (online backup)
redis-cli --rdb /backup/dump.rdb
# Output: RDB file written to /backup/dump.rdb

# dump RDB to a remote host's file (via SSH):
ssh remote-host "redis-cli --rdb /tmp/dump.rdb"

# the --rdb flag:
# - connects to Redis and requests a BGSAVE
# - streams the RDB to the specified file
# - non-blocking (uses the background fork)
# - safe to run on a production server

# verify the RDB file
redis-check-rdb /backup/dump.rdb

# restore: stop Redis, replace dump.rdb, restart
redis-cli SHUTDOWN
cp /backup/dump.rdb /var/lib/redis/dump.rdb
redis-server /etc/redis/redis.conf

# schedule regular backups:
# 0 2 * * * redis-cli --rdb /backup/dump-$(date +\%F).rdb

redis-cli --pipe(대량 삽입)

redis-cli --pipe는 Redis에 데이터를 대량 적재하는 가장 빠른 방법입니다. 원시 RESP를 스트리밍하고 끝까지 응답을 기다리지 않습니다. printf나 스크립트로 RESP를 생성하세요. --pipe는 오류와 전체 응답 수를 보고합니다. 더 간단하거나 작은 적재에는 텍스트 명령 파이프(echo | redis-cli)도 되지만 느립니다. 항상 벤치마크하세요. --pipe는 수백만 키를 몇 분에 적재할 수 있습니다. 대량 적재 중 메모리를 주시하세요.

redis-cli
# --pipe: bulk load raw RESP data (fastest method)
# generate RESP and pipe it:

# example: bulk SET commands (bash)
for i in $(seq 1 100000); do
  printf '*3\r\n$3\r\nSET\r\n$%d\r\nkey:%d\r\n$%d\r\nvalue%d\r\n' \
    $((4 + ${#i})) $i $((5 + ${#i})) $i
done | redis-cli --pipe

# simpler text mode (slower but easier):
for i in $(seq 1 100000); do
  echo "SET key:$i value$i"
done | redis-cli

# --pipe mode output:
# All data transferred. Waiting for the last reply...
# Last reply received from server.
# errors: 0, replies: 100000

# prepare RESP from a CSV/data file:
# (each line: key,value)
while IFS=, read -r key value; do
  printf '*3\r\n$3\r\nSET\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n' \
    ${#key} "$key" ${#value} "$value"
done < data.csv | redis-cli --pipe

DUMP와 RESTORE

DUMP는 키 값을 바이너리 블롭으로 직렬화합니다(타입과 값을 포함하지만 TTL은 제외, RESTORE에서 밀리초로 TTL 지정). RESTORE는 이를 키로 역직렬화하며 다른 Redis 인스턴스 간에도 동작합니다(마이그레이션에 유용). 직렬화 형식은 버전별로 다르므로 Redis 4.x 블롭이 7.x에서 로드되지 않을 수 있습니다. 항상 호환성을 검증하세요. 인스턴스 내 복사에는 DUMP+RESTORE보다 기본 COPY 명령(6.2+)을 권장합니다.

redis-cli
# DUMP: serialize a key's value (binary blob)
DUMP mykey
# returns a serialized blob (binary, includes type + value + TTL info)

# RESTORE: deserialize into a key
RESTORE newkey 0 <serialized_blob>
# 0 = no TTL (milliseconds); set a TTL otherwise
RESTORE newkey 3600000 <blob>   # 1 hour TTL
RESTORE newkey 0 <blob> REPLACE  # overwrite if exists

# copy a key (6.2+ does this natively with COPY)
# manual copy via DUMP + RESTORE:
SET source "value"
blob = DUMP source
RESTORE dest 0 blob

# DUMP/RESTORE preserve the type but NOT the TTL
# (TTL must be specified in RESTORE)

# DUMP/RESTORE work across different Redis instances
# (migrate data between servers)

# note: serialized format is version-specific
# a blob from Redis 4.x may not load in 7.x — verify compatibility

# use COPY (6.2+) instead for in-instance copies:
COPY source dest                # copy without TTL
COPY source dest REPLACE        # overwrite destination
COPY source dest DB 1           # copy to another database
COPY source dest REPLACE DB 1   # both

MIGRATE(서버 간 이동)

MIGRATE는 Redis 인스턴스 간에 키를 원자적으로 이동(또는 복사)합니다. 키가 동시에 두 곳에 존재하지 않습니다(원자적). 클러스터 리샤딩의 구성 요소입니다. COPY는 원본 키를 유지하고, 기본값은 삭제합니다. REPLACE는 기존 대상 키를 덮어씁니다. 여러 키를 옮기려면 키에 빈 문자열을 넘기고 KEYS로 목록을 지정하세요. 큰 값에 충분한 타임아웃을 설정하세요. MIGRATE는 전송 중 양쪽에서 블로킹입니다.

redis-cli
# MIGRATE: atomically move a key from one Redis to another
# syntax: MIGRATE host port key|"" dest-db timeout [COPY] [REPLACE]
#         [AUTH password] [KEYS key1 key2 ...]

# move a single key (default: deletes from source after copy)
MIGRATE 192.168.1.20 6379 mykey 0 5000
# host, port, key, dest-db, timeout-ms

# copy without deleting from source
MIGRATE 192.168.1.20 6379 mykey 0 5000 COPY

# overwrite if the key exists on destination
MIGRATE 192.168.1.20 6379 mykey 0 5000 REPLACE

# migrate multiple keys (pass "" as the key, then KEYS ...)
MIGRATE 192.168.1.20 6379 "" 0 5000 KEYS key1 key2 key3

# authenticate with the destination
MIGRATE 192.168.1.20 6379 mykey 0 5000 AUTH destpassword

# MIGRATE is atomic: the key appears on exactly one instance at any moment
# timeout is in milliseconds — large keys need longer timeouts
# returns NOKEY if the key doesn't exist on source

COPY(인스턴스 내 복사)

COPY(6.2+)는 같은 인스턴스 안에서 키를 원자적으로 복제하므로 DUMP+RESTORE보다 훨씬 간단합니다. 기본적으로 TTL은 복사하지 않으므로 이후 EXPIRE를 사용하세요. COPY는 DB 옵션으로 데이터베이스 간에도 동작합니다. REPLACE는 기존 대상을 덮어씁니다. 인스턴스 간 복사에는 네트워크를 넘어 원자적인 MIGRATE를 사용하세요. COPY는 인스턴스 내 복제에서 DUMP+RESTORE 패턴을 대체하는 현대적 방법입니다.

redis-cli
# COPY: duplicate a key within the same instance (6.2+)
COPY source dest               # copy value (no TTL by default)
COPY source dest REPLACE       # overwrite destination if it exists
COPY source dest DB 1          # copy to another database
COPY source dest REPLACE DB 1  # both options

# before COPY existed, you needed DUMP + RESTORE:
SET src "hello"
blob = DUMP src
RESTORE dst 0 blob

# COPY preserves the type (string, list, hash, ...)
SET mystr "hello"
COPY mystr mystr_copy
TYPE mystr_copy               # "string"

# COPY does NOT copy TTL by default — use after EXPIRE if needed
SET temp "data" EX 3600
COPY temp temp_copy
TTL temp_copy                 # -1 (no TTL)
EXPIRE temp_copy 3600         # set TTL manually

# COPY is atomic and never blocks (unlike DUMP on huge keys)

redis-check-rdb와 redis-check-aof

redis-check-rdb와 redis-check-aof는 영속성 파일의 무결성을 검증합니다. 복원 전에 백업에서 항상 실행하세요. redis-check-aof --fix는 잘린 AOF에서 불완전한 꼬리를 제거해 복구합니다(확인 프롬프트 있음). Redis 7은 다중 파트 AOF(기본 + 증분)를 사용하므로 매니페스트 파일을 확인하세요. 이 도구들은 --fix 외에는 읽기 전용이라 언제든 안전하게 실행할 수 있습니다. 백업 검증을 습관화하세요. 검증하지 않은 백업은 백업이 아닙니다.

redis-cli
# verify the integrity of an RDB file (offline, safe)
redis-check-rdb /var/lib/redis/dump.rdb
# outputs: [offset] Checksum OK | CRC error | file truncated

# verify an AOF file
redis-check-aof /var/lib/redis/appendonly.aof
# outputs: AOF analyzed: size=... ok_up_to=... ok_up_to_line=...

# fix a truncated AOF (interactive prompt)
redis-check-aof --fix /var/lib/redis/appendonly.aof

# Redis 7 multi-part AOF: check the manifest
redis-check-aof --manifest /var/lib/redis/appendonlydir/appendonly.aof.manifest

# truncate an RDB to a specific offset (recovery)
redis-check-rdb --fix /var/lib/redis/dump.rdb

# use cases:
# - verify a backup before restore
# - diagnose corruption after a crash
# - recover from a truncated AOF (removes the incomplete tail)
# - validate files copied across servers

# always run these checks BEFORE replacing production data files
20

성능 테스트

redis-benchmark 기초

redis-benchmark는 Redis 내장 부하 테스트 도구로, 동시 클라이언트를 시뮬레이션하고 처리량(초당 요청)과 지연 백분위수를 보고합니다. -t는 테스트 선택(PING, SET, GET, INCR 등), -n은 요청 수, -d는 페이로드 크기입니다. 운영 환경과 동등한 하드웨어에서 벤치마크해 기준 성능을 잡으세요. 기본 병렬 클라이언트 50은 출발점일 뿐이므로 실제 워크로드에 맞게 -c를 조정하세요. 설정 변경 전후에 벤치마크를 실행해 영향을 측정하세요.

redis-cli
# redis-benchmark: built-in performance benchmarking tool
# runs commands against a Redis server and reports throughput/latency

# default benchmark (50 parallel clients, 100000 requests)
redis-benchmark
# default commands: PING, SET, GET, INCR, LPUSH, RPUSH, LPOP, RPOP,
#   SADD, HSET, SPOP, ZADD, ZPOPMIN, LRANGE_100, LRANGE_300, ...

# run a specific command only
redis-benchmark -t set,get -n 100000
# -t = test (comma-separated commands)
# -n = number of requests

# test a specific command with custom data
redis-benchmark -t set -n 100000 -d 100
# -d = data size in bytes (default 3)

# output example:
# ====== SET ======
#   100000 requests completed in 0.85 seconds
#   50 parallel clients
#   3 bytes payload
#   keep alive: 1
#   98.90% <= 1 milliseconds
#   100.00% <= 1 milliseconds
#   117647.05 requests per second

# run against a remote server with auth
redis-benchmark -h host -p 6379 -a password -t set,get -n 100000

파이프라인과 동시성 튜닝

처리량을 좌우하는 두 가지 큰 요소는 -c(동시성)와 -P(파이프라인 크기)입니다. -c는 병렬 클라이언트를 늘려 동시 요청을 많게 하고, -P는 왕복당 명령을 묶어 네트워크 오버헤드를 줄입니다. 둘을 함께 쓰면 처리량이 10-20배까지 올라갑니다. 단일 클라이언트(-c 1) 벤치마크는 순수 지연을, 다중 클라이언트는 처리량을 측정합니다. 페이로드가 크면(-d) 병목이 네트워크 대역폭으로 이동합니다. 실제 클라이언트 라이브러리 동작에 맞게 -c/-P를 조정하세요.

redis-cli
# -c = number of parallel connections (clients)
redis-benchmark -t set -n 100000 -c 50     # default: 50 clients
redis-benchmark -t set -n 100000 -c 200    # 200 concurrent clients
redis-benchmark -t set -n 100000 -c 1      # single client (latency focus)

# -P = pipeline size (commands per round-trip)
redis-benchmark -t set -n 100000 -P 1      # no pipelining (baseline)
redis-benchmark -t set -n 100000 -P 16     # pipeline 16 commands
redis-benchmark -t set -n 100000 -P 100    # pipeline 100 commands

# combine -c and -P for max throughput
redis-benchmark -t set -n 100000 -c 50 -P 16

# typical results (localhost, small values):
#   -c 1  -P 1   -> ~100k req/s  (latency-bound)
#   -c 50 -P 1   -> ~600k req/s  (concurrency)
#   -c 50 -P 16  -> ~2M req/s    (pipelining)

# test with a larger payload (network-bound)
redis-benchmark -t set -n 100000 -d 1024   # 1KB values
redis-benchmark -t set -n 100000 -d 65536  # 64KB values

지연 백분위수와 CSV 출력

평균만 보지 말고 항상 지연 백분위수(P50, P99, P99.9)를 확인하세요. 평균은 사용자 경험을 해치는 꼬리 지연 급증을 숨깁니다. P99가 P50보다 5배 나쁘면 지터(GC, 네트워크, 느린 명령)를 뜻합니다. --csv는 시간에 따른 추세를 추적할 수 있는 기계 판독 가능 결과를 출력합니다. 설정 변경 전후 벤치마크를 저장해 영향을 객관적으로 측정하세요. P99 지연과 초당 요청을 함께 추적하세요. 하나를 위해 다른 하나를 희생하는 것은 흔한 함정입니다.

redis-cli
# --csv: CSV output (easy to parse / log)
redis-benchmark -t set,get -n 100000 --csv
# output: "test","rps","avg_latency_ms","min_latency_ms",...
# "SET","117647.05","0.284","0.144"
# "GET","125000.00","0.272","0.136"

# --precision: set decimal places for latency
redis-benchmark -t set -n 100000 --precision 4

# latency percentiles (Redis 6+):
# the default output shows "X% <= Y milliseconds" lines
# ====== SET ======
#   50.00% <= 0.239 milliseconds
#   99.00% <= 0.511 milliseconds
#   99.90% <= 1.023 milliseconds
#   100.00% <= 1.519 milliseconds

# focus on tail latency (P99, P99.9) — average hides outliers
# P99 > 5x P50 indicates jitter or GC pauses

# save results to a file for comparison
redis-benchmark -t set,get -n 100000 --csv > bench-$(date +%F).csv

# compare two runs (before/after a config change)
diff bench-2025-01-01.csv bench-2025-01-02.csv

클러스터와 Lua 벤치마크

--cluster 모드는 키를 클러스터 슬롯에 분산하므로 현실적인 클러스터 벤치마크에 필수입니다(단일 노드 벤치마크는 교차 슬롯 라우팅 오버헤드를 놓침). -r은 무작위 키스페이스 크기를 설정합니다(모든 작업이 한 키에 몰려 수치가 부풀려지지 않게 큰 값을 사용). --eval은 Lua 스크립트를 벤치마크합니다. --threads(Redis 6+)는 여러 벤치마크 스레드를 사용하므로 단일 스레드로 서버를 포화시킬 부하를 만들 수 없을 때 유용합니다. 현실적인 수치를 위해 항상 -r을 사용하세요.

redis-cli
# benchmark a Redis Cluster (redis-benchmark supports cluster mode)
redis-benchmark --cluster -h node1 -p 7000 -t set,get -n 100000
# automatically distributes keys across cluster slots

# cluster mode with multiple nodes
redis-benchmark --cluster -h node1 -p 7000 -h node2 -p 7000 \
  -t set,get -n 100000 -c 50

# benchmark a Lua script (--eval)
redis-benchmark -n 100000 eval "return redis.call('SET', KEYS[1], ARGV[1])" 0 mykey hello
# note: key and args are positional after the script

# benchmark with random keys (--random-data + keyspace length)
redis-benchmark -t set -n 100000 -r 1000000
# -r 1000000 = random keys from a 1M keyspace (SET key:RAND_INT value)
# avoids hitting the same key (tests real-world distribution)

# use a random payload (not the same bytes each time)
redis-benchmark -t set -n 100000 -r 1000000 -d 100 --random-data

# only run the benchmark for a fixed time (seconds)
redis-benchmark -t set --threads 4 -n 100000
# --threads (6+) uses multiple threads (default 1, doesn't help single-core)

--idle과 워밍업

--idle은 PING만으로 순수 연결/네트워크 오버헤드를 측정합니다(넘을 수 없는 기준선). 측정 전에 항상 서버를 워밍업하세요(차가운 캐시는 성능을 과소평가). 먼저 버리는 벤치마크를 실행한 뒤 측정하세요. --loop는 연속 실행하므로 지속 부하 테스트에 유용합니다. --seed는 무작위 키스페이스를 재현 가능하게 만들어 A/B 비교에 필수입니다. --dbnum은 데이터베이스를 선택합니다(벤치마크 중 운영 데이터를 오염시키지 않도록 별도 db 사용).

redis-cli
# --idle: only send PINGs (no commands) — measure pure connection overhead
redis-benchmark -t ping -n 100000 --idle
# useful for measuring connection / network baseline latency

# --dbnum: select a specific database
redis-benchmark -t set -n 100000 --dbnum 1

# --clients: same as -c (alias)
redis-benchmark -t set -n 100000 --clients 100

# warm up the server before measuring (avoid cold-start bias)
redis-benchmark -t set -n 10000   # warmup run (discard results)
redis-benchmark -t set -n 100000  # measured run

# --loop: run the benchmark forever (Ctrl+C to stop)
redis-benchmark -t set -n 100000 --loop

# --seed: reproducible random keys (same -r sequence every run)
redis-benchmark -t set -n 100000 -r 1000000 --seed 42

# benchmark with a specific client socket buffer
redis-benchmark -t set -n 100000 --numdatadb 1

벤치마크 해석과 함정

벤치마크 함정은 수치를 비현실적으로 부풀립니다. (1) localhost 전용 벤치마크는 네트워크 지연을 놓칩니다. (2) -r이 없으면 모든 작업이 한 키에 몰려 캐싱으로 수치가 부풀려집니다. (3) 아주 작은 페이로드는 메모리/네트워크를 압박하지 않습니다. (4) 영속성 오버헤드를 무시하면(AOF fsync는 처리량을 2-5배 줄일 수 있음) 안 됩니다. (5) 단일 벤치마크 스레드는 멀티코어 서버를 포화시킬 수 없습니다. 현실적인 벤치마크는 -r(무작위 키), -d(현실적 페이로드), --threads(멀티스레드 클라이언트)를 사용하고 운영과 동등한 영속성/네트워크에서 테스트합니다. 수치를 공유할 때는 항상 벤치마크 매개변수를 공개하세요.

redis-cli
# COMMON PITFALL #1: benchmarking localhost only
# localhost numbers don't reflect real network latency
# always test over your production network path

# COMMON PITFALL #2: all keys the same (no -r)
# redis-benchmark -t set -n 100000
#   -> all SETs hit "key:0" — inflated by in-memory caching
# FIX: use -r to randomize keys
redis-benchmark -t set -n 100000 -r 1000000

# COMMON PITFALL #3: tiny payloads only
# 3-byte values don't reflect real memory/network pressure
# test with realistic sizes
redis-benchmark -t set -n 100000 -d 256 -r 1000000

# COMMON PITFALL #4: ignoring persistence overhead
# benchmark with AOF on vs off to see the durability cost:
redis-benchmark -t set -n 100000   # with current persistence settings
# (then) CONFIG SET appendonly no
redis-benchmark -t set -n 100000   # without AOF — compare

# COMMON PITFALL #5: single-threaded benchmark client
# one benchmark thread may not generate enough load
redis-benchmark -t set -n 100000 --threads 4 -c 100

# GOOD BENCHMARK (realistic):
redis-benchmark -t set,get -n 1000000 -c 50 -P 16 -r 1000000 -d 100 --threads 4 --csv

Was this helpful?