Skip to content

Redis 치트시트

데이터베이스, 캐시, 메시지 브로커로 쓰이는 인메모리 자료구조 저장소입니다.

01

시작하기

Redis 연결

redis-cli가 표준 명령줄 클라이언트입니다. 연결 테스트는 PING입니다(PONG 반환). 프로덕션에서는 항상 AUTH 명령이나 -a 플래그를 쓰세요. 공유 환경에서는 비밀번호를 명령줄에 두지 말고 REDISCLI_AUTH 환경 변수를 쓰세요. 현대 Redis(6+)는 범위 지정 권한의 ACL 기반 사용자를 지원합니다.

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

# connect with a specific host and port
redis-cli -h host.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

# test the connection
PING          # returns PONG
PING "hello"  # returns "hello"

데이터베이스 선택과 기본

Redis 데이터베이스는 격리된 스키마가 아니라 (0~15로 번호 매겨진) 논리 네임스페이스이며 같은 메모리를 공유합니다. 대부분의 앱은 db 0만 씁니다. FLUSHDB가 현재 db를, FLUSHALL이 전부를 지웁니다. 단일 스레드를 공유하고 개별 설정이 안 되므로 별도 Redis 인스턴스나 키 접두어가 다중 데이터베이스보다 권장됩니다.

redis
# 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

# get basic server info
INFO server
INFO memory
INFO replication

키와 일반 연산

KEYS는 스캔 중 서버를 막으므로 큰 데이터셋의 프로덕션에서 절대 쓰지 말고 (커서 기반, 논블로킹인) SCAN을 쓰세요. 가독성을 위해 키는 콜론으로 구조화하세요(user:1:profile). EX가 초 단위, PX가 밀리초 단위 만료입니다. TYPE이 자료구조(string, list, hash, set, zset, stream)를 반환합니다.

redis
# set and get a key
SET user:1 "Alice"
GET user:1

# check if a key exists
EXISTS user:1          # 1 if exists, 0 if not

# delete keys
DEL user:1
DEL key1 key2 key3     # returns number deleted

# set a key with expiration (seconds)
SET session:abc "data" EX 3600

# find keys matching a pattern (avoid in production)
KEYS user:*
SCAN 0 MATCH user:* COUNT 100   # safer iteration

# rename a key
RENAME oldkey newkey

# get the type of a value stored at a key
TYPE user:1

만료와 TTL

TTL은 없는 키에 -2를, 만료 없는 키에 -1을 반환합니다. 만료는 지연 방식이며 Redis는 키 접근이나 주기적 백그라운드 스윕 때만 검사합니다. EX를 준 SET은 원자적입니다(SET과 EXPIRE 사이 경쟁 없음). 기본적으로 만료된 키는 이벤트를 트리거하지 않으며 필요하면 keyspace 알림을 켜세요.

redis
# set expiration on an existing key
EXPIRE user:1 60        # 60 seconds
EXPIREAT user:1 1700000000  # Unix timestamp

# set expiration in milliseconds
PEXPIRE user:1 60000

# view remaining time to live (seconds)
TTL user:1              # -2 if no key, -1 if no expiry

# view TTL in milliseconds
PTTL user:1

# remove expiration (make key persistent)
PERSIST user:1

# set value AND expiration atomically
SET token "abc" EX 3600

SCAN과 안전한 순회

SCAN이 KEYS의 프로덕션 안전 대안입니다. 0으로 돌아올 때까지 따라 가는 커서를 반환합니다. COUNT는 (정확한 값이 아니라) 힌트이며 더 많거나 적게 반환할 수 있습니다. SCAN은 약한 보장을 제공합니다. 순회 중 추가된 키를 중복 반환하거나 놓칠 수 있지만 절대 막지 않습니다. 컬렉션 타입에는 HSCAN/SSCAN/ZSCAN을 쓰세요. 커서 루프는 항상 코드에서 처리하세요.

redis
# SCAN: cursor-based iteration (non-blocking)
SCAN 0 MATCH user:* COUNT 100
# returns: [nextCursor, [key1, key2, ...]]
SCAN <nextCursor> MATCH user:* COUNT 100
# continue until cursor returns to 0

# scan a specific type
SCAN 0 TYPE hash

# HSCAN: iterate hash fields
HSCAN myhash 0 MATCH field* COUNT 100

# SSCAN: iterate set members
SSCAN myset 0 MATCH member* COUNT 100

# ZSCAN: iterate sorted set members
ZSCAN myzset 0 MATCH member* COUNT 100
02

데이터 타입 개요

핵심 자료구조

올바른 자료구조 선택이 Redis의 핵심 기술입니다. 카운터/캐시는 문자열, 객체는 해시, 큐는 리스트, 고유성/태그는 셋, 리더보드/순위는 정렬 셋, 이벤트 로그는 스트림. 자료구조의 각 연산이 원자적이므로 동시 클라이언트가 상태를 망치지 못합니다. 접근 패턴에 맞는 구조를 고르세요.

redis
# Redis is a data structure server, not just a key-value store
# Each key holds a typed data structure:

# String: binary-safe blob (up to 512MB)
SET key "value"
SET counter 100

# List: ordered, linked-list of strings
LPUSH mylist "a" "b"
RPUSH mylist "c"

# Hash: field-value map (like a small object)
HSET user:1 name "Alice" age 30

# Set: unordered collection of unique strings
SADD tags "redis" "db"

# Sorted Set (ZSet): set scored by a float
ZADD leaderboard 100 "alice" 200 "bob"

# Stream: append-only log with IDs
XADD mystream * field value

# Bitmap, HyperLogLog, Geo: built on strings/zsets

올바른 타입 선택

접근 패턴으로 타입을 고르세요. 고유성이 필요하면 셋, 점수순 정렬이 필요하면 정렬 셋, 객체의 한 필드 갱신이 필요하면 (직렬화된 문자열이 아니라) 해시, 규모 있는 근사 고유 개수가 필요하면 (수십억 항목에 12KB의) HyperLogLog. 올바른 타입 선택 = 더 단순한 코드, 원자적 연산, 극적인 메모리 절약입니다.

redis
# Use case -> data type mapping:
# Cache a string  -> String
SET api:response "json_blob"

# Store an object -> Hash (one key, multiple fields)
HSET user:1 name "Alice" email "[email protected]" age 30

# Queue / stack   -> List
LPUSH tasks "job1"   # push to head
RPOP tasks           # pop from tail (FIFO queue)

# Unique tags      -> Set
SADD post:1:tags "redis" "db" "cache"

# Leaderboard      -> Sorted Set
ZADD scores 100 "alice" 250 "bob"
ZREVRANGE scores 0 9     # top 10

# Event log        -> Stream
XADD events * type click user 1

# Count unique     -> HyperLogLog (approximate, fixed memory)
PFADD visitors "user1" "user2"

메모리 인코딩

Redis가 작은 구조에 (listpack, intset 같은) 컴팩트 인코딩을 써 메모리를 5~10배 아끼고, 커지면 해시 테이블/스킵리스트로 자동 전환합니다. 현재 인코딩 확인은 OBJECT ENCODING이고 바이트 보고는 MEMORY USAGE입니다. (hash-max-listpack-entries 같은) 임계값을 튜닝할 수 있지만 기본값이 잘 골라져 있습니다. 용량 계획에는 인코딩 이해가 도움이 됩니다.

redis
# Redis optimizes storage based on size
# Inspect the internal encoding of a key
OBJECT ENCODING mykey

# String encodings:
#   "embstr"  - short strings (< 44 bytes)
#   "raw"     - long strings
#   "int"     - integer values

# Hash/List/Set/ZSet encodings:
#   "listpack" / "intset" - small (compact, memory-efficient)
#   "hashtable" / "list" / "skiplist" - large (faster, more memory)

# check memory usage of a key
MEMORY USAGE mykey

# sample memory usage stats
MEMORY STATS

# the encoding changes automatically as the structure grows

OBJECT와 메모리 명령

OBJECT IDLETIME은 (거의 접근되지 않는) 콜드 캐시 키 찾기에 유용하고, OBJECT FREQ는 maxmemory-policy가 LFU일 때만 동작합니다. SAMPLES 0을 준 MEMORY USAGE가 정확히 셉니다(큰 컬렉션은 기본 샘플링). 구조화된 문서 반환은 (Redis 7+의) COMMAND DOCS입니다. 이 인트로스펙션 도구들이 메모리 비대 디버깅과 eviction 정책 튜닝에 도움이 됩니다.

redis
# OBJECT subcommands for introspection
OBJECT ENCODING mykey     # internal encoding
OBJECT REFCOUNT mykey     # reference count
OBJECT IDLETIME mykey     # seconds since last access
OBJECT FREQ mykey         # access frequency (LFU mode)

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

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

# help understand a command
COMMAND INFO GET
COMMAND DOCS SET

# COMMAND lists all commands (huge output)
COMMAND

타입 오류와 타입 검사

키의 타입은 수명 동안 고정입니다. 먼저 삭제하지 않으면 같은 키를 다른 타입으로 재사용할 수 없습니다. WRONGTYPE 오류가 실수로 인한 타입 혼동을 막습니다. 출처를 모르는 키를 다룰 때는 항상 TYPE을 확인하세요. 이 엄격한 타이핑 때문에 Redis 명령이 타입 접두어를 씁니다(HSET vs SET vs SADD).

redis
# each key has ONE type; using the wrong command fails
SET mykey "hello"
LPUSH mykey "x"        # WRONGTYPE error

# WRONGTYPE Operation against a key holding the wrong kind of value

# check the type before operating
TYPE mykey             # "string"
if [ "$(TYPE mykey)" = "string" ]; then ...

# TYPE returns: string|list|hash|set|zset|stream|none

# rename preserves the type
RENAME mykey newkey
TYPE newkey            # still "string"

# type is immutable; delete + recreate to change types
DEL mykey
LPUSH mykey "x"        # now a list
03

문자열

기본 문자열 연산

문자열은 바이너리 안전하며 (이미지나 JSON 포함) 최대 512MB의 임의 바이트를 담습니다. NX를 준 SET이 고전 Redis 락 프리미티브입니다(not exists면 set). 원자적이며 설정 교체에 유용한 것은 GETSET이고, 문자열 확장은 SETRANGE입니다. 구조화 데이터에는 필드별 갱신이 가능한 직렬화 JSON 문자열보다 해시를 선호하세요.

redis
# set and get
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 mykey "new" EX 60 NX  # with expiry, only if new

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

# append to a string
APPEND mykey " world"   # "hello world"

# get substring
GETRANGE mykey 0 4      # "hello"
SETRANGE mykey 6 "redis"# "hello redis"

# get string length
STRLEN mykey            # 11

숫자 카운터

INCR/DECR은 원자적이므로 락 없이 동시 접근에 안전합니다. 이것이 Redis를 카운터, 레이트 리밋(INCR + EXPIRE), 시퀀스 ID 생성에 이상적으로 만듭니다. INCRBYFLOAT가 소수를 지원하지만 배정밀도를 쓰므로(반올림 주의) 값이 정수가 아니면 INCR은 오류를 반환합니다. 시간 버킷 통계에는 EXPIRE와 결합하는 것이 최선입니다.

redis
# increment a numeric string atomically
INCR counter            # counter = counter + 1
INCRBY counter 10       # counter = counter + 10

# decrement
DECR counter            # counter = counter - 1
DECRBY counter 5        # counter = counter - 5

# floating point operations
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

다중 키 연산

MSET/MGET이 연산을 한 번의 왕복으로 배칭하며 성능에 필수입니다(Redis 단일 스레드 모델은 명령당 오버헤드가 중요). MSETNX은 원자적입니다. 모든 키가 설정되거나 하나도 안 됩니다(all-or-nothing). (6.2+의) GETDEL이 원자적으로 반환하고 삭제하며 일회성 읽기 메시지 패턴에 유용합니다. 네트워크 지연을 줄이려 가능하면 명령을 배칭하세요.

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

# get multiple keys at once
MGET k1 k2 k3           # ["v1", "v2", "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

# atomic get-and-delete (useful for queues)
GETDEL mykey            # returns value AND deletes key

비트맵 (문자열 기반)

비트맵은 약 512MB로 최대 40억 사용자의 불리언 플래그를 저장합니다. 대규모 인구에서 극히 공간 효율적입니다. 비트맵 결합은 BITOP AND/OR/XOR/NOT이며(예: 여러 날 활동 사용자) 활성 사용자 세기는 BITCOUNT입니다. 사용 사례: DAU, 피처 플래그, 출석 추적. 위치 = 사용자 ID.

