redis について
redisは、Redisの設定、運用、最適化を扱うスキルです。キャッシュやキュー、レート制限、リアルタイムデータに利用する開発者や運用担当者向けに、永続化、高可用性、監視も解説します。
主な機能
- 01Redisの導入と基本設定
- 02文字列、ハッシュ、リストなどの操作
- 03RDBとAOFによる永続化の設定
- 04Sentinelとクラスターモードの構成
- 05キャッシュ、レート制限、メッセージングの実装
- 06メトリクス確認と一般的な問題の調査
活用シーン
- 01TTL付きでデータベース検索結果をキャッシュ
- 02リストを使ったジョブキューの構築
- 03Sentinelによる自動フェイルオーバーの設定
- 04メモリ、ヒット率、レプリケーションの監視
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ bagelhole/ devops-security-agent-skills --skill redisインストール後、Claude Code で/redisを入力して読み込まれたか確認します。
詳細
Redis
キャッシュ、キュー、レート制限、リアルタイムデータストレージのために、Redis を設定、運用、最適化します。
使用する場面
- データベースの負荷を軽減するために、低レイテンシのインメモリキャッシュが必要な場合。
- アプリケーションでレート制限、セッションストレージ、リーダーボードが必要な場合。
- サービス間の Pub/Sub メッセージングが必要な場合。
- インメモリストアを基盤とした分散ロックやジョブキューが必要な場合。
前提条件
- Linux サーバーまたは Docker。
- パッケージのインストールに必要な root または sudo 権限。
- 本番環境では Redis 7.x を推奨します。
インストールとセットアップ
# Debian / Ubuntu
sudo apt update
sudo apt install -y redis-server
# RHEL / Amazon Linux
sudo dnf install -y redis
# Start and enable
sudo systemctl enable --now redis-server
# Verify
redis-cli ping
# Expected output: PONG
基本設定
/etc/redis/redis.conf を編集します。
# Network
bind 0.0.0.0
port 6379
protected-mode yes
requirepass strong_redis_password
# Memory
maxmemory 2gb
maxmemory-policy allkeys-lru
# Connections
maxclients 10000
timeout 300
tcp-keepalive 60
# Logging
loglevel notice
logfile /var/log/redis/redis-server.log
# Security — disable dangerous commands in production
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command CONFIG ""
rename-command DEBUG ""
sudo systemctl restart redis-server
redis-cli コマンドリファレンス
# Connect with authentication
redis-cli -a strong_redis_password
# Connect to a remote host
redis-cli -h 10.0.0.5 -p 6379 -a strong_redis_password
文字列の操作
SET user:1:name "Alice"
GET user:1:name
# Set with TTL (seconds)
SETEX session:abc123 3600 '{"userId":1}'
# Set only if key does not exist (distributed lock pattern)
SET lock:order:42 "worker-1" NX EX 30
# Increment counters
INCR page:views:/home
INCRBY api:quota:user:1 -1
ハッシュの操作
HSET user:1 name "Alice" email "[email protected]" plan "pro"
HGET user:1 email
HGETALL user:1
HINCRBY user:1 login_count 1
リストの操作(キュー)
LPUSH queue:emails '{"to":"[email protected]","subject":"Welcome"}'
RPOP queue:emails
LLEN queue:emails
# Blocking pop (worker pattern)
BRPOP queue:emails 30
セットとソート済みセットの操作
# Sets — unique tags
SADD article:1:tags "redis" "database" "caching"
SMEMBERS article:1:tags
SISMEMBER article:1:tags "redis"
# Sorted sets — leaderboards
ZADD leaderboard 1500 "player:1" 2300 "player:2" 1800 "player:3"
ZREVRANGE leaderboard 0 9 WITHSCORES
ZINCRBY leaderboard 100 "player:1"
ZRANK leaderboard "player:2"
キー管理
KEYS user:* # avoid in production — use SCAN instead
SCAN 0 MATCH user:* COUNT 100
TTL session:abc123
PERSIST session:abc123
DEL user:old
EXPIRE user:1 86400
TYPE user:1
永続化
RDB スナップショット
# redis.conf — save snapshots at intervals
save 900 1 # snapshot if >= 1 key changed in 900 seconds
save 300 10 # snapshot if >= 10 keys changed in 300 seconds
save 60 10000 # snapshot if >= 10000 keys changed in 60 seconds
dbfilename dump.rdb
dir /var/lib/redis
rdbcompression yes
AOF(追加専用ファイル)
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec # good balance of safety and performance
# Options: always (safest, slowest), everysec (recommended), no (OS decides)
# AOF rewrite thresholds
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
本番環境で推奨される戦略
RDB と AOF を併用します。RDB は高速な再起動とコンパクトなバックアップを実現します。AOF は 1 秒単位の粒度でデータの永続性を確保します。
save 900 1
save 300 10
appendonly yes
appendfsync everysec
Redis Sentinel(高可用性)
Sentinel は Redis インスタンスを監視し、自動フェイルオーバーを実行します。
Sentinel の設定
# /etc/redis/sentinel.conf
port 26379
sentinel monitor mymaster 10.0.0.1 6379 2
sentinel auth-pass mymaster strong_redis_password
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1
クォーラムを確保するため、Sentinel インスタンスを少なくとも 3 つ実行します。
# Start Sentinel
redis-sentinel /etc/redis/sentinel.conf
# Query Sentinel
redis-cli -p 26379 SENTINEL masters
redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster
redis-cli -p 26379 SENTINEL replicas mymaster
Redis クラスターモード
クラスターモードでは、複数のシャードにデータが自動的に分散されます。
# Create a 6-node cluster (3 masters + 3 replicas)
redis-cli --cluster create \
10.0.0.1:6379 10.0.0.2:6379 10.0.0.3:6379 \
10.0.0.4:6379 10.0.0.5:6379 10.0.0.6:6379 \
--cluster-replicas 1 -a strong_redis_password
# Check cluster status
redis-cli -c -a strong_redis_password CLUSTER INFO
redis-cli -c -a strong_redis_password CLUSTER NODES
# Add a new node
redis-cli --cluster add-node 10.0.0.7:6379 10.0.0.1:6379
# Rebalance slots
redis-cli --cluster rebalance 10.0.0.1:6379
# redis.conf for cluster nodes
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
よく使われるパターン
TTL を使用したキャッシュ
# Cache a database query result for 5 minutes
SET cache:user:42:profile '{"name":"Alice","plan":"pro"}' EX 300
# Cache-aside pattern (pseudocode):
# 1. GET cache:key -> if hit, return
# 2. Query database
# 3. SET cache:key result EX 300
# 4. Return result
レート制限(スライディングウィンドウ)
# Allow 100 requests per minute per user
# Using a sorted set with timestamps as scores
ZADD ratelimit:user:42 1700000000.123 "req-uuid-1"
ZREMRANGEBYSCORE ratelimit:user:42 0 1699999940.000
ZCARD ratelimit:user:42
EXPIRE ratelimit:user:42 60
# If ZCARD >= 100, reject the request
Pub/Sub メッセージング
# Terminal 1 — subscriber
redis-cli -a strong_redis_password
SUBSCRIBE notifications:order-updates
# Terminal 2 — publisher
redis-cli -a strong_redis_password
PUBLISH notifications:order-updates '{"orderId":42,"status":"shipped"}'
# Pattern subscription
PSUBSCRIBE notifications:*
分散ロック(Redlock パターン)
# Acquire lock
SET lock:resource:42 "worker-abc" NX EX 30
# Returns OK if acquired, nil if already held
# Release lock (use Lua script to ensure atomicity)
redis-cli -a strong_redis_password EVAL "
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
else
return 0
end
" 1 lock:resource:42 "worker-abc"
Docker Compose のセットアップ
# docker-compose.yml
version: "3.9"
services:
redis:
image: redis:7-alpine
restart: unless-stopped
ports:
- "6379:6379"
volumes:
- redis_data:/data
- ./redis.conf:/usr/local/etc/redis/redis.conf:ro
command: redis-server /usr/local/etc/redis/redis.conf
healthcheck:
test: ["CMD", "redis-cli", "-a", "strong_redis_password", "ping"]
interval: 10s
timeout: 5s
retries: 5
redis-sentinel:
image: redis:7-alpine
restart: unless-stopped
ports:
- "26379:26379"
volumes:
- ./sentinel.conf:/usr/local/etc/redis/sentinel.conf
command: redis-sentinel /usr/local/etc/redis/sentinel.conf
depends_on:
redis:
condition: service_healthy
redis-commander:
image: rediscommander/redis-commander:latest
restart: unless-stopped
ports:
- "8081:8081"
environment:
REDIS_HOSTS: "local:redis:6379:0:strong_redis_password"
depends_on:
redis:
condition: service_healthy
volumes:
redis_data:
docker compose up -d
redis-cli -h 127.0.0.1 -a strong_redis_password ping
監視
# Real-time stats
redis-cli -a strong_redis_password INFO stats
redis-cli -a strong_redis_password INFO memory
redis-cli -a strong_redis_password INFO replication
# Key metrics to watch
redis-cli -a strong_redis_password INFO stats | grep -E "keyspace_hits|keyspace_misses"
# Hit ratio = hits / (hits + misses) — aim for > 95%
# Memory usage breakdown
redis-cli -a strong_redis_password MEMORY STATS
# Slow log (queries > 10ms by default)
redis-cli -a strong_redis_password SLOWLOG GET 10
redis-cli -a strong_redis_password SLOWLOG LEN
# Monitor all commands in real time (debugging only — impacts performance)
redis-cli -a strong_redis_password MONITOR
# Connected clients
redis-cli -a strong_redis_password CLIENT LIST
トラブルシューティング
| 症状 | 考えられる原因 | 対処方法 |
|---|---|---|
OOM command not allowed | maxmemory の上限に達した | maxmemory を増やすか、より厳格なエビクションポリシーを設定します |
| 高レイテンシの急増 | RDB の保存または AOF の書き換え時のフォーク | AOF が有効な場合は save "" で RDB を無効にします。auto-aof-rewrite-min-size を調整します |
LOADING Redis is loading the dataset in memory | 起動時に大規模なデータセットを復元している | 読み込みの完了を待ちます。データセットを小さくするか、より高速なディスクを検討します |
| キャッシュヒット率が 90% 未満 | TTL が短すぎる、またはワーキングセットがメモリ容量を超えている | maxmemory を増やし、TTL 戦略を見直します |
| Sentinel がフェイルオーバーしない | クォーラムに必要な数の Sentinel に接続できない | Sentinel が 3 つ以上稼働し、ネットワークに接続されていることを確認します |
クラスター内で CROSSSLOT エラーが発生する | 複数キーのコマンドが複数のスロットにまたがっている | ハッシュタグ {user:42}:profile を使用し、関連するキーを同じ場所に配置します |
関連スキル
- postgresql - Redis がキャッシュするプライマリデータベース
- mysql - Redis がキャッシュするプライマリデータベース
- mongodb - Redis を前段に配置できるドキュメントデータベース
- database-backups - バックアップ戦略に RDB ファイルを含めます
コメント
Markdown 対応