はじめに
Redis への接続
redis-cli は標準のコマンドラインクライアントです。PING で疎通確認(PONG が返る)ができます。本番では必ず AUTH コマンドか -a フラグを使いましょう。共有環境ではコマンドラインにパスワードを書かず、REDISCLI_AUTH 環境変数を使ってください。新しい Redis(6+)は権限を限定した ACL ベースのユーザーをサポートします。
# 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 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)を返します。
# 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 を返します。有効期限は遅延処理です — キーがアクセスされたときか、周期的なバックグラウンドスイープのときにのみチェックされます。SET with EX はアトミックです(SET と EXPIRE の間に競合が起きません)。期限切れキーはデフォルトでイベントを発火しません。必要なら keyspace notifications を有効にしましょう。
# 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 3600SCAN と安全な反復
SCAN は KEYS の本番向け代替です — カーソルを返し、0 に戻るまで追いかけます。COUNT は目安であって正確ではありません(多く返ったり少なく返ったりする)。SCAN は弱い保証しかなく、反復中に重複を返したり追加されたキーを見逃したりしますが、決してブロックしません。コレクション型には HSCAN/SSCAN/ZSCAN を使います。カーソルループは必ず自前のコードで処理しましょう。
# 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データ型の概観
基本的なデータ構造
正しいデータ構造を選ぶことが Redis の鍵です。カウンター/キャッシュには Strings、オブジェクトには hashes、キューには lists、一意性/タグには sets、ランキングには sorted sets、イベントログには streams。データ構造への各操作はアトミックなので、並行アクセスしても状態が壊れません。アクセスパターンに合う構造を選びましょう。
# 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適切な型の選び方
型はアクセスパターンで選びます。一意性が必要? Set。スコア順が必要? Sorted set。オブジェクトの 1 フィールドだけ更新したい? Hash(シリアライズした文字列ではない)。大規模な概算ユニーク数が必要? HyperLogLog(数十億要素でも 12KB)。正しい型選び=よりシンプルなコード、アトミックな操作、劇的なメモリ節約につながります。
# 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 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 growsOBJECT とメモリコマンド
OBJECT IDLETIME はコールドなキャッシュキー(あまりアクセスされない)を見つけるのに有用です。OBJECT FREQ は maxmemory-policy が LFU のときだけ機能します。MEMORY USAGE は SAMPLES 0 で正確に数えます(大きなコレクションはデフォルトでサンプリング)。COMMAND DOCS(Redis 7+)は構造化されたドキュメントを返します。これらの内観ツールはメモリ肥大のデバッグと退去ポリシーのチューニングに役立ちます。
# 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)。
# 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 listStrings
基本的な文字列操作
文字列はバイナリセーフです(512MB まで任意のバイトを保持でき、画像や JSON も含む)。SET with NX は古典的な Redis のロックプリミティブ(存在しない場合にだけセット)です。GETSET はアトミックで、設定の差し替えに便利です。SETRANGE は文字列を伸ばせます。構造化データにはシリアライズした JSON 文字列ではなく Hash を推奨 — フィールド単位の更新ができます。
# 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 と組み合わせた時間窓の統計に最も活きます。
# 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 は操作を 1 回の往復にまとめます — パフォーマンスに不可欠です(Redis はシングルスレッドなのでコマンドごとのオーバーヘッドが効いてきます)。MSETNX はアトミックで、すべてのキーがセットされるか 1 つもされないかです。GETDEL(6.2+)は取得と削除をアトミックに行い — 1 回だけ読むメッセージパターンに便利です。ネットワークレイテンシを減らすため、できる限りコマンドをバッチ化しましょう。
# 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ビットマップ(String ベース)
ビットマップはブールフラグを 1 ビットずつ保存し、約 512MB で 40 億ユーザー分を扱えます — 大規模な母集団に対して非常に省メモリです。BITOP AND/OR/XOR/NOT でビットマップを組み合わせられます(例: 複数日アクティブなユーザー)。BITCOUNT でアクティブユーザー数を数えます。ユースケース: 日次アクティブユーザー、フィーチャーフラグ、出席管理。位置=ユーザー ID です。
# 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-bitBitfield 操作
BITFIELD は複数の小さなカウンターを 1 つの文字列に詰め込みます — 例えば u8 の日次カウンター 1000 個が 1KB に収まります。OVERFLOW SAT は最大値で飽和し(統計向き)、FAIL はオーバーフロー時に nil を返し(上限設定向き)、WRAP は桁あふれで一周します(デフォルトで、通常は望ましくない)。多くの小さなカウンターを個別キーにするより、はるかにメモリ効率が良いです。
# 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 16Hashes
Hash の基本
Hash はオブジェクトの保存に理想的です — オブジェクトごとに 1 キー、プロパティごとにフィールド。JSON をシリアライズするより優れています。個々のフィールドをアトミックに(HSET)更新でき、読み取り・変更・書き込みのサイクルが不要だからです。HGETALL は全フィールドを返しますが、大きなハッシュでは HSCAN を推奨します。Hash は小さい間(約 128 フィールド未満)listpack エンコーディングを使い、メモリ効率が良いです。
# 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 # 3Hash のフィールド操作
HSETNX はフィールドレベルの 'set if not exists' を提供します(1 回限りの初期化に便利)。ハッシュフィールドへの HINCRBY はアトミックで — ユーザーごとのカウンター(ログイン回数、閲覧数)に完璧です。最後のフィールドを削除するとハッシュは自動的に消えます(HDEL)。HSET が複数フィールドを受け付けるようになったため HMSET は非推奨です — 常に HSET を使いましょう。
# 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 HSETHash の反復
HGETALL は大きなハッシュでサーバーをブロックします — 本番での反復には HSCAN を使いましょう。HSCAN はカーソルベースで、カーソルが 0 に戻るまで繰り返し呼びます。COUNT は目安です。HRANDFIELD(6.2+)はサンプリングに有用です(例: ランダムなフィーチャーフラグ)。数百万フィールドのハッシュは、シャーディングして複数キーに分けることを検討しましょう。
# 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 + valuesHash のフィールド有効期限(Redis 7.4+)
フィールドレベルの TTL(7.4+)は Hash の大きな新機能です — 以前は個々のフィールドを期限切れにするのに別キーや回避策が必要でした。生存期間の混在するオブジェクトに有用です(ユーザープロフィールで、セッショントークンは切れるが名前は残る、など)。古い Redis バージョンでは、期限付きのフィールドを個別のキーとして独自の EXPIRE で保存する必要があります。
# 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_tokenHash のユースケース
Hash はオブジェクトとグループ化されたカウンターで輝きます。強力なメモリテクニック: 小さな文字列キーが大量にあるとき、それらを 1 つのハッシュにまとめましょう — listpack エンコーディングは、(それぞれメタデータを持つ)何千もの個別キーよりはるか にオーバーヘッドが小さいです。この「キーバケット化」により小さい値で 5〜10 倍のメモリ削減が可能です。
# 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 v2Lists
List の基本(Push/Pop)
List は両端キューなので、LPUSH+RPOP = キュー(FIFO)、LPUSH+LPOP = スタック(LIFO)です。BLPOP/BRPOP は要素が入るまでブロックします — これが Redis キューの基盤(ポーリング不要)。切断に備えて BLPOP には必ずタイムアウトを設定しましょう。List は先頭/末尾の操作が O(1)、中間アクセスは O(N) です。
# 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 foreverList のインデックスと範囲
LRANGE 0 -1 はリスト全体を返します。LTRIM はリストのサイズに上限を設ける定番パターンです(例: 最新 100 イベントだけ残す)。LREM は値で削除します(count: 正=先頭から、負=末尾から、0=すべて)。LINDEX は中間要素に対して O(N) です — List は端への アクセスに最適化されています。インデックスでのランダムアクセスには別の構造を使いましょう。
# 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キューとしての List
BRPOPLPUSH/BLMOVE は要素をソースからデスティネーションへアトミックに移動します — コンシューマは安全に処理でき、クラッシュしても要素はデスティネーションに残ります(reliable queue パターン)。BRPOP の後に処理する方式より優れています。BRPOP の直後にクラッシュすると要素を失うからです。処理が終わったらデスティネーションのリストから削除しましょう。
# 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 100List の挿入と削除
LINSERT は O(N) なので — 大きなリストでは控えめに使いましょう。LPOS は要素を削除せずに位置を見つけます。LMPOP(7.0+)は複数のリストから 1 回の呼び出しで pop でき、優先度付きキューに便利です。リスト中ほどへの頻繁な操作には List は不向きです — sorted set か別のデータモデルを検討しましょう。
# 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 occurrenceList のユースケース
List は端アクセス型のシーケンスに最適です: キュー、スタック、フィード、バッファ。LTRIM と組み合わせると上限付きのログ/フィードに理想的です。レートリミットには、タイムスタンプのリスト+ LTRIM がシンプルなスライディングウィンドウになります。ソート済み/優先度付きキューには sorted set を使います。List は重複排除に対応していません — それは set の役割です。
# 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 windowSets
Set の基本
Set は一意な値を保存します — タグ、カテゴリ、重複排除に完璧です。SISMEMBER は O(1) で — リストのチェックよりはるかに速い。SMEMBERS は大きなセットでブロックし得るので、反復には SSCAN を使いましょう。SRANDMEMBER は削除せず、SPOP は削除します。全メンバーが整数なら Set は intset(ソート済み配列)を使い — 非常にメモリ効率が良いです。
# 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 oneSet 演算
Set 演算は Redis の得意技です — 和集合、積集合、差集合が O(N) で、クライアント側の処理は不要。ユースケース: 共通の友達(SINTER)、ユニーク訪問者(SUNION)、タグによる絞り込み(タグセットの SINTER)。SINTERCARD(7.0+)は件数だけを返し、メンバーが不要なら速いです。再計算を避けるため結果を保存しておきましょう。
# 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 0Set の反復と移動
SMOVE はアトミックです — 状態遷移に便利(例: ユーザーを 'pending' セットから 'active' セットへ移す)。大きなセットの安全な反復には SSCAN を使います。SMISMEMBER(7.4+)は所属判定をバッチ化し、往復を減らします。BSPOP(7.0+)は BLPOP の set 版のブロック動作です — 順序が問題にならないイベント駆動パターンに有用です。
# 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]Set のユースケース
Set は一意性とリレーションの扱い に最適です。互いのフォロワー/友達を求める SINTER パターンは古典です。巨大なカーディナリティの「1 日あたり訪問者」には HyperLogLog を検討しましょう(概算ですが固定 12KB)。順序付きの一意データ(ランキング)には sorted set を。Set は順序を持たないので — 順序が重要なら list か sorted set を使いましょう。
# 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 winnerSet と他の型の比較
型の選択こそ Redis 設計の核心です。一意性+高速な所属判定には Set(順序なし)。ランキング/順序付けには sorted set(メモリは増える)。重複を許すシーケンスには List。フィールドと値のオブジェクトには Hash。迷ったら、読み・書き・順序・一意性のアクセスパターンを書き出してみましょう — 正しい型が自ずと見えてきます。
# 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? -> HashSorted Sets
Sorted Set の基本
Sorted Set(zset)は Redis で最も強力な構造です — スコア順に並ぶ一意なメンバーで、操作は O(log N)。ZADD のオプション(NX/XX/GT/LT)で条件付き更新ができます: GT は新しいスコアが大きいときだけ更新します(「ベストスコア」の記録に最適)。スコアは double、メンバーは一意です。同点は辞書順で決まります。
# 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 はこれらを ZRANGE に統一しました(BYSCORE/BYLEX/REV オプション)。WITHSCORES を付けると出力にスコアが含まれます。ランキングなら ZREVRANGE 0 9 でトップ 10 です。ZRANGESTORE(6.2+)は結果を新しいキーに保存します。
# 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 はスコアをアトミックに調整して再ソートします — ライブのランキングに完璧です。ZREMRANGEBYRANK は zset を一定サイズに保つのにもってこいです(例: トップ 1000 だけ残す)。ZCOUNT はメンバーを取得せずに範囲内の件数を返します。ZMSCORE(6.2+)はスコアをバッチ取得し、複数メンバーの参照で往復を減らします。
# 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 はスコアが等しい場合にメンバーの範囲クエリを可能にします — Sorted Set が自動ソートされる文字列インデックスになります。ユースケース: オートコンプリート(スコア 0 で単語を保存し、プレフィックスの範囲をクエリ)、ソート済み辞書。'[a' は含む、'(a' は含まない、'-' が先頭、'+' が末尾です。全スコアが同一のときにのみ機能します。
# 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" BYLEXSorted Set の集計
ZUNIONSTORE/ZINTERSTORE は集計方法(SUM/MIN/MAX)と重みを指定して zset を組み合わせます — 重み付きスコアリングに強力です(例: 関連度 = text_match*2 + recency*1)。Redis 6.2 は保存せず結果だけ返す ZUNION/ZINTER/ZDIFF を追加しました(コマンド 1 回減)。これらは O(N*M) なので — 多くの大きなセットでは注意しましょう。セット数はセット名の前に置きます。
# 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 WITHSCORESPub/Sub
Pub/Sub の基本
Pub/Sub は fire-and-forget です: メッセージは現在接続しているサブスクライバーに届くだけで、永続化はありません。サブスクライバーが listening していなければ、メッセージは失われます。そのため信頼性の高い配信には向かず — そこでは Streams を使います。Pub/Sub は時々の欠落が許容できる、リアルタイム通知・チャット・fan-out に理想的です。サブスクライバーは受信のために接続している必要があります。
# 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 insteadSharded Pub/Sub(7.0+)
Sharded Pub/Sub(7.0+)はクラスタモードの問題を解決します: 通常の Pub/Sub はすべての PUBLISH を全クラスタノードにブロードキャストし、帯域を浪費します。Sharded Pub/Sub はチャンネルキーを所有するシャードにだけメッセージをルーティングし — 大きなクラスタではるかに効率的です。クラスタデプロイでは SSUBSCRIBE/SPUBLISH を使いましょう。チャンネル名がシャードを決めます(キーと同じように)。
# 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 は fan-out パターンに完璧です: 1 つのパブリッシャーから多くのサブスクライバーへ(チャットルーム、ライブダッシュボード、キャッシュ無効化)。PSUBSCRIBE はグローブパターン(user:*:login)で柔軟なルーティングを可能にします。最大の制限は永続化がないことです — サブスクライバーが切断するとメッセージを取りこぼします。信頼性の高い配信には、Pub/Sub に Stream をバックアップとして併用するか、単に Streams を使いましょう。
# 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 Notifications
Keyspace notifications はクライアントがキーのライフサイクルイベント(set、delete、expire、evict)に反応できるようにします。notify-keyspace-events で設定します。これらも fire-and-forget(永続化なし)で信頼性はなく — Redis サーバーが再起動すると、未処理のイベントは失われます。信頼性の高いイベント処理には Streams を使います。Keyspace notifications は後始末やキャッシュウォーミングのような副作用に最適です。
# 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 endsPub/Sub と Streams
Pub/Sub は一時的なリアルタイムメッセージング向け、Streams は耐久性のある、リプレイ可能なメッセージング向けです。よくあるハイブリッド: ライブ通知には Pub/Sub(速い、欠落あり得る)+ 真実の情報源には Streams(耐久性あり、リプレイ可能)。新しいサブスクライバーは Stream を読んで追いつき、その後 Pub/Sub を購読してライブ更新を受けます。信頼性を要するほとんどの本番システムでは、Streams がより良いデフォルトです。
# 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トランザクションとパイプライン
MULTI/EXEC トランザクション
MULTI/EXEC はコマンドをアトミックで逐次のブロックにまとめます — 他のクライアントは割り込めません。コマンドはキューイングされ(QUEUED が返る)、EXEC でまとめて実行されます。キューイングエラー(不正なコマンド名)はトランザクション全体を中止します。実行時エラー(キーの型違い)はそのコマンドだけをスキップし — 残りは実行されます。これは SQL のトランザクションとは異なります。
# 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 commandWATCH(楽観ロック)
WATCH は楽観ロックを実装します: WATCH と EXEC の間に監視キーが変わると、トランザクションは中止されます(EXEC は nil を返す)。これは読み取り・変更・書き込みのアトミック性のための標準的な Redis パターンです(Redis には行ロックがないため)。nil になったら必ずリトライしましょう。WATCH はキューイング時ではなく EXEC 時にチェックされます。UNWATCH は監視をキャンセルします(DISCONNECT でも発生)。
# 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 と違い、パイプライン化されたコマンドはアトミックではありません(他のクライアントが割り込めます)。アトミック性が不要なバルク操作(一括 insert、read)にはパイプラインを、アトミック性が必要なときは MULTI/EXEC を使います。多くのクライアントは MULTI/EXEC 内で自動的にパイプライン化します。
# 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 があります。
# 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 はアトミックなサーバーサイドロジックを追加するモダンな方法です。スクリプト同様、レプリケーションのために決定的でなければなりません。
# 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)永続化
RDB スナップショット
RDB スナップショットはコンパクトなバイナリファイルで、バックアップと障害復旧に理想的です。BGSAVE はプロセスを fork するので(copy-on-write)メインスレッドはブロックされませんが、大きなデータセットでは fork 中にメモリが急増することがあります。'save' ルールは変化率に応じて自動スナップショットを発火させます。RDB は最後のスナップショット以降に書かれたデータを失うリスクがあります — 耐久性のため AOF と併 用しましょう。
# 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 snapshotsAOF(Append-Only File)
AOF はすべての書き込みコマンドをログに追記します — RDB よりはるかに耐久性が高いです(everysec なら最大 1 秒のデータ損失)。'always' はすべての書き込みで fsync します(非常に遅く、重要データ専用)。BGREWRITEAOF はログを圧縮します(最小限のコマンドセットとして書き直す)。AOF ファイルは RDB より大きく、ロードも遅いです。Redis 7 はマルチパート AOF 形式(base + incremental)を使います。
# 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 restartRDB + AOF のハイブリッド
RDB + AOF を併用すると、RDB の高速な再起動と AOF の耐久性を両立できます。Redis 7 以降、AOF はマルチパートファイルです: RDB ベーススナップショット + 増分のコマンドログ — 高速なロードと最小限のデータ損失を両立します。aof-use-rdb-preamble(デフォルト yes)は AOF の先頭に RDB スナップショットを置き、復旧を速くします。これが推奨の本番構成です。
# 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 は appendonly ディレクトリ全体をバックアップします(Redis 7 のマルチパート)。リストアは Redis を止め、ファイルを差し替え、再起動するだけです。悪いコマンドからの復旧には、再起動前に AOF からそのコマンドを編集で削除します。バックアップは必ず redis-check-rdb/aof で検証しましょう。
# 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 を offload)。everysec の AOF がスイートスポットです — 性能影響は最小で、データ損失は最大 1 秒。復旧手順は必ずテストしましょう。
# 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)クラスタリング
Redis Cluster の基本
Redis Cluster は 16,384 個のハッシュスロットでデータをノード間に分散します。CRC16(key) % 16384 がスロットを決めます。マルチキー操作(MGET、トランザクション)は同じスロットのキーを必要とするので — ハッシュタグ({user:1})で関連キーを強制的に同じスロットへ集めましょう。各プライマリには HA のためにレプリカを置けます。プライマリが落ちると、クラスタが自動でフェイルオーバーします。
# 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)は 1 つのシャードにホットスポットを作ります。ハッシュタグはアクセスパターンを中心に設計しましょう: まとめてアクセスされるキーをグループ化し(ユーザーのデータ、注文のアイテム)、無関係なキーは分けておきます。これがクラスタのデータモデリングの核心的な課題です。
# 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 はリクエストをさばきながらキーを 1 個ずつ移行します。ノードを追加してから rebalance で負荷を分散します。--cluster CLI ツールが複雑なオーケストレーションを担います。変更後は必ず --cluster check を実行しましょう。リシャーディングは遅い(キーごとの移行)ので、負荷下で実行するのではなく、先にキャパシティを計画しましょう 。
# 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(デフォルト 15 秒)を超えて到達不能になると、そのレプリカが昇格します。手動フェイルオーバーはメンテナンス用です(ダウンタイムなしのアップグレード)。TAKEOVER は split-brain のリスクがあり — 緊急時のみ使います。レプリカなしでは、落ちたプライマリのスロットは利用不能になります(クラスタダウン)。本番では必ずレプリカ付きで運用しましょう。CLUSTER NODES でトポロジーが見られます。
# 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 単体
開発環境は単一インスタンス。データが 1 台に収まるなら Sentinel で HA(1 プライマリ + レプリカ + 監視/フェイルオーバー用の sentinels)。データが 1 台を超えるか書き込みスループットが非常に高いなら Cluster で水平スケール。Cluster は複雑さを増します(ハッシュタグ、マルチキー制限)。マネージドサービス(Redis Cloud、ElastiCache、MemoryDB)は運用負担を肩代わりします — 自前運用の強い理由がなければそちらを推奨します。
# 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 youSentinel(高可用性)
Sentinel のセットアップ
Sentinel はシャーディングなしで HA を提供します: プライマリを監視し、障害時にレプリカを昇格させ、クライアントを再設定します。Quorum(最後の数字)はプライマリダウンに何個の sentinel が同意する必要があるかです — N 個の sentinel に対して (N/2)+1 に設定します。耐障害性のため 3 個の sentinel を別々のマシンに配置しましょう。down-after-milliseconds はネットワークのジッタより大きくする必要があり — 小さすぎると誤フェイルオーバーが起きます。
# 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 mymasterSentinel のコマンド
クライアントは Sentinel に接続して現在のプライマリを発見し、その後にプライマリへ接続します。フェイルオーバー時は、クライアントが再度 Sentinel に問い合わせて新しいプライマリを見つけます。SENTINEL failover は手動フェイルオーバーを発火させます(ローリングアップグレード用)。ckquorum は quorum を形成できるだけの sentinel がいるか検証します — 監視として実行しましょう。主要な Redis クライアントライブラリはすべて Sentinel をネイティブにサポートします。
# 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 は 1 個の sentinel の判断、ODOWN は quorum の合意です。選出された sentinel リーダーが最も新しいレプリカを選んで昇格させます。旧プライマリが戻るとレプリカになります — ネットワーク分断中に受け付けた書き込みは失われます(split-brain リスク)。アラートには +switch-master を購読しましょう。
# 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-*Read レプリカとスケール
レプリカは読み取りをプライマリから offload します — 読み取り中心のワークロード(分析、レポーティング)に有用です。レプリケーションは非同期なので、レプリカのデータは遅れ得ます(通常はミリ秒だが、負荷下では増える)。READONLY でレプリカから読めます。書き込み可能レプリカ(4.0+)は非複製の書き込みを受け付けます — 一時データやレプリカごとのキャッシュに有用ですが、フェイルオーバー時に書き込みは失われます。レプリカラグを監視しましょう。
# 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 は短い切断の後に部分的な再同期を可能にします(replication backlog を使用 — repl-backlog-size を調整)。レプリケーション ID の変更(プライマリの再起動やフェイルオーバー時)は完全な再同期を強制します。チェーンレプリケーション(レプリカのレプリカ)は大規模 fan-out でプライマリの負荷を減らします。
# 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 resyncStreams
Stream の基本(XADD/XREAD)
Streams は Redis の耐久性のあるメッセージング構造です — 追記専用、リプレイ可能、コンシューマグループ付き。ID はタイムスタンプベース(* で自動生成)。XREAD は $ でストリームを tail し(新規エントリのみ)、0 で最初から読みます。MAXLEN はストリームに上限を設けます(~ 付きの概算ならはるかに速い)。Streams は Pub/Sub の永続化なし問題を解決し、信頼性の高いキューを構築する推奨手段です。
# 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)コンシューマグループ
コンシューマグループは並列処理を可能にします: 各エントリはグループ内のちょうど 1 つのコンシューマに配信されます。'>' は新規エントリを読み、'0' はこのコンシューマの pending(未 ack)エントリを読みます。XACK はエントリを処理済みとしてマークします。Pending エントリ(配信されたが未 ack)は処理ログになります — XPENDING で詰まったメッセージを見つけ、XCLAIM でタイムアウト後に別のコンシューマへ再割り当てしましょう。
# 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 consumer1Stream の処理と復旧
XAUTOCLAIM は信頼性の高い処理の鍵です: 長く pending のままのエントリ(コンシューマがクラッシュまたは停滞)を健全なコンシューマへ再割り当てします。min-idle-time により、まだ処理中のエントリを横取りしません。XTRIM はストリームサイズを制限します(メモリのために必須)。XRANGE は ID で範囲を読みます。XINFO は監視のために stream/group/consumer の状態を明らかにします。これで完全で耐久性のあるメッセージキューになります。
# 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)はリストベースのキューの完全な置き換えで、リトライ(pending エントリ)と復旧(XAUTOCLAIM)が組み込みです。時系列では MAXLEN がメモリを有限に保ちます。Streams は 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 dayStreams と他のキュー
Streams は Redis ネイティブのキューです — Kafka/RabbitMQ よりシンプルで、RAM に収まるほとんどのワークロードには十分です。Kafka のパーティションレベルの並列性はありません(1 ストリーム= 1 シャード)が、コンシューマグループがワーカーの並列性を提供します。非常に高いスループットやディスクベースの耐久性なら Kafka が勝り、複雑なルーティングなら RabbitMQ が勝ります。すでに Redis を使っているほとんどのアプリでは、信頼性の高いメッセージングに Streams が正しいデフォルトです。
# 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 retryHyperLogLog、ビットマップ、GEO
HyperLogLog(カーディナリティ)
HyperLogLog(HLL)は固定 12KB で約 0.81% の誤差によりユニーク要素数を数えます — 定数メモリで数十億要素を数えられます。日次/週次/月次ユニーク訪問者のような分析に完璧です。PFMERGE は HLL を組み合わせます(例: 日次から月次のユニーク数)。トレードオフは概算であること — 正確な件数や所属判定(SISMEMBER)が必要なら Set を、件数だけなら HLL を使いましょう。
# 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 ビットを保存します — 100 万ユーザー=125KB、40 億=512MB。BITOP AND/OR/XOR/NOT はビットマップを組み合わせます(リテンション、離脱分析)。BITPOS は最初の立っているビットを見つけます。ユースケース: 日次アクティブユーザー、フィーチャーフラグ、出席、A/B テストのグループ分け。制限: 密な整数のユーザー ID が必要です(隙間はスペースを浪費)。疎なデータには Set か HyperLogLog を推奨します。
# 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 コマンドは地理座標を保存し、半径/ボックスのクエリに対応します — sorted set ベース(スコア=geohash)です。GEOSEARCH(6.2+、GEORADIUS の後継)は豊富なオプション(WITHCOORD、WITHDIST、ASC/DESC)で近くの地点を探します。距離は球面上で計算されます。精度はほとんどのアプリに十分です。複雑な GIS(ポリゴン、ルーティング)には専用の空間データベースを使いましょう。GEO は「近くを探す」機能に完璧です。
# 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 は sorted set の上に実装されています — 座標の geohash がスコアです。そのため一部の操作には Z* コマンドが使えます(ZREM、ZRANGE)。GEOSEARCH はリッチな結果を返します(距離、座標、geohash)。COUNT は結果を制限します(nearest-N には ASC と併用)。GEOSEARCHSTORE はさらなる処理のために結果を保存します。Geohash の精度は極付近で劣化します — ほとんどの実用的なアプリでは問題ありません。
# 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、密なブールフラグには Bitmaps、近接検索には GEO。モジュールは Bloom フィルタ(偽陽性のある所属判定)、Top-K(ヘビーヒッター)、RedisTimeSeries(最適化された時系列)を追加します。データの形と精度の要件に合わせて構造を選びましょう — 正しい選択はメモリを桁違いに節約できます。
# 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)セキュリティ
認証と ACL
Redis 6+ の ACL は単一パスワードのモデルを置き換えます — 権限を限定したユーザーを作れます。構文: on(有効)、>password、~pattern(キーのパターン)、+command/-command、+@category/-@category(例: +@read、-@dangerous)。アプリごとに最小権限のユーザーを必ず作りましょう。ACL はファイルに保存して永続化します。本番でデフォルトユーザーを使ってはいけません — 無効化するか強いパスワードを設定しましょう。
# 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.aclTLS/SSL 暗号化
TLS は通信中のデータを暗号化します — 特に信頼できないネットワーク越えでは本番に不可欠です。Redis 6+ は TLS をネイティブにサポートします。mTLS(tls-auth-clients yes)はクライアントに証明書を要求し、パスワードなしの相互認証を提供します。クラスタ/sentinel ではノード間通信にも TLS を有効にしましょう。ポート 0 で平文を無効化できま す。移行期間は両方のポートを一時的に並行稼働できます。
# 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 はパスワード未設定時に外部接続をブロックします。rename-command は危険なコマンドを無効化します(FLUSHALL、CONFIG、KEYS)が、ACL(6.0+)がモダンな方法です。Redis はプライベートサブネットに置き、VPN か bastion 経由でアクセスしましょう。
# 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 は接続中のクライアントを表示します(リークに注意)。本番では loglevel を 'notice' に設定しましょう(debug は冗長すぎます)。分析のためログは中央のシステムへ送りましょう。
# 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)。最重要ルール: Redis をインターネットに直接晒さないこと — 組み込みのレートリミットも総当たり攻撃対策もありません。RDB/AOF ファイルはディスクレベルで暗号化しましょう(データが平文で含まれます)。セキュリティパッチのため 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)パフォーマンスと最適化
パフォーマンスの基礎
Redis はコマンド実行がシングルスレッドです — 1 つの遅いコマンドがすべてのクライアントをブロックします。本番の大きな構造に KEYS、SMEMBERS、DEL を使ってはいけません。代わりに SCAN ファミリー、HSCAN、UNLINK(非同期削除)を使いましょう。往復を減らすためにコマンドはパイプライン化します。各コマンドの Big-O を把握しましょう: O(1) と O(log N) は安全、O(N) のコマンドは範囲を限定すべきです(小さな範囲の LRANGE など)。
# 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 で最大の性能レバーです — コマンドを 1 回のネットワーク往復にまとめると 10〜100 倍の高速化が得られます。1 往復にはネットワークレイテンシがかかり(約 0.1〜1ms)、1000 個の個別コマンド=100〜1000ms、パイプラインなら約 1ms です。パイプラインはやりすぎないように(キューイングされた応答がメモリを消費します)。redis-benchmark -P でベンチマークし、スイートスポットを見つけましょう。トランザクションは自動的にパイプライン化されます。
# 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 の第一の制約です。正しい構造を使いましょう: オブジェクトには hash(listpack エンコーディングは個別キーより 5〜10 倍小さい)。エンコーディングのしきい値を調整して構造をコンパクトな形に保ちます。「キーバケット化」(小さなキーを 1 つのハッシュにまとめる)はキーごとのオーバーヘッドを劇的に減らします。OOM を防ぐため maxmemory +退去ポリシーを設定しましょう。used_memory と断片化率を監視します。
# 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退去ポリシー
退去ポリシーはメモリが満杯のときの挙動を制御します。純粋なキャッシュなら: allkeys-lru か allkeys-lfu(LFU は偏ったアクセスパターンに有利)。データベース用途なら: noeviction(データを失うより書き込みを失敗させる)。混合なら: volatile-lru(TTL 付きのキーだけ退去し、永続的なキーを保持)。LFU(4.0+)はアクセス頻度を追跡し、しばしば LRU を上回ります。maxmemory を正しくサイジングするため evicted_keys を監視しましょう。
# 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 をサポートします。典型的なシングルノード性能: 汎用ハードウェアで 10 万 ops/sec 以上。
# 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管理
サーバー情報と監視
INFO は最も重要な監視コマンドです — memory、clients、persistence、stats のセクションを定期的に確認しましょう。MEMORY DOCTOR と LATENCY DOCTOR は自動分析を提供します。SLOWLOG は遅いコマンドを捕捉します。CLIENT LIST はすべての接続を表示します(リークに注意 — 各接続はメモリを消費します)。履歴グラフとメモリ・接続・レプリケーションラグのアラートのため、外部監視(Prometheus + redis_exporter、Datadog)を設置しましょう。
# 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 で接続の枯渇を防ぎます(各クライアントはメモリを使います)。
# 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 は再起動なしで実行時に設定を変更し、CONFIG REWRITE は redis.conf に永続化します。設定変更は必ずステージングでテストしましょう。重要な本番設定: maxmemory +退去ポリシー(OOM 防止)、save + appendonly(永続化)、tcp-keepalive(死んだクライアントの検出)、timeout(アイドル接続の掃除)。redis.conf はバージョン管理しましょう。CONFIG GET * ですべて表示できます — 監査に便利です。
# 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 は内部表現を明らかにします(メモリのデバッグ)。OBJECT IDLETIME はコールドキー(退去候補)を見つけます。MEMORY USAGE はキーごとにメモリを食う犯人を特定します。DEBUG SLEEP はアプリがレイテンシをどう扱うかテストします。LATENCY はイベント(expired、eviction、fast keys)を追跡します。アクティブデフラグ(4.0+)は断片化したメモリをオンラインで自動回収します。DEBUG コマンドは本番では控えめに使いましょう。
# 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アップグレードとメンテナンス
ダウンタイムなしのアップグレードにはレプリケーションを使いましょう: まずレプリカをアップグレードし、フェイルオーバーして、古いプライマリをアップグレードします。クラスタでは、1 ノードずつローリング再起動します(まずフェイルオーバーする primaries)。アップグレード前には必ずバックアップ(BGSAVE + RDB のコピー)を取りましょう。破壊的な変更がないかリリースノートを読み、ステージングでテストします。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よくあるパターン
キャッシュパターン(Cache-Aside)
Cache-aside は最もよく使う Redis パターンです: キャッシュから読み、ミスなら DB にフォールバックし、キャッシュを埋めます。TTL を設定して鮮度の上限を設けましょう。書き込み時には、write-through(DB 書き込み時にキャッシュも更新)か invalidate(キャッシュキーの削除)のどちらかです。invalidate の方が安全(再構築の競合がない)ですが、write-through はキャッシュを温かく保ちます。キャッシュスタンピード対策: ミス時に多くのリクエストが同時に DB に当たらないよう、ロックか 'dogpile' パターンを使いましょう。
# 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 によるアトミックな check-and-delete)。より高い安全性を求めるなら、Redlock アルゴリズムは複数の独立した Redis インスタンスを使います。ロックは完全には安全ではありません(時計のずれ、GC ポーズ)— 強い正しさの保証には合意システム(etcd、ZooKeeper)を検討しましょう。ほとんどの実用的な調整には 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)レートリミット
固定窓(INCR+EXPIRE)が最もシンプルですが、窓の境界で 2 倍のバーストが許されます。スライディングウィンドウ(タイムスタンプの sorted set)はより正確ですがメモリを余計に使います。トークンバケットは最大までのバーストを許します。どれも Lua スクリプトでアトミックにできます(並行下での正しさに重要)。大規模なユーザーごとのレートリミットには、固定窓方式が通常十分で、非常にメモリ効率が良いです。
# 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リーダーボードとランキング
Sorted set を使えばリーダーボードは簡単です: ZADD でスコアを更新し、ZREVRANGE でトップ N、ZREVRANK でプレイヤーの順位。ZINCRBY はスコアをアトミックに更新します。時間窓付きのリーダーボード(日次/週次)には、期間ごとのキーに TTL を付けましょう。ページネーションはオフセット付きの ZREVRANGE で行います。パーセンタイル順位には ZCARD と ZREVRANK を組み合わせます。Redis の最も自然で強力なユースケースの 1 つです。
# 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(リクエストごとに更新)を付けましょう。「全端末からログアウト」機能のため、ユーザーのセッションを set で追跡します。クラスタでは、ユーザーのセッションとセッションインデックスが同じシャードに収まるようハッシュタグ({user:1})を使いましょう。セキュリティのため、ログインや権限変更時にはセッション ID をローテーションします。
# 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 1800Lua スクリプティング
EVAL の基本
EVAL は Lua スクリプトをアトミックに実行します — スクリプトの実行中は他のコマンドは一切実行されないため、複数ステップのアトミック操作に理想的です。KEYS と ARGV で呼び出し側からデータを渡します。スクリプト内で文字列連結によりキーを組み立ててはいけません(クラスタのルールに違反)。redis.call はエラーを raise し(停止)、redis.pcall はエラーを返します。スクリプトは SHA1 ハッシュでキャッシュされるため、繰り返しの呼び出しには効率のために EVALSHA を使いましょう。
# 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" 0EVALSHA とスクリプトキャッシュ
EVALSHA はロード済みのスクリプトを SHA1 ハッシュで実行し、呼び出しごとのスクリプト本体の再送を避けます — 同じスクリプトを繰り返し実行するアプリにとって大きな帯域の節約です。キャッシュミスのとき(SCRIPT FLUSH や再起動の後)、Redis は NOSCRIPT を返します。クライアントはこれを捕捉して EVAL + SCRIPT LOAD にフォールバックします。これを透過的に扱うライブラリ(redis-py、ioredis)を使いましょう。
# 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+)を使います。
# 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 itemRedis Functions(7.0+)
Redis Functions(7.0+)はその場しのぎの EVAL スクリプトのモダンな代替です: データベースのストアドプロシージャのように登録、命名、バージョン管理されます。ライブラリが複数の関数をまとめ、FCALL がそれらを呼びます。Functions は RDB/AOF に永続化され(再起動後も生存)、一時的な EVAL キャッシュとは異なります。自明でないロジック のスクリプティングをより保守しやすくし、監査やバージョン管理もしやすくなります。
# 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.log() を使うと、戻り値に影響せず Redis のログへデバッグ用メッセージを出せます。redis-cli --ldb はインタラクティブな Lua デバッガです: ブレークポイントを設定し、コードをステップ実行し、ローカル変数を検査できます。SCRIPT DEBUG SYNC はサーバーをスクリプト上でブロックさせ、デバッガがステップできるようにします。スクリプトは必ずステージングでテストしましょう — 暴走ループは 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監視とトラブルシューティング
INFO と LATENCY
INFO は最重要の監視コマンドです — メモリ、クライアント、レプリケーション、スループットを 1 回で報告します。mem_fragmentation_ratio を見守りましょう(理想は約 1.0〜1.5)。1.5 超はメモリの浪費、1 未満は Redis がスワップしていることを意味します(レイテンシにとって壊滅的)。LATENCY DOCTOR は直近の遅いイベントを分析し修正を提案します。キャッシュヒット率を追うには keyspace_misses と keyspace_hits を監視しましょう。
# 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 でアプリの接続にラベルを付ければ、固まったクライアントがどのプールの所属か特定できます。
# 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-workerMEMORY と OBJECT
MEMORY USAGE は 1 キーの正確なバイト数を報告します(大きなコレクションで完全な精度には SAMPLES 0)。OBJECT ENCODING は Redis の内部形式を明らかにします — 小さな構造は CPU とメモリ効率の良いコンパクトなエンコーディング(listpack、ziplist)を使い、成長すると自動的にハッシュテーブル/スキップリストへ昇格します。エンコーディングを知っていると、キーが予想より大きい・遅い理由を説明できます。
# 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 mykeyBigkey と keyspace スキャン
本番で KEYS を使ってはいけません — サーバーをブロックします。SCAN がカーソルベースでノンブロッキングの代替であり、カーソルが 0 に戻るまで反復します。--bigkeys と --memkeys は SCAN の上に作られた CLI ヘルパーで、ブロックせずに最大のキーを明らかにします。大きなキー(特に数百万要素のコレクション)は失効/退去時にレイテンシ急増を引き起こします — 見つけて分割しましょう(例: 巨大な sorted set を時間でシャーディング)。
# 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 はクラスタの合意を迂回します(緊急時のみ)。リシャードや障害の後は必ず --cluster check を実行し、孤立スロットや split-brain 状態を見逃さないようにしましょう。
# 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関連する Redis スニペット
Copy-paste ready code for common tasks.
Strings & Counters
Set, get, increment, and expire string values.
Lists & Queues
Build queues and stacks with list operations.
Hashes
Store object fields and values efficiently.
Sets
Manage unique collections and compute intersections.
Sorted Sets & Leaderboards
Rank items by score for leaderboards and scheduling.
Pub/Sub
Broadcast messages to subscribed clients.
Persistence
Configure RDB snapshots and AOF append logs.
Keys & Expiration
Set TTL, scan keys, and inspect the keyspace.
Was this helpful?