redis
# 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:daily:2025-01-01 5 1
SETBIT users:daily:2025-01-02 5 1
BITOP AND active-both users:daily:2025-01-01 users:daily:2025-01-02
BITCOUNT active-both        # users active on both days

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

Bitfield 연산

BITFIELD가 여러 작은 카운터를 하나의 문자열에 담습니다. 예: 1000개 일일 카운터를 u8로 1KB에. OVERFLOW SAT가 최대에서 포화되고(통계에 좋음), FAIL이 오버플로 시 nil을 반환하고(상한에 좋음), WRAP이 감싸입니다(기본, 보통 원치 않음). 많은 작은 카운터의 별도 키보다 훨씬 메모리 효율적입니다.

redis
# BITFIELD: multiple counters in one string (compact)
# store up to 2^63 counters, each 1-64 bits, in a single key

# set a 8-bit unsigned counter at offset 0
BITFIELD mycount SET u8 0 100

# increment a counter (with overflow control)
BITFIELD mycount INCRBY u8 0 10   # returns 110
BITFIELD mycount INCRBY u8 0 10   # returns 120

# overflow control: WRAP (default), SAT, FAIL
BITFIELD mycount OVERFLOW SAT INCRBY u8 0 200  # saturates at 255
BITFIELD mycount OVERFLOW FAIL INCRBY u8 0 999 # returns nil (overflow)

# read multiple counters in one call
BITFIELD mycount GET u8 0 GET u8 8 GET u8 16
04

해시

해시 기본

해시가 객체 저장에 이상적입니다. 객체당 키 하나, 속성당 필드. 읽기-수정-쓰기 없이 개별 필드를 (HSET으로) 원자적으로 갱신할 수 있어 JSON 직렬화를 이깁니다. 전체 필드는 HGETALL이며 큰 해시에는 HSCAN을 선호하세요. (약 128 필드 미만의) 작은 해시는 listpack 인코딩을 써 메모리 효율적입니다.

redis
# 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 multiple fields
HMGET user:1 name age       # ["Alice", "30"]

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

# get all field names or values
HKEYS user:1                # [name, age, email]
HVALS user:1                # [Alice, 30, [email protected]]

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

해시 필드 연산

HSETNX가 필드 수준 'set if not exists'를 제공합니다(일회성 초기화에 유용). 해시 필드의 HINCRBY는 원자적으로 사용자별 카운터(로그인 수, 조회 수)에 완벽합니다. 마지막 필드가 제거되면 해시가 자동 삭제됩니다(HDEL). HSET이 이제 여러 필드를 받으므로 HMSET은 폐기 예정이며 항상 HSET을 쓰세요.

redis
# 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

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

# increment a numeric field atomically
HINCRBY user:1 age 1         # age = 31
HINCRBY user:1 age -5        # age = 26
HINCRBYFLOAT user:1 score 0.5

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

# set multiple fields (same as HSET with multiple)
HMSET user:1 a 1 b 2         # deprecated, use HSET

해시 순회

HGETALL은 큰 해시에서 서버를 막으므로 프로덕션 순회에는 HSCAN을 쓰세요. HSCAN은 커서 기반으로 커서가 0으로 돌아올 때까지 반복 호출합니다. COUNT는 힌트입니다. (6.2+의) HRANDFIELD가 (랜덤 피처 플래그 같은) 샘플링에 유용합니다. 수백만 필드의 해시는 샤딩으로 여러 키로 쪼개는 것을 고려하세요.

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

# iterate all fields
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

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

해시 만료 (Redis 7.4+)

필드 수준 TTL(7.4+)이 해시의 주요 기능입니다. 이전에는 개별 필드 만료에 별도 키나 우회가 필요했습니다. 수명이 섞인 객체에 유용합니다(세션 토큰은 만료되지만 이름은 남는 사용자 프로필). 오래된 Redis 버전은 만료 필드를 자기 EXPIRE가 있는 별도 키로 저장해야 합니다.

redis
# before 7.4, expiration was only at the key level
EXPIRE user:1 3600    # the whole hash expires

# Redis 7.4+: field-level TTL (HEXPIRE)
HEXPIRE user:1 60 FIELDS 1 session_token
# expires only the session_token field in 60 seconds

# get TTL of a specific field
HPTTL user:1 FIELDS 1 session_token

# persist a specific field (remove its TTL)
HPERSIST user:1 FIELDS 1 session_token

# get all fields and their expiration times
HEXPIRETIME user:1 FIELDS 1 session_token

해시 사용 사례

해시가 객체와 그룹 카운터에서 빛납니다. 강력한 메모리 기법: 작은 문자열 키가 많으면 하나의 해시로 묶으세요. listpack 인코딩이 (각각 메타데이터를 가진) 수천 개 개별 키보다 오버헤드가 훨씬 적습니다. 이 '키 버킷팅'이 작은 값의 메모리 사용을 5~10배 줄일 수 있습니다.

redis
# 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. Group small key-value pairs into one hash (memory savings)
# instead of SET k1 v1; SET k2 v2 -> HSET bucket k1 v1 k2 v2
05

리스트

리스트 기본 (Push/Pop)

리스트가 양단이므로 LPUSH+RPOP = 큐(FIFO), LPUSH+LPOP = 스택(LIFO)입니다. BLPOP/BRPOP이 항목이 생길 때까지 막으며 Redis 큐의 기반입니다(폴링 불필요). 연결 끊김 처리를 위해 BLPOP에는 항상 타임아웃을 설정하세요. 리스트는 머리/꼬리 연산이 O(1)이지만 중간 접근은 O(N)입니다.

redis
# lists are ordered sequences of strings (linked lists)
# push to head (left) or tail (right)
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
LPOP mylist 2             # ["a", ...]

# 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

리스트 인덱싱과 범위

LRANGE 0 -1이 전체 리스트를 반환합니다. (최신 100 이벤트만 유지하는 식의) 리스트 크기 제한 흔한 패턴은 LTRIM입니다. 값 기반 제거는 LREM이며(count: 양수=머리, 음수=꼬리, 0=전부) 중간 요소의 LINDEX는 O(N)입니다. 리스트는 끝 접근에 최적화되어 인덱스 랜덤 접근에는 다른 구조를 쓰세요.

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

# get a range of elements
LRANGE mylist 0 -1        # all elements
LRANGE mylist 0 2         # first 3 elements
LRANGE mylist -3 -1       # last 3 elements

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

# get length
LLEN mylist

# trim to a range (removes everything outside)
LTRIM mylist 0 99         # keep only first 100 elements

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

큐로서의 리스트

BRPOPLPUSH/BLMOVE가 항목을 소스에서 대상으로 원자적으로 옮깁니다. 소비자가 안전히 처리할 수 있고 크래시해도 항목이 대상에 남습니다(신뢰 큐 패턴). BRPOP 후 처리보다 낫습니다. BRPOP 뒤 크래시는 항목을 잃습니다. 처리 후에는 대상 리스트에서 삭제하세요.

redis
# 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
LPUSH source "item"
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

리스트 삽입과 제거

LINSERT는 O(N)이므로 큰 리스트에서는 아껴 쓰세요. 제거 없이 요소 위치 찾기는 LPOS입니다. (7.0+의) LMPOP이 한 번의 호출로 여러 리스트에서 pop하며 우선순위 큐에 유용합니다. 잦은 리스트 중간 연산에는 리스트가 잘못된 선택이므로 정렬 셋이나 다른 데이터 모델을 고려하세요.

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

# remove elements by value
LREM mylist 1 "value"     # remove first occurrence from head
LREM mylist -1 "value"    # remove first occurrence from tail
LREM mylist 0 "value"     # remove ALL occurrences

# pop and push in one atomic operation
RPOPLPUSH source dest

# get and remove from both ends (6.2+)
LPOP mylist 2             # pop 2 from head
LMPOP 2 mylist LEFT COUNT 3  # (7.0+) pop from one of multiple lists

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

리스트 사용 사례

리스트가 끝 접근 패턴의 시퀀스에 최선입니다. 큐, 스택, 피드, 버퍼. LTRIM이 (상한이 있는) 로그/피드에 이상적입니다. 레이트 리밋은 타임스탬프 리스트 + LTRIM이 간단한 슬라이딩 윈도우입니다. 정렬/우선순위 큐에는 정렬 셋을 쓰세요. 리스트는 중복 제거를 지원하지 않으니 그건 셋입니다.

redis
# 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 <timestamp>
LTRIM rate:user:1 0 99
LLEN rate:user:1           # request count in window
06

셋

셋 기본

셋이 고유 값을 저장합니다. 태그, 카테고리, 중복 제거에 완벽합니다. SISMEMBER는 O(1)로 리스트 검사보다 훨씬 빠릅니다. SMEMBERS는 큰 셋에서 막을 수 있으므로 순회에는 SSCAN입니다. 제거하지 않는 샘플은 SRANDMEMBER, 제거하는 것은 SPOP입니다. 모든 멤버가 정수면 셋은 (정렬 배열인) intset을 써 매우 메모리 효율적입니다.

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

# remove a member
SREM tags "cache"

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

# get the number of members
SCARD tags                 # 2

# get all members (avoid on large sets)
SMEMBERS tags              # ["redis", "db"]

# get a random member
SRANDMEMBER tags           # one random member
SRANDMEMBER tags 3         # 3 random (may repeat)
SRANDMEMBER tags -3        # 3 unique random

# pop a random member (removes it)
SPOP tags                  # removes and returns one

셋 연산

셋 연산이 Redis의 슈퍼파워입니다. 클라이언트 측 처리 없이 O(N)의 합집합, 교집합, 차집합. 사용 사례: 공통 친구(SINTER), 고유 방문자(SUNION), 태그 기반 필터링(태그 셋의 SINTER). (7.0+의) SINTERCARD가 개수만 반환하며 멤버가 필요 없을 때 더 빠릅니다. 재계산을 피하려 결과를 저장하세요.

redis
# 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

셋 순회와 이동

SMOVE는 원자적이며 (사용자를 'pending'에서 'active' 셋으로 옮기는 식의) 상태 전이에 유용합니다. 큰 셋의 안전한 순회는 SSCAN입니다. (7.4+의) SMISMEMBER가 멤버십을 배칭 검사해 왕복을 줄입니다. (7.0+의) BSPOP이 BLPOP처럼 막지만 셋용이며 순서가 중요하지 않은 이벤트 구동 패턴에 유용합니다.

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

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

# pop multiple random members (6.2+)
SPOP myset 3               # removes and returns 3 members

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

# check multiple memberships at once (7.4+)
SMISMEMBER myset "a" "b" "c"
# returns [1, 0, 1]

셋 사용 사례

셋이 고유성과 관계의 기본입니다. 상호 팔로워/친구의 SINTER 패턴이 고전입니다. 카디널리티가 거대한 '일일 방문자'에는 (근사지만 고정 12KB의) HyperLogLog를 고려하세요. (리더보드 같은) 정렬된 고유 데이터에는 정렬 셋을 쓰세요. 셋은 순서가 없으며 순서가 중요하면 리스트나 정렬 셋을 쓰세요.

redis
# 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
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"

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

셋 vs 기타 타입

타입 선택이 Redis 설계의 핵심 결정입니다. 고유성 + 빠른 멤버십(순서 없음)은 셋, 순위/정렬(메모리 더 씀)은 정렬 셋, 중복이 있는 시퀀스는 리스트, 필드-값 객체는 해시. 확신이 없으면 접근 패턴을 스케치하세요. 읽기, 쓰기, 정렬, 고유성 요구가 있으면 올바른 타입이 명백해집니다.

redis
# Set: unordered, unique, O(1) membership check
SADD myset "a" "b"
SISMEMBER myset "a"       # O(1)

# Sorted Set: unique + ordered by score
ZADD myzset 1 "a" 2 "b"
ZRANK myzset "a"          # 0 (rank)

# List: ordered, allows duplicates, O(N) search
LPUSH mylist "a" "a"
LPOS mylist "a"           # 0 (first match)

# Hash: field-value pairs, no ordering
HSET myhash a 1 b 2

# Choose:
# - need uniqueness only?           -> Set
# - need uniqueness + ordering?     -> Sorted Set
# - need ordering + allow dups?     -> List
# - need key-value mapping?         -> Hash
07

정렬 셋

정렬 셋 기본

정렬 셋(zsets)이 Redis의 가장 강력한 구조입니다. 점수순으로 정렬된 고유 멤버와 O(log N) 연산. (NX/XX/GT/LT 같은) ZADD 옵션이 조건부 갱신을 가능하게 합니다. GT는 새 점수가 더 클 때만 갱신하며('최고 점수' 추적에 좋음) 점수는 double, 멤버는 고유입니다. 동률은 사전순으로 깹니다.

redis
# 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: conditional)
ZADD leaderboard NX 300 "new"
ZADD leaderboard GT 300 "alice"  # only if new score is greater

# 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

범위 쿼리

순위(인덱스) 기반 반환은 ZRANGE, 점수 기반은 ZRANGEBYSCORE입니다. '(' 접두어가 점수를 배타로 만듭니다. Redis 6.2가 BYSCORE/BYLEX/REV 옵션의 ZRANGE로 이들을 통합했습니다. WITHSCORES가 출력에 점수를 포함합니다. 리더보드 top 10은 ZREVRANGE 0 9입니다. (6.2+의) ZRANGESTORE가 결과를 새 키에 저장합니다.

redis
# 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)

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

# descending order
ZREVRANGE leaderboard 0 2            # top 3 (highest scores)
ZREVRANGEBYSCORE leaderboard 200 100 # 200 down to 100

# 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

점수 연산과 순위

ZINCRBY가 점수를 원자적으로 조정·재정렬하며 실시간 리더보드에 완벽합니다. (top 1000만 유지하는 식의) zset 크기 유지에 좋은 것은 ZREMRANGEBYRANK이며, 멤버를 가져오지 않고 범위 개수를 주는 것은 ZCOUNT입니다. (6.2+의) ZMSCORE가 점수를 배칭 가져와 다중 멤버 조회의 왕복을 줄입니다.

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

# get the score
ZSCORE leaderboard "alice"

# remove a member
ZREM leaderboard "bob"

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

# count members in a score range
ZCOUNT leaderboard 100 200

# get the rank
ZRANK leaderboard "alice"          # ascending rank
ZREVRANK leaderboard "alice"       # descending rank (0 = highest)

# get multiple members' scores at once
ZMSCORE leaderboard "alice" "bob"  # ["250", "200"]

사전식 범위 (BYLEX)

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

redis
# 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

정렬 셋 집계

ZUNIONSTORE/ZINTERSTORE가 (SUM/MIN/MAX의) 설정 가능한 집계와 가중치로 zset을 결합합니다. 가중 점수 매기기(예: relevance = text_match*2 + recency*1)에 강력합니다. Redis 6.2가 저장 없이 결과를 반환하는 ZUNION/ZINTER/ZDIFF를 추가했습니다(명령 하나 덜). O(N*M)이므로 많은 큰 셋에 주의하세요. 셋 개수는 셋 이름 앞에 옵니다.

redis
# ZUNIONSTORE / ZINTERSTORE: 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
08

Pub/Sub

Pub/Sub 기본

Pub/Sub은 fire-and-forget입니다. 메시지가 현재 연결된 구독자에게 전달되며 영속성이 없습니다. 구독자가 없으면 메시지가 사라집니다. 그래서 신뢰 전달에는 부적합하며 그건 Streams입니다. Pub/Sub은 가끔 손실이 허용되는 실시간 알림, 채팅, 팬아웃에 이상적입니다. 수신하려면 구독자가 연결되어 있어야 합니다.

redis
# subscribe to channels (in one client)
SUBSCRIBE news alerts

# publish a message to a channel (from another client)
PUBLISH news "Breaking: Redis 7.4 released"

# pattern subscription (glob-style)
PSUBSCRIBE news.*

# unsubscribe
UNSUBSCRIBE news
PUNSUBSCRIBE news.*

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

샤딩된 Pub/Sub (7.0+)

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

redis
# 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)

Pub/Sub 패턴과 사용 사례

Pub/Sub이 팬아웃 패턴에 완벽합니다. 게시자 하나, 구독자 다수(채팅방, 라이브 대시보드, 캐시 무효화). glob 패턴(user:*:login)의 PSUBSCRIBE가 유연한 라우팅을 가능하게 합니다. 주요 한계는 영속성 부재입니다. 구독자가 연결을 끊으면 메시지를 놓칩니다. 신뢰 전달은 Pub/Sub를 (백업인) 스트림과 짝짓거나 그냥 Streams를 쓰세요.

redis
# 1. Real-time chat
# client subscribes to their room
SUBSCRIBE chat:room:42
# server publishes messages
PUBLISH chat:room:42 "Alice: hello"

# 2. Cache invalidation
# subscribe to invalidation channel
SUBSCRIBE cache:invalidate
# when data changes, publish
PUBLISH cache:invalidate "user:123"

# 3. Event notifications (with PSUBSCRIBE patterns)
PSUBSCRIBE user:*:login
# matches user:1:login, user:2:login, etc.

# 4. Live dashboards
SUBSCRIBE metrics:*
# push real-time updates to dashboards

# 5. Multiplayer game state
PUBLISH game:room:1 "player_moved:5:10"

Keyspace 알림

keyspace 알림이 클라이언트가 키 수명 주기 이벤트(set, delete, expire, evict)에 반응하게 합니다. 설정은 notify-keyspace-events입니다. fire-and-forget이며(영속성 없음) 신뢰할 수 없습니다. Redis 서버가 재시작하면 대기 이벤트가 사라집니다. 신뢰할 수 있는 이벤트 처리에는 Streams를 쓰세요. keyspace 알림이 정리나 캐시 예열 같은 부수 효과에 좋습니다.

redis
# 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

Pub/Sub vs Streams

Pub/Sub은 일회성 실시간 메시징이고 Streams는 지속·재생 가능 메시징입니다. 흔한 하이브리드: 라이브 알림은 Pub/Sub(빠르고 유실 가능), 진실의 원천은 Streams(지속, 재생 가능). 새 구독자는 따라잡으려 스트림을 읽고 라이브 갱신은 Pub/Sub를 구독합니다. 신뢰성이 필요한 대부분의 프로덕션 시스템에서 Streams가 더 나은 기본입니다.

redis
# Pub/Sub: fire-and-forget, no persistence
PUBLISH channel "msg"   # lost if no subscribers

# Streams: persistent, replayable, consumer groups
XADD mystream * msg "hello"   # stored forever (or capped)

# Pub/Sub pros: simple, low latency, fan-out
# Pub/Sub cons: no persistence, no replay, no consumer groups

# Streams pros: persistent, replayable, consumer groups, ACK
# Streams cons: more complex, requires cleanup (XADD MAXLEN)

# when to use each:
# - real-time notifications (loss OK)     -> Pub/Sub
# - chat with presence                    -> Pub/Sub + Streams
# - reliable task queue                   -> Streams
# - event sourcing / audit log            -> Streams
# - fan-out to transient subscribers      -> Pub/Sub
09

트랜잭션과 파이프라이닝

MULTI/EXEC 트랜잭션

MULTI/EXEC가 명령을 원자적 순차 블록으로 묶습니다. 다른 클라이언트가 끼어들 수 없습니다. 명령이 큐잉되고(QUEUED 반환) EXEC에서 함께 실행됩니다. 큐잉 오류(잘못된 명령 이름)가 전체 트랜잭션을 중단하고, 런타임 오류(키의 잘못된 타입)는 그 명령만 건너뛰며 나머지는 실행됩니다. SQL 트랜잭션과 다릅니다.

redis
# MULTI starts a transaction; commands are queued
MULTI
SET counter 1
INCR counter
INCR counter
GET counter
EXEC
# returns: [OK, 2, 3, "3"]

# discard a transaction (cancels all queued commands)
MULTI
SET x 1
DISCARD

# errors during queuing (syntax) abort the whole transaction
# errors during EXEC (e.g., wrong type) skip only that command

WATCH (낙관적 잠금)

WATCH가 낙관적 잠금을 구현합니다. WATCH와 EXEC 사이에 감시된 키가 바뀌면 트랜잭션이 중단됩니다(EXEC가 nil 반환). Redis에 행 락이 없으므로 이것이 (읽기-수정-쓰기 원자성의) 표준 Redis 패턴입니다. nil에서는 항상 재시도하세요. WATCH는 큐잉 중이 아니라 EXEC 시점에 검사됩니다. 감시 취소는 UNWATCH이며 DISCONNECT에서도 일어납니다.

redis
# WATCH monitors keys; if any change before EXEC, the 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

파이프라이닝 (배치 왕복)

파이프라이닝이 네트워크 왕복을 줄이려 명령을 배칭하며 네트워크를 통한 개별 명령보다 극적으로 빠릅니다. MULTI/EXEC와 달리 파이프라인된 명령은 '원자적이지 않습니다'(다른 클라이언트가 끼어들 수 있음). 원자성이 무관한 대량 연산(대량 삽입, 읽기)에는 파이프라이닝, 원자성이 필요하면 MULTI/EXEC를 쓰세요. 대부분의 클라이언트가 MULTI/EXEC 내에서 자동 파이프라인합니다.

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

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

# vs MULTI/EXEC: pipelining does NOT guarantee atomicity
# other clients can interleave between pipelined commands

# raw protocol example (RESP):
# *1\r\n$4\r\nPING\r\n*1\r\n$4\r\nPING\r\n
# (send multiple commands at once, read multiple replies)

Lua 스크립트 (원자적)

Lua 스크립트가 Redis식 복잡한 원자적 연산 방법입니다. 스크립트가 단일 원자 단위로 실행됩니다(끼어들기 없음). 해시로 로드된 스크립트 재실행은 EVALSHA이며(스크립트 재전송 회피) 스크립트는 (서버를 막으므로) 짧게 유지하세요. 복제를 위해 스크립트에는 (랜덤/시간 호출 없는) 결정적 요구가 있습니다. 더 구조화된 대안은 Redis 7+의 FUNCTIONS입니다.

redis
# Lua scripts run atomically — no other command runs during execution
# EVAL: run a script
EVAL "return redis.call('GET', KEYS[1])" 1 mykey

# 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"

# load a script once, then run by SHA hash (efficient)
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
# returns a SHA1 hash
EVALSHA <sha1> 1 mykey

# check if a script is loaded
SCRIPT EXISTS <sha1>

Functions (Redis 7.0+)

Functions(7.0+)가 EVAL 스크립트를 개선합니다. 이름이 있고(단순 해시가 아님) 라이브러리로 조직되며 재시작에도 유지됩니다(EVAL 스크립트는 일시적). 관리와 배포가 더 쉽습니다. 이름으로 함수 호출은 FCALL입니다. Functions가 원자적 서버 측 로직 추가의 현대적 방법입니다. 스크립트처럼 복제를 위해 결정적이어야 합니다.

redis
# 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

# get the function's code
FUNCTION DUMP mylib

# delete a library
FUNCTION DELETE mylib

# functions persist across restarts (unlike EVAL scripts)
10

영속성

RDB 스냅샷

RDB 스냅샷은 백업과 재해 복구에 이상적인 컴팩트 바이너리 파일입니다. BGSAVE가 (copy-on-write로) 프로세스를 fork해 메인 스레드를 막지 않지만 큰 데이터셋은 fork 중에도 메모리 스파이크를 일으킬 수 있습니다. ('save' 규칙이) 변경 비율에 따라 자동 스냅샷을 트리거합니다. RDB는 마지막 스냅샷 이후 쓰인 데이터를 잃을 위험이 있으므로 내구성은 AOF와 짝지으세요.

redis
# RDB: point-in-time snapshot of the dataset (compact binary)
# trigger a snapshot manually:
SAVE              # blocks until done (use with care)
BGSAVE            # forks a background process (non-blocking)
LASTSAVE          # Unix timestamp of the last successful save

# 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 (default: dump.rdb in the working dir)
CONFIG GET dbfilename
CONFIG GET dir

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

AOF (Append-Only File)

AOF가 모든 쓰기 명령을 로그에 append합니다. RDB보다 훨씬 지속적입니다(everysec은 최대 1초 데이터 손실). 'always'가 매 쓰기마다 fsync하며(매우 느림, 중요 데이터 전용) 로그 압축(최소 명령 집합으로 재작성)은 BGREWRITEAOF입니다. AOF 파일이 RDB보다 크고 로드가 느립니다. Redis 7은 (base + 증분의) 다중 부분 AOF 형식을 씁니다.

redis
# 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

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

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

RDB + AOF 하이브리드

RDB + AOF를 함께 실행하면 RDB의 빠른 재시작과 AOF의 내구성을 모두 얻습니다. Redis 7부터 AOF는 다중 부분 파일입니다. RDB base 스냅샷 + 증분 명령 로그로 빠른 로드와 최소 데이터 손실을 결합합니다. aof-use-rdb-preamble(기본 yes)이 더 빠른 복구를 위해 AOF 시작에 RDB 스냅샷을 둡니다. 권장 프로덕션 설정입니다.

redis
# use BOTH RDB and AOF for the best of both worlds
# redis.conf:
#   save 900 1          # RDB snapshots
#   appendonly yes      # AOF enabled
#   aof-use-rdb-preamble yes  # RDB header in AOF (faster load)

# on restart, Redis loads AOF (more complete)
# the AOF file can start with an RDB snapshot (faster load)
# followed by incremental AOF commands

# disaster recovery: keep both RDB and AOF backups
# RDB for fast restores, AOF for minimal data loss

# check what's enabled
CONFIG GET save
CONFIG GET appendonly

# monitor persistence operations
INFO persistence

백업과 복구

RDB 파일(컴팩트하고 빠름)은 Redis 실행 중에도 일관된 스냅샷이므로(copy-on-write) 정기적으로 백업하세요. AOF는 (Redis 7 다중 부분의) appendonly 디렉터리 전체를 백업합니다. 복구는 Redis 정지, 파일 교체, 재시작입니다. 나쁜 명령에서의 복구는 재시작 전 AOF에서 제거 편집입니다. 백업 검증은 redis-check-rdb/aof로 항상 하세요.

redis
# backup: copy the RDB file while Redis runs
cp /var/lib/redis/dump.rdb /backup/dump-$(date +%F).rdb

# or trigger a BGSAVE first for a consistent snapshot
BGSAVE
# wait for LASTSAVE to update, then copy the file

# AOF backup: copy the AOF manifest + files
cp /var/lib/redis/appendonly.aof.* /backup/

# restore: stop Redis, replace the data files, start
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)
redis-check-rdb /var/lib/redis/dump.rdb
redis-check-aof /var/lib/redis/appendonly.aof

영속성 절충

영속성 선택은 내구성 요구에 달려 있습니다. 순수 캐시: 최대 속도를 위해 영속성 비활성화. 중요 데이터: RDB+AOF(권장). 흔한 패턴: (성능을 위해) 프라이머리에서 영속성 비활성화, (디스크 I/O 분산을 위해) 레플리카에서 영속화. everysec AOF가 스위트 스팟입니다. 최소 성능 영향으로 최대 1초의 데이터 손실. 복구는 항상 테스트하세요.

redis
# choosing a persistence strategy:

# 1. RDB only (cache, re-buildable data)
#    save 3600 1
#    appendonly no
#    -> fast restart, some data loss on crash

# 2. AOF only (durability-critical, everysec)
#    save ""
#    appendonly yes
#    appendfsync everysec
#    -> up to 1s data loss, larger files

# 3. RDB + AOF (recommended production default)
#    save 3600 1
#    appendonly yes
#    aof-use-rdb-preamble yes
#    -> durability + fast restart

# 4. No persistence (pure cache, ephemeral)
#    save ""
#    appendonly no
#    -> maximum speed, all data lost on restart

# 5. Replica-only persistence (offload from primary)
#    primary: no persistence (max performance)
#    replica: RDB + AOF (persist here instead)
11

클러스터링

Redis Cluster 기본

Redis Cluster가 16,384개 해시 슬롯으로 노드에 걸쳐 데이터를 샤딩합니다. 슬롯 결정은 CRC16(key) % 16384입니다. (MGET, 트랜잭션 같은) 다중 키 연산에는 같은 슬롯의 키가 필요하므로 관련 키를 강제로 모으려 해시 태그({user:1})를 쓰세요. 각 프라이머리가 HA를 위해 레플리카를 가질 수 있으며 프라이머리 실패 시 클러스터가 자동 페일오버합니다.

redis
# Redis Cluster shards data across multiple nodes (16,384 slots)
# each key maps to a slot: CRC16(key) % 16384

# 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 status
redis-cli -p 7000 CLUSTER INFO
redis-cli -p 7000 CLUSTER NODES

# count slots assigned
CLUSTER COUNTKEYSINSLOT 1234

# get the slot for a key
CLUSTER KEYSLOT mykey   # e.g., 1234

# multi-key operations require keys in the SAME slot
# 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 {})

해시 태그와 다중 키 연산

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

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

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)
# - too narrow -> can't do multi-key ops

클러스터 리샤딩

리샤딩이 다운타임 없이 노드 간 슬롯을 옮기며 Redis는 요청을 처리하면서 키를 하나씩 마이그레이션합니다. 부하 분산을 위해 노드 추가 후 rebalance하세요. 복잡한 오케스트레이션은 --cluster CLI 도구가 처리합니다. 변경 후에는 항상 --cluster check을 실행하세요. 리샤딩이 (키별 마이그레이션으로) 느리므로 부하 상태의 리샤딩보다 용량을 미리 계획하세요.

redis
# move slots from one node to another (resharding)
redis-cli --cluster reshard host1:7000
# prompts for: how many slots, target node, source nodes

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

# add a new replica to an existing primary
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>

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

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

클러스터 페일오버

클러스터 페일오버는 자동입니다. 프라이머리가 cluster-node-timeout(기본 15s)을 넘어 도달 불가면 그 레플리카가 승격됩니다. 수동 페일오버는 (무중단 업그레이드 같은) 유지보수용입니다. TAKEOVER는 split-brain 위험이 있어 비상 시에만 쓰세요. 레플리카가 없으면 프라이머리 실패가 그 슬롯을 사용 불가로 만듭니다(클러스터 다운). 프로덕션에서는 항상 레플리카와 함께 실행하세요. 토폴로지는 CLUSTER NODES입니다.

redis
# when a primary fails, its replica is promoted automatically
# manual failover (for maintenance):
redis-cli -p 7001 CLUSTER FAILOVER         # replica -> primary
redis-cli -p 7001 CLUSTER FAILOVER FORCE   # without primary agreement
redis-cli -p 7001 CLUSTER FAILOVER TAKEOVER # force, may split brain

# view the cluster topology
CLUSTER NODES
CLUSTER SHARDS    # (7.0+)

# a node flagged as FAIL after timeout is removed
# cluster- node-timeout 15000   (15 seconds in redis.conf)

# if a cluster has no replica for a failing primary,
# that slot range becomes unavailable until the primary returns
# (or you manually fix it)

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

Cluster vs Sentinel vs Single

개발에는 단일 인스턴스, 데이터가 한 머신에 들어갈 때의 HA에는 Sentinel(모니터링/페일오버용 프라이머리 하나 + 레플리카 + 센티널), 데이터가 한 머신을 초과하거나 쓰기 처리량이 매우 높을 때의 수평 확장에는 Cluster입니다. Cluster가 (해시 태그, 다중 키 한도 같은) 복잡성을 더합니다. (Redis Cloud, ElastiCache, MemoryDB 같은) 관리형 서비스가 운영 부담을 처리하므로 셀프 호스팅의 강한 이유가 없다면 이들을 선호하세요.

redis
# Single Redis: one instance, no HA, no scaling
#    simplest, fine for dev/small cache

# Sentinel: 1 primary + replicas + sentinel monitors
#    HA (automatic failover), no sharding
#    good when dataset fits on one machine
#    sentinel.conf: sentinel monitor mymaster host 6379 2

# Cluster: sharded across N primaries + replicas
#    HA + horizontal scaling
#    good for large datasets / high throughput
#    more complex (multi-key limitations)

# choose:
# - dev / tiny cache              -> single
# - production, data fits in RAM  -> sentinel (HA)
# - data > single machine RAM     -> cluster (sharding)
# - very high write throughput    -> cluster (shard writes)

# managed Redis (Redis Cloud, ElastiCache) handles
# sentinel/cluster ops for you
12

Sentinel (고가용성)

Sentinel 설정

Sentinel이 샤딩 없이 HA를 제공합니다. 프라이머리를 모니터링하고, 실패 시 레플리카를 승격하며, 클라이언트를 재설정합니다. quorum(마지막 수)은 프라이머리 다운에 동의해야 하는 센티널 수이며 N개 센티널이면 (N/2)+1로 설정합니다. 내결함성을 위해 별도 머신에 3개 센티널을 배포하세요. down-after-milliseconds는 네트워크 지터보다 커야 하며 너무 낮으면 거짓 페일오버를 일으킵니다.

redis
# 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 명령

클라이언트가 센티널에 연결해 현재 프라이머리를 찾은 뒤 그것에 연결합니다. 페일오버 시 클라이언트가 새 프라이머리를 찾으려 다시 센티널에 질의합니다. (롤링 업그레이드용) 수동 페일오버 트리거는 SENTINEL failover입니다. quorum에 충분한 센티널이 있는지 검증하는 ckquorum은 모니터링에서 실행하세요. 주요 Redis 클라이언트 라이브러리가 Sentinel을 네이티브 지원합니다.

redis
# query sentinel state
redis-cli -p 26379 SENTINEL masters          # all monitored primaries
redis-cli -p 26379 SENTINEL master mymaster  # details of one primary
redis-cli -p 26379 SENTINEL replicas mymaster
redis-cli -p 26379 SENTINEL sentinels mymaster

# find the current primary address
SENTINEL get-master-addr-by-name mymaster

# force a failover (manual, for maintenance)
SENTINEL failover mymaster

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

# check the number of OK sentinels
SENTINEL ckquorum mymaster
# "OK 3 usable Sentinels" or "NOQUORUM" warning

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

페일오버 과정

페일오버는 자동이지만 (수 초의) 짧은 쓰기 중단을 일으킵니다. SDOWN은 한 센티널의 의견이고 ODOWN은 quorum 합의입니다. 선출된 센티널 리더가 가장 최신 레플리카를 골라 승격합니다. 이전 프라이머리가 돌아오면 레플리카가 되며, 네트워크 파티션 중 수락한 쓰기는 '잃습니다'(split-brain 위험). 알림 구독은 +switch-master입니다.

redis
# when a primary is down longer than down-after-milliseconds:
# 1. sentinels mark it 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-*

읽기 레플리카와 확장

레플리카가 프라이머리에서 읽기를 떼어냅니다. (분석, 보고 같은) 읽기 무거운 워크로드에 유용합니다. 복제는 비동기이므로 레플리카 데이터가 뒤처질 수 있습니다(보통 밀리초, 부하 하에 증가 가능). 레플리카에서 읽기는 READONLY입니다. (4.0+의) 쓰기 가능 레플리카가 비복제 쓰기를 수락하며 임시 데이터나 레플리카별 캐시에 유용하지만 페일오버 시 쓰기가 사라집니다. 레플리카 지연을 모니터링하세요.

redis
# replicas can serve reads (eventually consistent)
REPLICAOF 192.168.1.10 6379    # become a replica of this primary
REPLICAOF NO ONE               # promote to primary (manual)

# check replication status
INFO replication
# role:slave, master_host, master_link_status:up, ...

# replica lag (bytes and seconds lagging behind primary)
# master_repl_offset vs slave_repl_offset

# clients can route reads to replicas for read scaling
# but beware: replica data may be stale (replication lag)

# Redis Sentinel + clients: configure read preference
#   READONLY command enables reads on a replica

# writable replicas (Redis 4.0+): accept writes that are
# local-only (not replicated) — useful for ephemeral data
#   replica-read-only no   (in redis.conf)

복제 내부

복제는 비동기이고 단방향입니다(프라이머리 → 레플리카). 초기 동기화가 전체 RDB를 보낸 뒤 명령 백로그를 보내며, PSYNC가 (복제 백로그를 쓰는) 짧은 연결 끊김 후 부분 재동기화를 가능하게 합니다(tune repl-backlog-size). (프라이머리 재시작이나 페일오버의) 복제 ID 변경이 전체 재동기화를 강제합니다. (레플리카의 레플리카인) 체인 복제가 대규모 팬아웃에서 프라이머리 부하를 줄입니다.

redis
# replication is asynchronous: primary -> replica (one-way)
# initial sync: full RDB transfer + buffered commands
# subsequent: streaming command log

# trigger a full resync (force replica to reload everything)
redis-cli -p 6380 REPLICAOF NO ONE
redis-cli -p 6380 REPLICAOF 192.168.1.10 6379

# partial resync (PSYNC): if the replica disconnects briefly,
# it can resume from the replication backlog (no full resync)
#   repl-backlog-size 1mb    (tune for longer disconnects)

# monitor replication in real-time
redis-cli -p 6379 INFO replication
# master_repl_offset, slave_read_repl_offset, backlog_size

# chain replication: a replica of a replica (tree topology)
# reduces load on the primary for many replicas
REPLICAOF replica-host 6380   # chain off another replica

# replication ID changes on every primary restart -> full resync
13

Streams

Stream 기본 (XADD/XREAD)

Streams가 Redis의 지속 메시징 구조입니다. append-only, 재생 가능, 소비자 그룹. ID는 타임스탬프 기반입니다(*로 자동 생성). $를 준 XREAD가 스트림을 tail하며(새 항목만) 0이면 처음부터 읽습니다. 스트림 상한은 MAXLEN이며(~가 근사로 훨씬 빠름) Streams가 Pub/Sub의 영속성 부재 문제를 해결하고 신뢰 큐 구축의 권장 방법입니다.

redis
# streams are append-only logs with IDs (durable, replayable)
# XADD: add an entry (auto-generate ID with *)
XADD mystream * sensor temp 25.5
# returns an ID like "1700000000000-0" (timestamp-sequence)

# add with a specific ID (must be greater than the last)
XADD mystream 1700000001000-0 sensor temp 26.0

# read entries
XREAD COUNT 10 STREAMS mystream 0        # from the beginning
XREAD COUNT 10 STREAMS mystream $        # new entries only (tail)

# block for new entries (like BLPOP for lists)
XREAD BLOCK 30000 STREAMS mystream $     # blocks up to 30s

# get the length
XLEN mystream                            # number of entries

# capped stream (keep only last N entries)
XADD mystream MAXLEN 1000 * field value
XADD mystream MAXLEN ~ 1000 * field value  # ~ = approx (faster)

소비자 그룹

소비자 그룹이 병렬 처리를 가능하게 합니다. 각 항목이 그룹의 정확히 한 소비자에게 전달됩니다. '>'가 새 항목을 읽고, '0'이 이 소비자의 (unacked) 대기 항목을 읽습니다. 처리 표시는 XACK입니다. 전달됐지만 ack 안 된 대기 항목이 처리 로그를 이루며, 막힌 메시지 찾기는 XPENDING, 타임아웃 후 다른 소비자에게 재할당은 XCLAIM입니다.

redis
# create a consumer group at a specific position
XGROUP CREATE mystream mygroup $        # only new entries
XGROUP CREATE mystream mygroup 0        # all existing entries
XGROUP CREATE mystream mygroup 0 MKSTREAM  # create stream if missing

# read entries as a consumer (assigns pending entries)
XREADGROUP GROUP mygroup consumer1 COUNT 10 STREAMS mystream >
# '>' = never-delivered entries

# read pending entries (for this consumer, not yet acked)
XREADGROUP GROUP mygroup consumer1 STREAMS mystream 0

# acknowledge processing (removes from pending)
XACK mystream mygroup <id1> <id2>

# view pending entries (pending entries list)
XPENDING mystream mygroup
# returns: count, min-id, max-id, consumers

# view a consumer's pending entries
XPENDING mystream mygroup - + 10 consumer1

Stream 처리와 복구

XAUTOCLAIM이 신뢰 처리의 열쇠입니다. 너무 오래 대기한 항목(소비자 크래시나 정체)을 건강한 소비자에게 재할당합니다. 아직 처리 중인 항목 훔치기를 막는 것은 min-idle-time입니다. 스트림 크기 경계는 XTRIM이며(메모리에 필수) ID로 범위 읽기는 XRANGE입니다. 모니터링용 stream/group/consumer 상태는 XINFO입니다. 완전하고 지속적인 메시지 큐입니다.

redis
# XCLAIM: reassign a pending entry to another consumer
# (after the original consumer died or is too slow)
XCLAIM mystream mygroup consumer2 60000 <entry-id>
# 60000 = min idle time (ms) before claiming

# XAUTOCLAIM (6.2+): auto-claim stale pending entries
XAUTOCLAIM mystream mygroup consumer2 60000 0 COUNT 10
# claims entries idle > 60s, returns them to consumer2

# view stream info
XINFO STREAM mystream FULL
XINFO GROUPS mystream
XINFO CONSUMERS mystream mygroup

# delete an entry (rarely needed)
XDEL mystream <id>

# trim the stream (free memory)
XTRIM mystream MAXLEN 10000
XTRIM mystream MINID 1700000000000   # remove older than this ID

# range queries
XRANGE mystream - +                   # all entries
XRANGE mystream 1700000000000 - 1700000009999 -

Stream 사용 사례

Streams가 신뢰 큐, 이벤트 소싱, 시계열 데이터에 탁월합니다. (XADD + XREADGROUP + XACK의) 소비자 그룹 패턴이 (대기 항목의) 내장 재시도와 (XAUTOCLAIM의) 복구를 갖춘 리스트 기반 큐의 완전한 대체입니다. 시계열의 메모리 경계 유지는 MAXLEN입니다. Streams가 가장 기능 완전한 Redis 구조이며 내구성과 순서 처리가 필요하면 언제든 쓰세요.

redis
# 1. Reliable task queue (replaces lists + BRPOPLPUSH)
XADD tasks * type email payload '{"to":"[email protected]"}'
XREADGROUP GROUP workers worker1 COUNT 1 STREAMS tasks >
# process and XACK on success

# 2. Event sourcing / audit log
XADD events * user 1 action login ip 1.2.3.4
# replay with XRANGE for reconstruction

# 3. Real-time analytics (time-windowed)
XADD metrics * cpu 75 mem 60
XRANGE metrics - +           # query by time range

# 4. Chat history (capped)
XADD chat:room:1 MAXLEN ~ 1000 * user alice msg "hello"
XREAD COUNT 20 STREAMS chat:room:1 0

# 5. IoT sensor data (with TTL via trimming)
XADD sensors:temp MAXLEN ~ 86400 * value 22.5  # keep last day

Streams vs 기타 큐

Streams가 Redis 네이티브 큐입니다. Kafka/RabbitMQ보다 단순하며 RAM에 들어가는 대부분의 워크로드에 충분합니다. Kafka의 파티션 수준 병렬성(하나의 스트림 = 하나의 샤드)이 없지만 소비자 그룹이 워커 병렬성을 제공합니다. 매우 높은 처리량이나 디스크 기반 내구성에는 Kafka가, 복잡한 라우팅에는 RabbitMQ가 이깁니다. Redis를 이미 쓰는 대부분의 앱에서 신뢰 메시징의 올바른 기본은 Streams입니다.

redis
# Redis Streams vs Lists (for queues):
# Lists: LPUSH/BRPOP, simple, NO retry/recovery
# Streams: consumer groups, ACK, pending, XAUTOCLAIM

# Redis Streams vs Kafka:
# Streams: in-memory (RAM-bounded), simpler, single-node or cluster
# Kafka: disk-based, partitioned, higher throughput at scale

# Redis Streams vs RabbitMQ:
# Streams: simpler, fewer features, in-memory
# RabbitMQ: rich routing, exchanges, acknowledgments, disk

# Streams capacity: limited by RAM (use MAXLEN/MINID to trim)
# Streams persistence: RDB/AOF (like any Redis data)

# choose Streams when:
# - you need a queue but already use Redis
# - dataset fits in RAM
# - you want simplicity over Kafka's scale
# - you need consumer groups with retry
14

HyperLogLog, 비트맵, Geo

HyperLogLog (카디널리티)

HyperLogLog(HLL)가 고정 12KB로 약 0.81% 오차의 고유 요소를 셉니다. 상수 메모리로 수십억 항목을 셉니다. 일/주/월별 고유 방문자 같은 분석에 완벽합니다. HLL 결합(예: 일별에서 월별 고유)은 PFMERGE입니다. 절충은 근사이므로 정확한 개수나 멤버십 검사(SISMEMBER)가 필요하면 셋, 개수만 필요하면 HLL을 쓰세요.

redis
# HyperLogLog: approximate unique count with fixed 12KB memory
# perfect for counting unique visitors, IPs, etc. at scale

# add elements (returns 1 if the cardinality changed)
PFADD visitors:2025-01-01 "user:1" "user:2" "user:3"

# get the approximate unique count
PFCOUNT visitors:2025-01-01        # ~3

# merge multiple HLLs (e.g., monthly uniques from daily)
PFMERGE visitors:2025-01 visitors:2025-01-01 visitors:2025-01-02

# accuracy: ~0.81% standard error
# memory: always ~12KB regardless of element count (up to 2^64)

# vs a Set for unique counting:
# SADD + SCARD: exact, but O(N) memory (grows with count)
# PFADD + PFCOUNT: approximate, fixed 12KB memory
# 1 million uniques: Set ~10MB, HLL always 12KB

비트맵 심화

비트맵이 사용자당 1비트를 저장합니다. 백만 사용자 = 125KB, 40억 = 512MB. 비트맵 결합(리텐션, 이탈 분석)은 BITOP AND/OR/XOR/NOT이고 첫 설정 비트 찾기는 BITPOS입니다. 사용 사례: DAU, 피처 플래그, 출석, A/B 테스트 그룹. 한계: (간격이 공간을 낭비하는) 밀집 정수 사용자 ID가 필요합니다. 희소 데이터에는 셋이나 HyperLogLog를 선호하세요.

redis
# bitmaps: boolean operations on a string's bits
# ideal for per-user flags over a large user base (user ID = bit position)

# mark user 7 as "active today"
SETBIT active:2025-01-01 7 1

# check if user 7 was active
GETBIT active:2025-01-01 7          # 1

# count active users
BITCOUNT active:2025-01-01

# users active on BOTH days (AND)
BITOP AND active:both active:2025-01-01 active:2025-01-02
BITCOUNT active:both

# users active on EITHER day (OR)
BITOP OR active:either active:2025-01-01 active:2025-01-02

# users active on day 1 but NOT day 2 (XOR or AND NOT)
BITOP XOR diff active:2025-01-01 active:2025-01-02

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

# memory: 1 million users = 125KB (1 bit per user)

지리 공간 (GEO)

GEO 명령이 지리 점을 저장하고 반경/박스 쿼리를 지원합니다. (점수 = geohash인) 정렬 셋 위에 구축됩니다. (GEORADIUS를 대체하는 6.2+의) GEOSEARCH가 (WITHCOORD, WITHDIST, ASC/DESC 같은) 풍부한 옵션으로 근처 점을 찾습니다. 거리는 구에서 계산되며 대부분의 앱에 정확도가 좋습니다. (다각형, 라우팅 같은) 복잡한 GIS에는 전용 공간 데이터베이스를 쓰세요. GEO가 '근처 찾기' 기능에 완벽합니다.

redis
# GEO: built on sorted sets, stores (lng, lat, name) points
# add locations (longitude, latitude, name)
GEOADD places -73.99 40.73 "Park" -73.98 40.75 "Museum" -74.00 40.70 "Cafe"

# get coordinates of a member
GEOPOS places "Park"               # [["-73.99","40.73"]]

# distance between two members (meters by default)
GEODIST places "Park" "Museum"     # "1623.5"
GEODIST places "Park" "Museum" km  # "1.623"

# find members within a radius (meters)
GEOSEARCH places FROMMEMBER "Park" BYRADIUS 1000 m ASC
# members within 1km of Park, sorted by distance

# find members within a bounding box
GEOSEARCH places FROMLONLAT -73.99 40.73 BYBOX 2 2 km

# GEOSEARCH also returns distance and coordinates
GEOSEARCH places FROMMEMBER "Park" BYRADIUS 500 m WITHCOORD WITHDIST

지리 공간 연산

GEO는 정렬 셋 위에 구현되며 좌표의 geohash가 점수입니다. 따라서 일부 연산(ZREM, ZRANGE)에는 Z* 명령을 쓸 수 있습니다. (거리, 좌표, geohash의) 풍부한 결과 반환은 GEOSEARCH이며 결과 제한은 COUNT입니다(가까운 N개는 ASC와 함께). 추가 처리용 결과 저장은 GEOSEARCHSTORE입니다. 극지방 근처에서 geohash 정밀도가 떨어지지만 대부분의 실제 앱에는 괜찮습니다.

redis
# add multiple points at once
GEOADD cities -122.41 37.78 "San Francisco" -74.00 40.71 "New York"

# get the geohash of a member
GEOHASH places "Park"              # ["dr5reg..."]

# remove a member (uses ZREM internally)
ZREM places "Cafe"

# count members in an area (using ZCOUNT on the underlying zset)
ZCOUNT places -180 180             # all members

# GEOSEARCH with a center point and limiting results
GEOSEARCH places FROMLONLAT -73.99 40.73 \
  BYRADIUS 2000 m ASC COUNT 5      # nearest 5 within 2km

# GEOSEARCHSTORE: store results in a new key (6.2+)
GEOSEARCHSTORE nearby FROMLONLAT -73.99 40.73 BYRADIUS 1000 m

# the underlying structure is a sorted set, so:
ZRANGE places 0 -1                 # list all members
ZSCORE places "Park"               # geohash score

특화 타입 선택

Redis가 핵심 5개 넘어 많은 특화 구조를 제공합니다. 근사 카디널리티는 HyperLogLog, 밀집 불리언 플래그는 비트맵, 근접성은 GEO입니다. 모듈이 (오탐이 있는) 멤버십 검사용 Bloom 필터, Top-K(heavy hitters), RedisTimeSeries(최적화된 시계열)를 더합니다. 데이터 형태와 정확도 요구에 구조를 맞추세요. 올바른 선택이 몇 자릿수의 메모리를 아낄 수 있습니다.

redis
# Cardinality counting (unique elements):
#   exact, need membership test  -> Set (SADD/SISMEMBER/SCARD)
#   approximate, huge scale      -> HyperLogLog (PFADD/PFCOUNT)
#   per-time-bucket uniques      -> HLL per day, PFMERGE for ranges

# Boolean flags over a dense ID space:
#   small number of flags        -> Set of active IDs
#   millions of users            -> Bitmap (SETBIT/BITCOUNT)
#   multiple counters compactly  -> BITFIELD

# Geographic points:
#   "find nearby" queries        -> GEO (GEOADD/GEOSEARCH)
#   complex GIS                  -> use PostGIS/external

# Time-series data:
#   simple, capped               -> Stream (XADD MAXLEN)
#   dedicated TS module          -> RedisTimeSeries (module)

# Probabilistic structures (modules):
#   Bloom filter                 -> RedisBloom (BF.ADD/BF.EXISTS)
#   Top-K                        -> RedisBloom (TOPK)
15

보안

인증과 ACL

Redis 6+ ACL이 단일 비밀번호 모델을 대체하며 범위 지정 권한의 사용자를 만듭니다. 문법: on(활성), >password, ~pattern(키 패턴), +command/-command, +@category/-@category(예: +@read, -@dangerous). 앱마다 항상 최소 권한 사용자를 만드세요. 영속화를 위해 ACL을 파일에 저장하세요. 프로덕션에서 기본 사용자를 절대 쓰지 말고 비활성화하거나 강한 비밀번호를 설정하세요.

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

# Redis 6+: ACL system with users and permissions
# add a user with limited access
ACL SETUSER appuser on >secretpassword ~app:* +get +set +del -@dangerous

# list users
ACL LIST
ACL WHOAMI                # current user

# view a user's permissions
ACL GETUSER appuser

# delete a user
ACL DELUSER appuser

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

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

TLS/SSL 암호화

TLS가 전송 중 데이터를 암호화하며 (신뢰할 수 없는 네트워크를 넘을 때 특히) 프로덕션에 필수입니다. Redis 6+가 TLS를 네이티브 지원합니다. mTLS(tls-auth-clients yes)가 클라이언트 인증서 제시를 요구해 비밀번호 없이 상호 인증을 제공합니다. 클러스터/센티널에서는 노드 간 통신에도 TLS를 켜세요. 평문 포트 비활성화는 포트 0이며 마이그레이션 중에는 임시로 두 포트를 모두 실행할 수 있습니다.

redis
# enable TLS in redis.conf (Redis 6+)
# generate certs first (or use a real CA):
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-cluster yes              # TLS between cluster nodes
tls-replication yes          # TLS between primary/replica
tls-auth-clients yes         # require client certs

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

네트워크 보안

Redis에는 네이티브 네트워크 접근 제어가 없으므로 bind + protected-mode + 방화벽을 쓰세요. Redis를 인터넷에 절대 노출하지 마세요(인증 없는 공개 Redis로 셀 수 없는 침해). protected-mode가 비밀번호가 없을 때 외부 연결을 막습니다. (FLUSHALL, CONFIG, KEYS의) 위험 명령 비활성화는 rename-command이지만 (6.0+의) ACL이 현대적 접근입니다. Redis를 사설 서브넷에 두고 VPN이나 bastion을 통해 접근하세요.

redis
# bind to specific interfaces (never 0.0.0.0 in prod)
bind 127.0.0.1 10.0.0.5
protected-mode yes            # blocks external access if no password

# require authentication
requirepass "strong-random-password"

# rename dangerous commands (or disable them)
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command CONFIG "CONFIG_9f8a7b"
rename-command KEYS ""

# Redis 6+: better to use ACLs instead of rename-command
# ACL SETUSER default -flushall -config -keys

# disable debug commands
# ACL SETUSER default -@dangerous

# use a firewall / security group to restrict access
# Redis should NEVER be directly internet-accessible
# (the 2018+ ransom attacks scanned for open Redis instances)

감사와 로깅

SLOWLOG가 (SLO에 맞춰 임계값을 설정해 예: 10ms) 느린 명령을 성능 감사용으로 기록합니다. 모든 명령 로그는 MONITOR이며(거대한 성능 영향. 디버그 전용) 지연 스파이크 찾기는 LATENCY MONITOR입니다. 연결 클라이언트 표시는 CLIENT LIST이며(누수 주시) 프로덕션 로그 레벨은 'notice'입니다(debug는 너무 장황). 분석을 위해 로그를 중앙 시스템으로 보내세요.

redis
# log slow commands (slowlog)
CONFIG SET slowlog-log-slower-than 10000   # 10ms in microseconds
CONFIG SET slowlog-max-len 128             # keep 128 entries
SLOWLOG GET 10                             # last 10 slow commands
SLOWLOG RESET

# log to a file (redis.conf)
logfile /var/log/redis/redis.log
loglevel notice    # debug|verbose|notice|warning

# monitor all commands (debugging only — huge perf impact)
MONITOR

# latency monitoring
CONFIG SET latency-monitor-threshold 100   # 100ms
LATENCY HISTORY event-name
LATENCY DOCTOR                              # analysis report

# client list (who's connected)
CLIENT LIST
CLIENT GETNAME
CLIENT SETNAME "my-app"

보안 베스트 프랙티스

Redis 보안은 겹겹이입니다. 네트워크(bind/방화벽), 인증(비밀번호/ACL), 전송(TLS), 명령 제한(ACL/rename), 감사(slowlog/monitor). 1위 규칙: Redis를 인터넷에 직접 노출하지 마세요. 내장 요율 제한이나 무차별 대입 보호가 없습니다. RDB/AOF 파일은 (평문으로 데이터를 담으므로) 디스크 수준에서 암호화하세요. 보안 패치를 위해 Redis를 최신으로 유지하세요.

redis
# 1. NEVER expose Redis to the public internet
bind 127.0.0.1
protected-mode yes

# 2. Use strong passwords or ACLs
requirepass "<64-char-random-string>"
# or ACLs with least privilege

# 3. Enable TLS for transit encryption
tls-port 6379

# 4. Restrict dangerous commands
ACL SETUSER default -@dangerous -flushall -keys

# 5. Use a firewall / security group
# allow only app servers on the Redis port

# 6. Rotate credentials regularly
ACL SETUSER appuser on >newpassword ~app:* +@read +@write

# 7. Audit access
LOGICALDB MONITOR  # or use an audit module

# 8. Encrypt sensitive data at rest (disk encryption)
# RDB/AOF files can contain sensitive data

# 9. Keep Redis updated (security patches)
# 10. Isolate environments (separate dev/staging/prod)
16

성능과 최적화

성능 기본

Redis의 명령 실행은 단일 스레드이며 느린 명령 하나가 '모든' 클라이언트를 막습니다. 큰 구조에 KEYS, SMEMBERS, DEL을 프로덕션에서 절대 쓰지 마세요. 대신 SCAN 계열, HSCAN, (비동기 삭제인) UNLINK를 쓰세요. 왕복 감소를 위한 명령 파이프라인. 각 명령의 Big-O를 알아 두세요. O(1)과 O(log N)은 안전하고 O(N) 명령은 (작은 범위의 LRANGE처럼) 경계를 둬야 합니다.

redis
# Redis is single-threaded (mostly) — avoid blocking commands
# DANGEROUS on large datasets (block the server):
KEYS *              # use SCAN instead
SMEMBERS bigset     # use SSCAN
HGETALL bighash     # use HSCAN
DEL hugekey         # use UNLINK (async delete)
FLUSHDB             # use FLUSHDB ASYNC

# use UNLINK instead of DEL for large keys (non-blocking)
UNLINK bigkey       # deletes in a background thread

# favor pipelining and batch commands
MGET k1 k2 k3       # one round-trip, not three GETs
LPUSH list a b c    # one command, not three

# prefer structurally efficient commands
# O(1): GET, SET, HGET, SISMEMBER, ZSCORE
# O(log N): ZADD, ZRANGE
# O(N): LRANGE, SMEMBERS, KEYS, SORT

파이프라이닝과 배치 연산

파이프라이닝이 단일 최대 Redis 성능 레버입니다. 명령을 한 번의 네트워크 왕복으로 배칭하면 10~100배 가속이 가능합니다. 왕복당 비용은 네트워크 지연(약 0.1~1ms)이며 1000개 개별 명령 = 100~1000ms이지만 파이프라인은 약 1ms입니다. 과도한 파이프라인은 금물입니다(큐잉된 응답이 메모리를 소비). 스위트 스팟 찾기는 redis-benchmark -P입니다. 트랜잭션이 자동 파이프라이닝을 씁니다.

redis
# pipelining: send many commands without waiting for replies
# (reduces round-trip time — huge speedup over network)

# example (Node.js with ioredis):
const pipeline = redis.pipeline()
for (let i = 0; i < 1000; i++) {
  pipeline.set(`key:${i}`, "value")
}
await pipeline.exec()        # one round-trip for 1000 commands

# transactions (MULTI/EXEC) are automatically pipelined
redis.multi().set("k", "v").incr("c").exec()

# MSET/MGET batch in one command
MSET k1 v1 k2 v2 k3 v3
MGET k1 k2 k3

# benchmark pipelining
redis-benchmark -t set -n 100000 -P 16   # -P = pipeline size

# don't pipeline too many at once (memory for queued replies)
# batch in groups of 100-1000

메모리 최적화

메모리가 Redis의 1차 제약입니다. 올바른 구조를 쓰세요. 객체에는 해시(listpack 인코딩이 별도 키보다 5~10배 작음). 컴팩트 형태 유지를 위한 인코딩 임계값 튜닝. ('작은 키를 하나의 해시로 묶는') 키 버킷팅이 키당 오버헤드를 극적으로 줄입니다. OOM 방지를 위해 maxmemory + eviction 정책을 설정하세요. used_memory와 단편화 비율을 모니터링하세요.

redis
# use the right data structure (memory vs speed trade-offs)
# store small objects as hashes (listpack encoding is compact)
HSET user:1 name "Alice" age 30   # better than 3 string keys

# tune encoding thresholds (redis.conf)
hash-max-listpack-entries 128     # hash -> hashtable above this
hash-max-listpack-value 64        # field value size limit
list-max-listpack-size -2         # listpack max size
set-max-intset-entries 512        # intset -> hashtable above this
zset-max-listpack-entries 128

# use hashes for many small keys (key bucketing)
# instead of SET user:1:clicks 5; SET user:2:clicks 3
# use HSET clicks user:1 5 user:2 3

# monitor memory
INFO memory | grep used_memory_human
MEMORY STATS

# set maxmemory and an eviction policy
maxmemory 4gb
maxmemory-policy allkeys-lru

Eviction 정책

eviction 정책이 메모리가 가득 찰 때의 동작을 제어합니다. 순수 캐시: allkeys-lru 또는 allkeys-lfu(치우친 접근 패턴에는 LFU가 더 낫음). 데이터베이스: noeviction(데이터 손실보다 쓰기 실패). 혼합용: volatile-lru(TTL이 있는 키만 쫓아내고 영속 키 유지). (4.0+의) LFU가 접근 빈도를 추적하며 LRU를 이기는 경우가 많습니다. maxmemory를 올바르게 정하려 evicted_keys를 모니터링하세요.

redis
# when maxmemory is reached, Redis evicts keys per the policy
# maxmemory-policy options:

# no eviction (writes fail with OOM error)
maxmemory-policy noeviction

# LRU (Least Recently Used) — approximate LRU
allkeys-lru         # evict any key (cache use case)
volatile-lru        # only evict keys with TTL set

# LFU (Least Frequently Used) — better for skewed access
allkeys-lfu
volatile-lfu

# random eviction
allkeys-random
volatile-random

# TTL-based (evict soonest-expiring)
volatile-ttl

# for a cache: allkeys-lru or allkeys-lfu (best hit rate)
# for a database: noeviction (never lose data silently)
# mixed (some persistent, some cache): volatile-lru

벤치마킹

redis-benchmark가 부하 하의 처리량과 지연을 측정합니다. -c(동시성)가 클라이언트를 시뮬레이트하고 -P(파이프라이닝)가 배칭 성능을 시험합니다. 실시간 왕복 시간 표시는 --latency입니다. 정확한 결과를 위해 Redis에 가까운 머신에서 벤치마크하세요(네트워크가 지배). 멀티스레드 벤치마킹은 (Redis 6+의) --threads입니다. 전형 단일 노드 성능: 상용 하드웨어에서 100K+ ops/sec.

redis
# redis-benchmark: built-in performance testing
redis-benchmark -t set,get -n 100000 -c 50
# -t: test commands, -n: number of requests, -c: concurrent clients

# test with pipelining
redis-benchmark -t set -n 100000 -c 50 -P 16

# test a specific command with a specific key
redis-benchmark -t get -n 100000 -r 100000 -q
# -r: random keys (INSERT random keys for testing)

# latency check (100 requests, shows distribution)
redis-cli --latency
redis-cli --latency-history    # rolling update
redis-cli --latency-dist       # histogram

# in-memory test (no network overhead)
redis-benchmark -t set -n 100000 -q --threads 4

# monitor while benchmarking
redis-cli INFO stats | grep instantaneous_ops_per_sec
17

관리

서버 정보와 모니터링

INFO가 대표적인 모니터링 명령입니다. memory, clients, persistence, stats 섹션을 정기 확인하세요. 자동 분석 제공은 MEMORY DOCTOR와 LATENCY DOCTOR이고 느린 명령 포착은 SLOWLOG입니다. 모든 연결 표시는 CLIENT LIST이며(누수 주시. 각 클라이언트가 메모리를 소비) (메모리, 연결, 복제 지연의) 역사 그래프와 알림은 (Prometheus + redis_exporter, Datadog 같은) 외부 모니터링으로 구축하세요.

redis
# 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 keyspace         # keys per database

# real-time stats
LATENCY DOCTOR        # latency analysis
MEMORY DOCTOR         # memory analysis

# live monitoring (subscribe to a special channel)
SUBSCRIBE __redis__:invalidate

# slow query log
SLOWLOG GET 10
SLOWLOG LEN

# client connections
CLIENT LIST
CLIENT KILL ID <id>   # disconnect a client

클라이언트 관리

CLIENT LIST가 주소, 이름, 현재 명령으로 연결을 식별합니다. 누수나 막힌 클라이언트 찾기에 귀중합니다. 연결 식별을 쉽게 하는 레이블은 CLIENT SETNAME이며(앱에서 연결 시 설정) 안전한 마이그레이션/스냅샷을 위한 임시 클라이언트 블로킹은 CLIENT PAUSE입니다. 유휴 연결 정리를 위한 타임아웃 설정과 (각 클라이언트가 어느 정도 메모리를 쓰는) 연결 고갈 방지는 maxclients입니다.

redis
# list all connected clients
CLIENT LIST
# id, addr, name, age, idle, flags, db, cmd

# name your connections (for identification)
CLIENT SETNAME "my-app-worker-1"

# get the current client's info
CLIENT INFO

# get the current client's ID
CLIENT ID

# kill a client
CLIENT KILL ADDR 1.2.3.4:12345
CLIENT KILL ID 42
CLIENT KILL TYPE normal    # kill all normal clients

# pause clients (for maintenance, 10 seconds)
CLIENT PAUSE 10000

# set a timeout for idle clients
CONFIG SET timeout 300    # 5 minutes

# max clients
CONFIG SET maxclients 10000

설정

CONFIG SET이 재시작 없이 런타임에 설정을 바꾸고 redis.conf 영속화는 CONFIG REWRITE입니다. 스테이징에서 항상 설정 변경을 테스트하세요. 핵심 프로덕션 설정: maxmemory + eviction 정책(OOM 방지), save + appendonly(영속성), tcp-keepalive(죽은 클라이언트 감지), timeout(유휴 연결 정리). redis.conf는 버전 관리하세요. 전체 표시는 CONFIG GET *이며 감사에 유용합니다.

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

# change config at runtime
CONFIG SET maxmemory 4gb
CONFIG SET maxmemory-policy allkeys-lru
CONFIG SET slowlog-log-slower-than 10000

# persist config changes to redis.conf
CONFIG REWRITE

# view all config (large output)
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

디버깅과 문제 해결

메모리 디버깅용 내부 표현 공개는 OBJECT ENCODING이고, (eviction 후보인) 콜드 키 찾기는 OBJECT IDLETIME이며 메모리 잡아먹는 것 식별은 키별 MEMORY USAGE입니다. 앱이 지연을 어떻게 다루는지 시험은 DEBUG SLEEP이고 이벤트(expired, eviction, fast keys) 추적은 LATENCY입니다. (4.0+의) 능동적 조각 모음이 온라인으로 조각난 메모리를 자동 회수합니다. 프로덕션의 DEBUG 명령은 아껴 쓰세요.

redis
# check if a key exists and its type
EXISTS mykey
TYPE mykey
OBJECT ENCODING mykey
OBJECT IDLETIME mykey     # seconds since last access

# memory usage per key
MEMORY USAGE mykey

# find keys blocking the server (DEBUG SLEEP for testing)
DEBUG SLEEP 2             # blocks for 2 seconds (testing only)

# check the latency
LATENCY HISTORY event
LATENCY GRAPH event

# object frequency (LFU mode)
OBJECT FREQ mykey

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

# last saved RDB timestamp
LASTSAVE

# active defragmentation (4.0+)
CONFIG SET activedefrag yes
MEMORY MALLOC-STATS

업그레이드와 유지보수

무중단 업그레이드는 복제를 쓰세요. 먼저 레플리카 업그레이드, 페일오버, 그다음 이전 프라이머리 업그레이드. 클러스터는 한 노드씩 롤링 재시작합니다(먼저 페일오버된 프라이머리). 업그레이드 전 항상 백업(BGSAVE + RDB 복사)하세요. 파괴적 변경은 릴리스 노트를 읽고 스테이징에서 테스트하세요. Redis가 마이너 버전 간 하위 호환을 유지하지만 메이저 버전에는 마이그레이션 단계가 있을 수 있습니다.

redis
# upgrade a standalone Redis:
# 1. save the dataset
SAVE
# 2. stop Redis
redis-cli SHUTDOWN
# 3. replace the binary
# 4. start the new version
redis-server /etc/redis/redis.conf

# upgrade a primary/replica pair (zero downtime):
# 1. upgrade the REPLICA first
SHUTDOWN
# 2. start new version on replica
# 3. promote replica to primary (SENTINEL FAILOVER)
# 4. upgrade the old primary (now a replica)
# 5. failback if desired

# upgrade a cluster:
# 1. upgrade one node at a time (rolling)
# 2. for each node: CLUSTER FAILOVER (if primary), upgrade, restart

# always back up before upgrading
# check the release notes for breaking changes
# test the upgrade in staging first

# rolling restart of a cluster (script)
for node in $nodes; do
  redis-cli -h $node CLUSTER FAILOVER
  redis-cli -h $node SHUTDOWN
  ssh $node "systemctl start redis"
done
18

흔한 패턴

캐싱 패턴 (Cache-Aside)

cache-aside가 가장 흔한 Redis 패턴입니다. 캐시에서 읽고, 미스 시 DB로 폴백하고, 캐시를 채웁니다. 오래됨 경계를 위한 TTL 설정. 쓰기는 write-through(DB 쓰기 시 캐시 갱신)나 무효화(캐시 키 삭제)입니다. 무효화가 더 안전합니다(재채움 경쟁 없음) 하지만 write-through가 캐시를 따뜻하게 유지합니다. 캐시 스탬피드 보호: 미스 시 많은 요청이 동시에 DB를 치지 않게 락이나 'dogpile' 패턴을 쓰세요.

redis
# cache-aside: app checks cache, falls back to DB, fills cache
# pseudo-code:
function get_user(id):
  # 1. check cache
  data = GET("user:" + id)
  if data:
    return JSON.parse(data)

  # 2. cache miss -> query database
  data = db.query("SELECT * FROM users WHERE id = ?", id)

  # 3. fill cache (with TTL to avoid stale data)
  SET("user:" + id, JSON.stringify(data), "EX", 3600)

  return data

# write-through: update cache when DB changes
function update_user(id, data):
  db.update(id, data)
  SET("user:" + id, JSON.stringify(data), "EX", 3600)

# cache invalidation:
DEL("user:" + id)   # when the DB record is deleted

분산 락

SET NX EX의 분산 락은 단순하지만 주의가 필요합니다. (보유자 크래시 시 교착 방지를 위해) 항상 TTL을 설정하고, (Lua의 원자적 확인-삭제로) 자기 락만 해제하려 고유 토큰을 쓰세요. 더 높은 안전성은 여러 독립 Redis 인스턴스를 쓰는 Redlock 알고리즘입니다. 락은 완벽히 안전하지 않습니다(시계 드리프트, GC 일시정지). 강한 정확성 보장에는 합의 시스템(etcd, ZooKeeper)을 고려하세요. 대부분의 실용적 조율에는 Redis 락으로 충분합니다.

redis
# SET NX with expiry = simple distributed lock
SET lock:resource "token-abc" NX EX 10
# returns OK if acquired, nil if already held

# release: only delete if the value matches (avoid releasing others' locks)
# (requires a Lua script for atomicity)
EVAL "
  if redis.call('GET', KEYS[1]) == ARGV[1] then
    return redis.call('DEL', KEYS[1])
  end
  return 0
" 1 lock:resource "token-abc"

# Redlock algorithm (multi-instance, higher safety):
# 1. get the time
# 2. SET NX on N (usually 5) independent Redis instances
# 3. if acquired on majority (3/5) within validity window -> locked
# 4. otherwise, release on all instances and retry

# lock options:
#   EX 10        # expire after 10 seconds (safety)
#   NX           # only if not exists
#   "token"      # unique value per lock holder (for safe release)

Rate Limiting

고정 윈도우(INCR+EXPIRE)가 가장 단순하지만 윈도우 경계에서 2배 스파이크를 허용합니다. (타임스탬프의 정렬 셋인) 슬라이딩 윈도우가 더 정확하지만 메모리를 더 씁니다. 최대까지의 버스트를 허용하는 것은 토큰 버킷입니다. (동시성 하의 정확성에 중요) Lua 스크립트로 모두 원자적일 수 있습니다. 규모 있는 사용자별 레이트 리밋에는 고정 윈도우 접근이 보통 충분하고 매우 메모리 효율적입니다.

redis
# fixed window rate limiter (simple)
# INCR + EXPIRE on first request
count = INCR("rate:user:1")
if count == 1:
  EXPIRE("rate:user:1", 60)   # 60-second window
if count > 100:
  return "Rate limited"

# sliding window rate limiter (sorted set)
now = current_time_millis()
ZADD("rate:user:1", now, now)         # add current request
ZREMRANGEBYSCORE("rate:user:1", 0, now - 60000)  # remove old
EXPIRE("rate:user:1", 60)
count = ZCARD("rate:user:1")          # current count
if count > 100:
  return "Rate limited"

# token bucket (Lua script for atomicity)
# maintains a bucket of tokens refilled over time
# see: https://redis.io/docs/patterns/distributed-locks/

# GCRA (Generic Cell Rate Algorithm) — elegant single-key version

리더보드와 순위

정렬 셋이 리더보드를 쉽게 만듭니다. 점수 갱신은 ZADD, top N은 ZREVRANGE, 플레이어 위치는 ZREVRANK입니다. 원자적 점수 갱신은 ZINCRBY입니다. (일/주별 같은) 시간 버킷 리더보드는 TTL이 있는 기간별 키를 쓰세요. 페이지네이션은 오프셋을 준 ZREVRANGE이며 백분위 순위는 ZCARD와 ZREVRANK 결합입니다. Redis의 가장 자연스럽고 강력한 사용 사례 중 하나입니다.

redis
# sorted set = perfect for leaderboards
ZADD leaderboard 100 "alice" 250 "bob" 150 "carol"

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

# a player's rank
ZREVRANK leaderboard "alice"     # 0-indexed from top

# 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

세션 스토어

Redis가 고전 세션 스토어입니다. 빠르고, TTL(자동 만료)을 지원하며, 앱 서버에 걸쳐 공유됩니다. (요청마다 갱신하는) 슬라이딩 TTL의 세션별 해시를 쓰세요. '모든 곳에서 로그아웃' 기능을 위해 사용자의 세션을 셋에서 추적하세요. 클러스터에서는 (사용자 세션과 세션 인덱스가 같은 샤드에 있도록) 해시 태그({user:1})를 쓰세요. 보안을 위해 로그인/권한 변경 시 세션 ID를 교체하세요.

redis
# Redis is ideal for web sessions (fast, expiring, shared)
# store session as a hash with TTL
HSET session:abc123 user_id 1 last_active 1700000000 data "..."
EXPIRE session:abc123 1800     # 30-minute timeout

# update session (and refresh TTL)
HSET session:abc123 last_active 1700001000
EXPIRE session:abc123 1800     # sliding expiration

# destroy a session
DEL session:abc123

# list active sessions for a user (index by user)
SADD user:1:sessions "session:abc123"
SMEMBERS user:1:sessions       # all session IDs

# cluster-friendly: use a hash tag for the user's sessions
SADD {user:1}:sessions "session:abc123"
# enables multi-key operations on the user's session data

# rotate session ID on privilege change (security)
RENAME session:old session:new
EXPIRE session:new 1800
19

Lua 스크립팅

EVAL 기본

EVAL이 Lua 스크립트를 원자적으로 실행합니다. 스크립트가 실행되는 동안 다른 명령이 실행되지 않아 다단계 원자적 연산에 이상적입니다. 호출자로부터의 데이터 전달은 KEYS와 ARGV이며, 스크립트 안에서 문자열 연결로 키를 만들지 마세요(클러스터 규칙 위반). redis.call이 오류를 raise하고(중단) redis.pcall이 반환합니다. 스크립트가 SHA1 해시로 캐시되므로 반복 호출의 효율은 EVALSHA입니다.

redis
# run a Lua script inline
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey "hello"
# 1 = number of keys
# mykey = KEYS[1]
# "hello" = ARGV[1]

# return types: string/integer/boolean/table (nil/true/false)
EVAL "return 42" 0
EVAL "return {1, 2, 3}" 0
EVAL "return redis.call('GET', KEYS[1])" 1 mykey

# 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와 스크립트 캐시

EVALSHA가 이전에 로드한 스크립트를 SHA1 해시로 실행해 매 호출마다 스크립트 본문을 재전송하지 않게 합니다. 같은 스크립트를 반복 실행하는 앱의 주요 대역폭 이득입니다. 캐시 미스 시(SCRIPT FLUSH나 재시작 뒤) Redis가 NOSCRIPT를 반환하고 클라이언트가 이를 잡아 EVAL + SCRIPT LOAD로 폴백합니다. 이를 투명히 처리하는 라이브러리(redis-py, ioredis)를 항상 쓰세요.

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

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

# check if a script is cached
SCRIPT EXISTS "fa00..." "abcd..."
# returns: 1) 1  2) 0

# flush the script cache
SCRIPT FLUSH

# list all running scripts (NOSCRIPT errors = cache miss -> reload)
SCRIPT DEBUG SYNC   # blocking debug mode
SCRIPT DEBUG NO     # disable

원자적 연산

Lua 스크립트가 Redis에서 (MULTI/EXEC 경쟁 없이) 원자적 다중 명령 연산의 정석 방법입니다. compare-and-set, 세마포어 획득, 큐 마이그레이션이 모두 이익을 봅니다. 스크립트가 실행 중 서버를 막으므로 짧게 유지하고 (다른 클라이언트를 정체시킬 수 있는) 많은 키를 도는 루프를 피하세요. 매우 긴 작업에는 (저장 프로시저처럼 선언·버전화되는) Redis Functions(Redis 7.0+)를 쓰세요.

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

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

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

Redis Functions (7.0+)

Redis Functions(7.0+)가 임시 EVAL 스크립트의 현대적 대체물입니다. (데이터베이스 저장 프로시저처럼) 등록, 이름, 버전화됩니다. 라이브러리가 여러 함수를 묶고 FCALL이 호출합니다. Functions는 RDB/AOF에 영속화되어(재시작 생존) 일시적 EVAL 캐시와 다릅니다. 사소하지 않은 로직의 스크립팅을 더 유지보수 가능하게 하고 감사와 버전 관리가 쉽습니다.

redis
# register a library of functions
FUNCTION LOAD "#!lua name=mylib
redis.register_function('myset', function(keys, args)
  return redis.call('SET', keys[1], args[1])
end)

redis.register_function('double', function(keys, args)
  local v = tonumber(redis.call('GET', keys[1]))
  return redis.call('SET', keys[1], v * 2)
end)
"

# call a function
FCALL myset 1 mykey "hello"
FCALL double 1 counter

# list libraries
FUNCTION LIST
FUNCTION LIST WITHCODE

# delete a library
FUNCTION DELETE mylib

# dump and restore (for backup / migration)
FUNCTION DUMP
FUNCTION RESTORE <payload>

스크립트 디버깅

반환 값에 영향 없이 Redis 로그로 메시지를 내보내는 디버깅은 redis.log()입니다. redis-cli --ldb가 인터랙티브 Lua 디버거이며 중단점 설정, 코드 스텝, 지역 검사가 가능합니다. 서버가 스크립트에서 막게 하는 것은 SCRIPT DEBUG SYNC이며 디버거가 스텝할 수 있습니다. 스크립트는 항상 스테이징에서 테스트하세요. 무모한 루프가 전체 Redis 서버를 잠글 수 있습니다. 복제 정확성을 위해 스크립트는 (랜덤/시간 없이) 결정적으로 유지하세요.

redis
# LOG writes to the Redis log (visible in redis-cli)
EVAL "redis.log(redis.LOG_NOTICE, 'hello from lua'); return 1" 0
# levels: LOG_DEBUG, LOG_VERBOSE, LOG_NOTICE, LOG_WARNING

# return the error object on pcall failure
EVAL "local ok, err = pcall(function()
  error('something broke')
end)
return {ok=tostring(ok), err=tostring(err)}" 0

# debugger (Redis 5.0+)
SCRIPT DEBUG SYNC   # synchronous, blocking
TDEBUG              # step / continue / print
# use redis-cli --ldb to launch debugger:
#   redis-cli --ldb --eval myscript.lua key1 key2 , arg1 arg2

# print variables in the debugger
print myvar
step
continue
20

모니터링과 문제 해결

INFO와 LATENCY

INFO가 단일 최중요 모니터링 명령입니다. 메모리, 클라이언트, 복제, 처리량을 한 번에 보고합니다. mem_fragmentation_ratio를 주시하세요(이상적 약 1.0~1.5). >1.5는 메모리 낭비이고 <1은 Redis가 스왑 중이라는 뜻입니다(지연에 재앙적). 최근 느린 이벤트 분석과 처방 제안은 LATENCY DOCTOR입니다. 캐시 히트율 추적은 keyspace_misses vs keyspace_hits 모니터링입니다.

redis
# INFO: server, clients, memory, stats, replication, cpu
INFO                # everything
INFO memory         # memory section only
INFO replication    # replica lag, master link
INFO stats          # ops/sec, keyspace hits/misses

# key metrics to watch:
#   used_memory_rss        # RSS from OS (real footprint)
#   mem_fragmentation_ratio # >1.5 = fragmentation, <1 = swapping (bad!)
#   connected_clients       # client connections
#   instantaneous_ops_per_sec
#   keyspace_misses         # cache hit ratio = hits / (hits + misses)

# LATENCY: samples slow events
LATENCY HISTORY event-name
LATENCY DOCTOR      # human-readable diagnosis
LATENCY RESET

# LATENCY GRAPH event-name (ASCII art)

SLOWLOG와 CLIENT LIST

SLOWLOG가 설정된 임계값(기본 10ms)보다 느린 명령을 포착합니다. 지연 스파이크를 일으키는 쿼리 찾기에 귀중합니다. 거대 셋의 (KEYS *, SMEMBERS 같은) KEYSPACE 연산이 흔한 범인입니다. CLIENT LIST가 유휴 시간과 현재 명령과 함께 모든 연결을 보여 주며, 막힌 클라이언트가 어느 풀에 속하는지 식별하려 앱 연결에 CLIENT SETNAME으로 레이블을 다세요.

redis
# SLOWLOG: record slow commands (over slowlog-log-slower-than, default 10ms)
CONFIG SET slowlog-log-slower-than 10000   # 10ms in microseconds
CONFIG SET slowlog-max-len 128             # keep last 128 entries

SLOWLOG GET          # last 10 slow commands
SLOWLOG GET 5        # last 5
SLOWLOG RESET        # clear

# each entry: id, timestamp, duration (us), command args, client, addr

# CLIENT LIST: see all connected clients
CLIENT LIST
# fields: id, addr, fd, name, age, idle, flags, db, cmd, ...

# kill a stuck client
CLIENT KILL ADDR 10.0.0.1:12345
CLIENT KILL ID 42

# name your connections for easier debugging
CLIENT SETNAME my-app-worker

MEMORY와 OBJECT

MEMORY USAGE가 하나의 키의 정확 바이트를 보고합니다(큰 컬렉션의 완전 정확도는 SAMPLES 0). Redis 내부 형식 공개는 OBJECT ENCODING이며, 작은 구조가 (CPU와 메모리 효율적인) 컴팩트 인코딩(listpack, ziplist)을 쓰다 커지면 해시 테이블/스킵리스트로 자동 승격됩니다. 인코딩을 알면 키가 예상보다 크거나 느린 이유 설명에 도움이 됩니다.

redis
# MEMORY USAGE: bytes used by a single key
MEMORY USAGE key
MEMORY USAGE bigset SAMPLES 0   # scan all elements (accurate)

# MEMORY STATS: detailed allocator stats
MEMORY STATS

# MEMORY DOCTOR: diagnosis
MEMORY DOCTOR

# OBJECT ENCODING: see internal representation
OBJECT ENCODING mylist      # quicklist / ziplist / listpack / hashtable
OBJECT REFCOUNT mykey
OBJECT IDLETIME mykey       # seconds since last access
OBJECT FREQ mykey           # LFU access frequency (only with maxmemory-policy LFU)

# why is my key so big? use DEBUG OBJECT (careful, can be slow)
DEBUG OBJECT mykey

Bigkey와 Keyspace 스캔

프로덕션에서 KEYS를 절대 쓰지 마세요. 서버를 막습니다. (커서 기반, 논블로킹인) 대안은 SCAN이며 커서가 0으로 돌아올 때까지 순회합니다. SCAN 기반의 CLI 헬퍼인 --bigkeys와 --memkeys가 막히지 않고 가장 큰 키를 드러냅니다. (수백만 요소의 컬렉션 같은) big key가 만료/eviction 중 지연 스파이크를 일으키므로 찾아 분할하세요(예: 거대 정렬 셋을 시간별 샤딩).

redis
# find big keys safely (production-safe, samples)
redis-cli --bigkeys
# scans keyspace, reports largest of each type

# more accurate: --memkeys (memory usage per key)
redis-cli --memkeys
redis-cli --hotkeys      # with LFU policy, finds frequently-accessed keys

# SCAN: iterate keys without blocking (never use KEYS *)
SCAN 0 MATCH user:* COUNT 100
# returns: next-cursor, [key1, key2, ...]
SCAN <next-cursor> ...
# cursor 0 = done

# scan a hash field-by-field
HSCAN myhash 0 COUNT 100
SSCAN myset 0 MATCH prefix*
ZSCAN myzset 0

# inspect a key's TTL (left to live)
TTL mykey           # seconds (-1 = no expire, -2 = no key)
PTTL mykey          # milliseconds

클러스터 헬스와 페일오버

클러스터 헬스의 대표 검사는 CLUSTER NODES와 CLUSTER INFO입니다. cluster_state:ok와 모든 슬롯 할당(총 16384)을 확인하세요. 레플리카의 CLUSTER FAILOVER가 통제된 마스터 전환을 트리거하며, FORCE가 초기 동기화를 건너뛰고(빠르지만 약간의 데이터 손실 위험) TAKEOVER가 클러스터 합의를 우회합니다(비상 시에만). 고아 슬롯이나 split-brain 상태를 잡으려 리샤드나 사고 뒤 항상 --cluster check을 실행하세요.

redis
# cluster node status
CLUSTER NODES
# fields: id, addr, flags (master/slave/fail?), slots, ping/pong

# cluster-wide health
CLUSTER INFO
# cluster_state:ok / cluster_slots_assigned / cluster_slots_ok
# cluster_known_nodes

# slot ownership (which node owns a key)
CLUSTER KEYSLOT mykey    # hash slot number
CLUSTER COUNTKEYSINSLOT 1234

# reshard slots (use redis-cli --cluster reshard)
redis-cli --cluster reshard 127.0.0.1:7000 \
  --cluster-from <node-id> --cluster-to <node-id> \
  --cluster-slots 1000 --cluster-yes

# manual failover (on a replica)
CLUSTER FAILOVER          # wait for sync
CLUSTER FAILOVER FORCE    # skip sync (faster, slight data loss risk)
CLUSTER FAILOVER TAKEOVER # no consensus (emergency only)

# verify cluster after changes
redis-cli --cluster check 127.0.0.1:7000
redis-cli --cluster fix 127.0.0.1:7000    # auto-repair minor issues

Was this helpful?