[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AKEVCMATTGJTNE9DBYFCZ0":3,"skill-same:01M7AKEVCMATTGJTNE9DBYFCZ0":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AKEVCMATTGJTNE9DBYFCZ0","redis-patterns",null,"Redisデータ構造パターン、キャッシング戦略、分散ロック、レート制限、Pub\u002FSub、本番アプリケーション用コネクション管理。","Cyrilthetecchieee\u002Fcyril-code-","Cyrilthetecchieee","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F219787998?v=4","01M7AF0MMMKRAA0H61XMJPV92H","Julian Cyril D ","01M7AF0MQ10AVG6QJQ1C2BC0F5",2,"MIT","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Fredis-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: redis-patterns\ndescription: Redisデータ構造パターン、キャッシング戦略、分散ロック、レート制限、Pub\u002FSub、本番アプリケーション用コネクション管理。\norigin: ECC\n---\n\n# Redis Patterns\n\n一般的なバックエンド使用例に対するRedisベストプラクティスの参考資料。\n\n## How It Works\n\nRedisはメモリ内データ構造ストアで、文字列、ハッシュ、リスト、セット、ソート済みセット、ストリームなどをサポートします。単一インスタンスでは個々のRedisコマンドは原子的ですが、マルチステップワークフローはLuaスクリプト、MULTI\u002FEXECトランザクション、または明示的な同期化が必要です。RDBスナップショットまたはAOFログを通じてデータをオプションで永続化します。クライアントはRESPプロトコルを使用してTCP経由で通信します。接続プール不可欠でリクエストごとのハンドシェイクオーバーヘッドを回避します。\n\n## When to Activate\n\n- アプリケーションにキャッシング追加\n- レート制限またはスロットリング実装\n- 分散ロックまたはコーディネーション構築\n- セッションまたはトークンストレージ設定\n- Pub\u002FSubまたはRedis Streams for messaging使用\n- 本番環境でRedis設定（プール、削除、クラスタリング）\n\n## Data Structure Cheat Sheet\n\n| Use Case | Structure | Example Key |\n|----------|-----------|-------------|\n| Simple cache | String | `product:123` |\n| User session | Hash | `session:abc` |\n| Leaderboard | Sorted Set | `scores:weekly` |\n| Unique visitors | Set | `visitors:2024-01-01` |\n| Activity feed | List | `feed:user:456` |\n| Event stream | Stream | `events:orders` |\n| Counters \u002F rate limits | String (INCR) | `ratelimit:user:123` |\n| Bloom filter \u002F HLL | HyperLogLog | `hll:pageviews` |\n\n## Core Patterns\n\n### Cache-Aside (Lazy Loading)\n\n```python\nimport redis\nimport json\n\nr = redis.Redis(host='localhost', port=6379, decode_responses=True)\n\ndef get_product(product_id: int):\n    cache_key = f\"product:{product_id}\"\n    cached = r.get(cache_key)\n\n    if cached:\n        return json.loads(cached)\n\n    product = db.query(\"SELECT * FROM products WHERE id = %s\", product_id)\n    r.setex(cache_key, 3600, json.dumps(product))  # TTL: 1 hour\n    return product\n```\n\n### Write-Through Cache\n\n```python\ndef update_product(product_id: int, data: dict):\n    # DB書き込み先\n    db.execute(\"UPDATE products SET ... WHERE id = %s\", product_id)\n\n    # キャッシュを即座に更新\n    cache_key = f\"product:{product_id}\"\n    r.setex(cache_key, 3600, json.dumps(data))\n```\n\n### Cache Invalidation\n\n```python\n# タグベース削除 — セット内で関連キーをグループ化\ndef cache_product(product_id: int, category_id: int, data: dict):\n    key = f\"product:{product_id}\"\n    tag = f\"tag:category:{category_id}\"\n    pipe = r.pipeline(transaction=True)\n    pipe.setex(key, 3600, json.dumps(data))\n    pipe.sadd(tag, key)\n    pipe.expire(tag, 3600)\n    pipe.execute()\n\ndef invalidate_category(category_id: int):\n    tag = f\"tag:category:{category_id}\"\n    keys = r.smembers(tag)\n    if keys:\n        r.delete(*keys)\n    r.delete(tag)\n```\n\n### Session Storage\n\n```python\nimport time\nimport uuid\n\ndef create_session(user_id: int, ttl: int = 86400) -> str:\n    session_id = str(uuid.uuid4())\n    key = f\"session:{session_id}\"\n    pipe = r.pipeline(transaction=True)\n    pipe.hset(key, mapping={\n        \"user_id\": user_id,\n        \"created_at\": int(time.time()),\n    })\n    pipe.expire(key, ttl)\n    pipe.execute()\n    return session_id\n\ndef get_session(session_id: str) -> dict | None:\n    data = r.hgetall(f\"session:{session_id}\")\n    return data if data else None\n\ndef delete_session(session_id: str):\n    r.delete(f\"session:{session_id}\")\n```\n\n## Rate Limiting\n\n### Fixed Window (Simple)\n\n```python\ndef is_rate_limited(user_id: int, limit: int = 100, window: int = 60) -> bool:\n    key = f\"ratelimit:{user_id}:{int(time.time()) \u002F\u002F window}\"\n    pipe = r.pipeline(transaction=True)\n    pipe.incr(key)\n    pipe.expire(key, window)\n    count, _ = pipe.execute()\n    return count > limit\n```\n\n### Sliding Window (Lua — Atomic)\n\n```lua\n-- sliding_window.lua\nlocal key = KEYS[1]\nlocal now = tonumber(ARGV[1])\nlocal window = tonumber(ARGV[2])\nlocal limit = tonumber(ARGV[3])\n\nredis.call('ZREMRANGEBYSCORE', key, 0, now - window)\nlocal count = redis.call('ZCARD', key)\n\nif count \u003C limit then\n    -- Use unique member (now + sequence) to avoid collisions within the same millisecond\n    local seq_key = key .. ':seq'\n    local seq = redis.call('INCR', seq_key)\n    redis.call('EXPIRE', seq_key, math.ceil(window \u002F 1000))\n    redis.call('ZADD', key, now, now .. '-' .. seq)\n    redis.call('EXPIRE', key, math.ceil(window \u002F 1000))\n    return 1\nend\nreturn 0\n```\n\n```python\nsliding_window = r.register_script(open('sliding_window.lua').read())\n\ndef allow_request(user_id: int) -> bool:\n    key = f\"ratelimit:sliding:{user_id}\"\n    now = int(time.time() * 1000)\n    return bool(sliding_window(keys=[key], args=[now, 60000, 100]))\n```\n\n## Distributed Locks\n\n### Distributed Lock (Single Node — SET NX PX)\n\n```python\nimport uuid\n\ndef acquire_lock(resource: str, ttl_ms: int = 5000) -> str | None:\n    lock_key = f\"lock:{resource}\"\n    token = str(uuid.uuid4())\n    acquired = r.set(lock_key, token, px=ttl_ms, nx=True)\n    return token if acquired else None\n\ndef release_lock(resource: str, token: str) -> bool:\n    release_script = \"\"\"\n    if redis.call('get', KEYS[1]) == ARGV[1] then\n        return redis.call('del', KEYS[1])\n    else\n        return 0\n    end\n    \"\"\"\n    result = r.eval(release_script, 1, f\"lock:{resource}\", token)\n    return bool(result)\n\n# Usage\ntoken = acquire_lock(\"order:payment:123\")\nif token:\n    try:\n        process_payment()\n    finally:\n        release_lock(\"order:payment:123\", token)\n```\n\n> マルチノード設定の場合、フルRedlockアルゴリズムを実装する `redlock-py` ライブラリを使用してください。\n\n## Pub\u002FSub & Streams\n\n### Pub\u002FSub (Fire-and-Forget)\n\n```python\n# Publisher\ndef publish_event(channel: str, payload: dict):\n    r.publish(channel, json.dumps(payload))\n\n# Subscriber (blocking — run in separate thread\u002Fprocess)\ndef subscribe_events(channel: str):\n    pubsub = r.pubsub()\n    pubsub.subscribe(channel)\n    for message in pubsub.listen():\n        if message['type'] == 'message':\n            handle(json.loads(message['data']))\n```\n\n### Redis Streams (Durable Queue)\n\n```python\n# Producer\ndef emit(stream: str, event: dict):\n    r.xadd(stream, event, maxlen=10000)  # Cap stream length\n\n# Consumer group — guarantees at-least-once delivery\ntry:\n    r.xgroup_create('events:orders', 'processor', id='0', mkstream=True)\nexcept Exception:\n    pass  # Group already exists\n\ndef consume(stream: str, group: str, consumer: str):\n    while True:\n        messages = r.xreadgroup(group, consumer, {stream: '>'}, count=10, block=2000)\n        for _, entries in (messages or []):\n            for msg_id, data in entries:\n                process(data)\n                r.xack(stream, group, msg_id)\n```\n\n> 配信保証、コンシューマーグループ、または再生が必要な場合、Pub\u002FSub代わりに**Streams**を優先してください。\n\n## Key Design\n\n### Naming Conventions\n\n```\n# Pattern: resource:id:field\nuser:123:profile\norder:456:status\ncache:product:789\n\n# Pattern: namespace:resource:id\nmyapp:session:abc123\nmyapp:ratelimit:user:123\n\n# Pattern: resource:date (time-bound keys)\nstats:pageviews:2024-01-01\n```\n\n### TTL Strategy\n\n| Data Type | Suggested TTL |\n|-----------|--------------|\n| User session | 24h (`86400`) |\n| API response cache | 5–15 min |\n| Rate limit window | Match window size |\n| Short-lived tokens | 5–10 min |\n| Leaderboard | 1h–24h |\n| Static\u002Freference data | 1h–1 week |\n\n常にTTLを設定してください。TTLなしのキーは無限に蓄積してメモリ圧力を引き起こします。\n\n## Connection Management\n\n### Connection Pooling\n\n```python\nfrom redis import ConnectionPool, Redis\n\npool = ConnectionPool(\n    host='localhost',\n    port=6379,\n    db=0,\n    max_connections=20,\n    decode_responses=True,\n    socket_connect_timeout=2,\n    socket_timeout=2,\n)\n\nr = Redis(connection_pool=pool)\n```\n\n### Cluster Mode\n\n```python\nfrom redis.cluster import RedisCluster\n\nr = RedisCluster(\n    startup_nodes=[{\"host\": \"redis-1\", \"port\": 6379}],\n    decode_responses=True,\n    skip_full_coverage_check=True,\n)\n```\n\n### Sentinel (High Availability)\n\n```python\nfrom redis.sentinel import Sentinel\n\nsentinel = Sentinel(\n    [('sentinel-1', 26379), ('sentinel-2', 26379)],\n    socket_timeout=0.5,\n)\nmaster = sentinel.master_for('mymaster', decode_responses=True)\nreplica = sentinel.slave_for('mymaster', decode_responses=True)\n```\n\n## Eviction Policies\n\n| Policy | Behavior | Best For |\n|--------|----------|----------|\n| `noeviction` | Error on write when full | Queues \u002F critical data |\n| `allkeys-lru` | Evict least recently used | General cache |\n| `volatile-lru` | LRU only among keys with TTL | Mixed data store |\n| `allkeys-lfu` | Evict least frequently used | Skewed access patterns |\n| `volatile-ttl` | Evict soonest-to-expire | Prioritize long-lived data |\n\n`redis.conf`を通じて設定：`maxmemory-policy allkeys-lru`\n\n## Anti-Patterns\n\n| Anti-Pattern | Problem | Fix |\n|---|---|---|\n| Keys with no TTL | Memory grows unbounded | Always set TTL |\n| `KEYS *` in production | Blocks the server (O(N)) | Use `SCAN` cursor |\n| Storing large blobs (>100KB) | Slow serialization, memory pressure | Store reference + fetch from object store |\n| Single Redis for everything | No isolation between cache & queue | Use separate DBs or instances |\n| Ignoring connection pool limits | Connection exhaustion under load | Size pool to workload |\n| Not handling cache miss stampede | Thundering herd on cold start | Use locks or probabilistic early expiry |\n| `FLUSHALL` without thought | Wipes entire instance | Scope deletes by key pattern |\n\n### Cache Miss Stampede Prevention\n\n```python\nimport threading\n\n_locks: dict[str, threading.Lock] = {}\n_locks_mutex = threading.Lock()\n\ndef get_with_lock(key: str, fetch_fn, ttl: int = 300):\n    cached = r.get(key)\n    if cached:\n        return json.loads(cached)\n\n    with _locks_mutex:\n        if key not in _locks:\n            _locks[key] = threading.Lock()\n        lock = _locks[key]\n    with lock:\n        cached = r.get(key)  # Re-check after acquiring lock\n        if cached:\n            return json.loads(cached)\n        value = fetch_fn()\n        r.setex(key, ttl, json.dumps(value))\n        return value\n```\n\n> マルチプロセスデプロイメント：インプロセスロックを上記の分散ロックセクション から `acquire_lock`\u002F`release_lock` に置き換えてください。\n\n## Examples\n\n**Django\u002FFlask APIエンドポイントにキャッシング追加：**\nレスポンスに5分TTLでCache-asideを使用。リクエストパラメータでキーを指定。\n\n**ユーザーごとにAPIレート制限：**\n低トラフィックエンドポイントに固定ウィンドウを `pipeline(transaction=True)` で使用；正確なユーザーごと制限にはsliding-windowの Lua使用。\n\n**ワーカー間のバックグラウンドジョブ調整：**\n予想ジョブ期間を超えるTTLで `acquire_lock` を使用。常に `finally` ブロックでリリース。\n\n**複数購読者への通知のファンアウト：**\nファイアアンドフォーゲットにPub\u002FSubを使用。保証配信または再生が必要な場合、Streamsに切り替え。\n\n## Quick Reference\n\n| Pattern | When to Use |\n|---------|-------------|\n| Cache-aside | Read-heavy, tolerate slight staleness |\n| Write-through | Strong consistency required |\n| Distributed lock | Prevent concurrent access to a resource |\n| Sliding window rate limit | Accurate per-user throttling |\n| Redis Streams | Durable event queue with consumer groups |\n| Pub\u002FSub | Broadcast with no delivery guarantees needed |\n| Sorted Set leaderboard | Ranked scoring, pagination |\n| HyperLogLog | Approximate unique count at low memory |\n\n## Related\n\n- Skill: `postgres-patterns` — リレーショナルデータパターン\n- Skill: `backend-patterns` — APIおよびサービスレイヤーパターン\n- Skill: `database-migrations` — スキーマバージョニング\n- Skill: `django-patterns` — Djangoキャッシュフレームワーク統合\n- Agent: `database-reviewer` — 全データベースレビューワークフロー\n","# Redis Patterns\n\n一般的なバックエンド使用例に対するRedisベストプラクティスの参考資料。\n\n## How It Works\n\nRedisはメモリ内データ構造ストアで、文字列、ハッシュ、リスト、セット、ソート済みセット、ストリームなどをサポートします。単一インスタンスでは個々のRedisコマンドは原子的ですが、マルチステップワークフローはLuaスクリプト、MULTI\u002FEXECトランザクション、または明示的な同期化が必要です。RDBスナップショットまたはAOFログを通じてデータをオプションで永続化します。クライアントはRESPプロトコルを使用してTCP経由で通信します。接続プール不可欠でリクエストごとのハンドシェイクオーバーヘッドを回避します。\n\n## When to Activate\n\n- アプリケーションにキャッシング追加\n- レート制限またはスロットリング実装\n- 分散ロックまたはコーディネーション構築\n- セッションまたはトークンストレージ設定\n- Pub\u002FSubまたはRedis Streams for messaging使用\n- 本番環境でRedis設定（プール、削除、クラスタリング）\n\n## Data Structure Cheat Sheet\n\n| Use Case | Structure | Example Key |\n|----------|-----------|-------------|\n| Simple cache | String | `product:123` |\n| User session | Hash | `session:abc` |\n| Leaderboard | Sorted Set | `scores:weekly` |\n| Unique visitors | Set | `visitors:2024-01-01` |\n| Activity feed | List | `feed:user:456` |\n| Event stream | Stream | `events:orders` |\n| Counters \u002F rate limits | String (INCR) | `ratelimit:user:123` |\n| Bloom filter \u002F HLL | HyperLogLog | `hll:pageviews` |\n\n## Core Patterns\n\n### Cache-Aside (Lazy Loading)\n\n```python\nimport redis\nimport json\n\nr = redis.Redis(host='localhost', port=6379, decode_responses=True)\n\ndef get_product(product_id: int):\n    cache_key = f\"product:{product_id}\"\n    cached = r.get(cache_key)\n\n    if cached:\n        return json.loads(cached)\n\n    product = db.query(\"SELECT * FROM products WHERE id = %s\", product_id)\n    r.setex(cache_key, 3600, json.dumps(product))  # TTL: 1 hour\n    return product\n```\n\n### Write-Through Cache\n\n```python\ndef update_product(product_id: int, data: dict):\n    # DB書き込み先\n    db.execute(\"UPDATE products SET ... WHERE id = %s\", product_id)\n\n    # キャッシュを即座に更新\n    cache_key = f\"product:{product_id}\"\n    r.setex(cache_key, 3600, json.dumps(data))\n```\n\n### Cache Invalidation\n\n```python\n# タグベース削除 — セット内で関連キーをグループ化\ndef cache_product(product_id: int, category_id: int, data: dict):\n    key = f\"product:{product_id}\"\n    tag = f\"tag:category:{category_id}\"\n    pipe = r.pipeline(transaction=True)\n    pipe.setex(key, 3600, json.dumps(data))\n    pipe.sadd(tag, key)\n    pipe.expire(tag, 3600)\n    pipe.execute()\n\ndef invalidate_category(category_id: int):\n    tag = f\"tag:category:{category_id}\"\n    keys = r.smembers(tag)\n    if keys:\n        r.delete(*keys)\n    r.delete(tag)\n```\n\n### Session Storage\n\n```python\nimport time\nimport uuid\n\ndef create_session(user_id: int, ttl: int = 86400) -> str:\n    session_id = str(uuid.uuid4())\n    key = f\"session:{session_id}\"\n    pipe = r.pipeline(transaction=True)\n    pipe.hset(key, mapping={\n        \"user_id\": user_id,\n        \"created_at\": int(time.time()),\n    })\n    pipe.expire(key, ttl)\n    pipe.execute()\n    return session_id\n\ndef get_session(session_id: str) -> dict | None:\n    data = r.hgetall(f\"session:{session_id}\")\n    return data if data else None\n\ndef delete_session(session_id: str):\n    r.delete(f\"session:{session_id}\")\n```\n\n## Rate Limiting\n\n### Fixed Window (Simple)\n\n```python\ndef is_rate_limited(user_id: int, limit: int = 100, window: int = 60) -> bool:\n    key = f\"ratelimit:{user_id}:{int(time.time()) \u002F\u002F window}\"\n    pipe = r.pipeline(transaction=True)\n    pipe.incr(key)\n    pipe.expire(key, window)\n    count, _ = pipe.execute()\n    return count > limit\n```\n\n### Sliding Window (Lua — Atomic)\n\n```lua\n-- sliding_window.lua\nlocal key = KEYS[1]\nlocal now = tonumber(ARGV[1])\nlocal window = tonumber(ARGV[2])\nlocal limit = tonumber(ARGV[3])\n\nredis.call('ZREMRANGEBYSCORE', key, 0, now - window)\nlocal count = redis.call('ZCARD', key)\n\nif count \u003C limit then\n    -- Use unique member (now + sequence) to avoid collisions within the same millisecond\n    local seq_key = key .. ':seq'\n    local seq = redis.call('INCR', seq_key)\n    redis.call('EXPIRE', seq_key, math.ceil(window \u002F 1000))\n    redis.call('ZADD', key, now, now .. '-' .. seq)\n    redis.call('EXPIRE', key, math.ceil(window \u002F 1000))\n    return 1\nend\nreturn 0\n```\n\n```python\nsliding_window = r.register_script(open('sliding_window.lua').read())\n\ndef allow_request(user_id: int) -> bool:\n    key = f\"ratelimit:sliding:{user_id}\"\n    now = int(time.time() * 1000)\n    return bool(sliding_window(keys=[key], args=[now, 60000, 100]))\n```\n\n## Distributed Locks\n\n### Distributed Lock (Single Node — SET NX PX)\n\n```python\nimport uuid\n\ndef acquire_lock(resource: str, ttl_ms: int = 5000) -> str | None:\n    lock_key = f\"lock:{resource}\"\n    token = str(uuid.uuid4())\n    acquired = r.set(lock_key, token, px=ttl_ms, nx=True)\n    return token if acquired else None\n\ndef release_lock(resource: str, token: str) -> bool:\n    release_script = \"\"\"\n    if redis.call('get', KEYS[1]) == ARGV[1] then\n        return redis.call('del', KEYS[1])\n    else\n        return 0\n    end\n    \"\"\"\n    result = r.eval(release_script, 1, f\"lock:{resource}\", token)\n    return bool(result)\n\n# Usage\ntoken = acquire_lock(\"order:payment:123\")\nif token:\n    try:\n        process_payment()\n    finally:\n        release_lock(\"order:payment:123\", token)\n```\n\n> マルチノード設定の場合、フルRedlockアルゴリズムを実装する `redlock-py` ライブラリを使用してください。\n\n## Pub\u002FSub & Streams\n\n### Pub\u002FSub (Fire-and-Forget)\n\n```python\n# Publisher\ndef publish_event(channel: str, payload: dict):\n    r.publish(channel, json.dumps(payload))\n\n# Subscriber (blocking — run in separate thread\u002Fprocess)\ndef subscribe_events(channel: str):\n    pubsub = r.pubsub()\n    pubsub.subscribe(channel)\n    for message in pubsub.listen():\n        if message['type'] == 'message':\n            handle(json.loads(message['data']))\n```\n\n### Redis Streams (Durable Queue)\n\n```python\n# Producer\ndef emit(stream: str, event: dict):\n    r.xadd(stream, event, maxlen=10000)  # Cap stream length\n\n# Consumer group — guarantees at-least-once delivery\ntry:\n    r.xgroup_create('events:orders', 'processor', id='0', mkstream=True)\nexcept Exception:\n    pass  # Group already exists\n\ndef consume(stream: str, group: str, consumer: str):\n    while True:\n        messages = r.xreadgroup(group, consumer, {stream: '>'}, count=10, block=2000)\n        for _, entries in (messages or []):\n            for msg_id, data in entries:\n                process(data)\n                r.xack(stream, group, msg_id)\n```\n\n> 配信保証、コンシューマーグループ、または再生が必要な場合、Pub\u002FSub代わりに**Streams**を優先してください。\n\n## Key Design\n\n### Naming Conventions\n\n```\n# Pattern: resource:id:field\nuser:123:profile\norder:456:status\ncache:product:789\n\n# Pattern: namespace:resource:id\nmyapp:session:abc123\nmyapp:ratelimit:user:123\n\n# Pattern: resource:date (time-bound keys)\nstats:pageviews:2024-01-01\n```\n\n### TTL Strategy\n\n| Data Type | Suggested TTL |\n|-----------|--------------|\n| User session | 24h (`86400`) |\n| API response cache | 5–15 min |\n| Rate limit window | Match window size |\n| Short-lived tokens | 5–10 min |\n| Leaderboard | 1h–24h |\n| Static\u002Freference data | 1h–1 week |\n\n常にTTLを設定してください。TTLなしのキーは無限に蓄積してメモリ圧力を引き起こします。\n\n## Connection Management\n\n### Connection Pooling\n\n```python\nfrom redis import ConnectionPool, Redis\n\npool = ConnectionPool(\n    host='localhost',\n    port=6379,\n    db=0,\n    max_connections=20,\n    decode_responses=True,\n    socket_connect_timeout=2,\n    socket_timeout=2,\n)\n\nr = Redis(connection_pool=pool)\n```\n\n### Cluster Mode\n\n```python\nfrom redis.cluster import RedisCluster\n\nr = RedisCluster(\n    startup_nodes=[{\"host\": \"redis-1\", \"port\": 6379}],\n    decode_responses=True,\n    skip_full_coverage_check=True,\n)\n```\n\n### Sentinel (High Availability)\n\n```python\nfrom redis.sentinel import Sentinel\n\nsentinel = Sentinel(\n    [('sentinel-1', 26379), ('sentinel-2', 26379)],\n    socket_timeout=0.5,\n)\nmaster = sentinel.master_for('mymaster', decode_responses=True)\nreplica = sentinel.slave_for('mymaster', decode_responses=True)\n```\n\n## Eviction Policies\n\n| Policy | Behavior | Best For |\n|--------|----------|----------|\n| `noeviction` | Error on write when full | Queues \u002F critical data |\n| `allkeys-lru` | Evict least recently used | General cache |\n| `volatile-lru` | LRU only among keys with TTL | Mixed data store |\n| `allkeys-lfu` | Evict least frequently used | Skewed access patterns |\n| `volatile-ttl` | Evict soonest-to-expire | Prioritize long-lived data |\n\n`redis.conf`を通じて設定：`maxmemory-policy allkeys-lru`\n\n## Anti-Patterns\n\n| Anti-Pattern | Problem | Fix |\n|---|---|---|\n| Keys with no TTL | Memory grows unbounded | Always set TTL |\n| `KEYS *` in production | Blocks the server (O(N)) | Use `SCAN` cursor |\n| Storing large blobs (>100KB) | Slow serialization, memory pressure | Store reference + fetch from object store |\n| Single Redis for everything | No isolation between cache & queue | Use separate DBs or instances |\n| Ignoring connection pool limits | Connection exhaustion under load | Size pool to workload |\n| Not handling cache miss stampede | Thundering herd on cold start | Use locks or probabilistic early expiry |\n| `FLUSHALL` without thought | Wipes entire instance | Scope deletes by key pattern |\n\n### Cache Miss Stampede Prevention\n\n```python\nimport threading\n\n_locks: dict[str, threading.Lock] = {}\n_locks_mutex = threading.Lock()\n\ndef get_with_lock(key: str, fetch_fn, ttl: int = 300):\n    cached = r.get(key)\n    if cached:\n        return json.loads(cached)\n\n    with _locks_mutex:\n        if key not in _locks:\n            _locks[key] = threading.Lock()\n        lock = _locks[key]\n    with lock:\n        cached = r.get(key)  # Re-check after acquiring lock\n        if cached:\n            return json.loads(cached)\n        value = fetch_fn()\n        r.setex(key, ttl, json.dumps(value))\n        return value\n```\n\n> マルチプロセスデプロイメント：インプロセスロックを上記の分散ロックセクション から `acquire_lock`\u002F`release_lock` に置き換えてください。\n\n## Examples\n\n**Django\u002FFlask APIエンドポイントにキャッシング追加：**\nレスポンスに5分TTLでCache-asideを使用。リクエストパラメータでキーを指定。\n\n**ユーザーごとにAPIレート制限：**\n低トラフィックエンドポイントに固定ウィンドウを `pipeline(transaction=True)` で使用；正確なユーザーごと制限にはsliding-windowの Lua使用。\n\n**ワーカー間のバックグラウンドジョブ調整：**\n予想ジョブ期間を超えるTTLで `acquire_lock` を使用。常に `finally` ブロックでリリース。\n\n**複数購読者への通知のファンアウト：**\nファイアアンドフォーゲットにPub\u002FSubを使用。保証配信または再生が必要な場合、Streamsに切り替え。\n\n## Quick Reference\n\n| Pattern | When to Use |\n|---------|-------------|\n| Cache-aside | Read-heavy, tolerate slight staleness |\n| Write-through | Strong consistency required |\n| Distributed lock | Prevent concurrent access to a resource |\n| Sliding window rate limit | Accurate per-user throttling |\n| Redis Streams | Durable event queue with consumer groups |\n| Pub\u002FSub | Broadcast with no delivery guarantees needed |\n| Sorted Set leaderboard | Ranked scoring, pagination |\n| HyperLogLog | Approximate unique count at low memory |\n\n## Related\n\n- Skill: `postgres-patterns` — リレーショナルデータパターン\n- Skill: `backend-patterns` — APIおよびサービスレイヤーパターン\n- Skill: `database-migrations` — スキーマバージョニング\n- Skill: `django-patterns` — Djangoキャッシュフレームワーク統合\n- Agent: `database-reviewer` — 全データベースレビューワークフロー\n",{"name":5,"origin":24,"description":7},"ECC","main","57e7aa6b6e03bce1a7d7862ba9c2ec312f7f19b5","src\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Fredis-patterns",0,"https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee","https:\u002F\u002Fwithcyril.me\u002F","Hi, I’m Julian Cyril D, a Computer Science and Business Systems student at PSNACET.\r\nI’m passionate about full-stack development, UI\u002FUX design, and building sma","2026-11-04 23:28:50",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add Cyrilthetecchieee\u002Fcyril-code- --skill redis-patterns",{"tool":40,"command":41},"bunx","bunx skills add Cyrilthetecchieee\u002Fcyril-code- --skill redis-patterns",{"tool":43,"command":44},"pnpm","pnpm dlx skills add Cyrilthetecchieee\u002Fcyril-code- --skill redis-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Fredis-patterns\u002FSKILL.md",true,[],[49,58,65,73,80,87],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":54,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":19},"01M7AQV6CYX8RMC78420V9WZ62","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7AQV2895N3S1MEX6K76G6G2","youtube-downloader","Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fvideo-downloader\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":69,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7AQTRNX62DNKVZ5GXEHRBKB","theme-factory","Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors\u002Ffonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7AQTNNVHAAN9H6DA8T6ZVE0","template-skill","Replace with description of the skill and when Claude should use it.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftemplate-skill\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7AQTJ3MQ6AKX152MEX2MYCC","tailored-resume-generator","Analyzes job descriptions and generates tailored resumes that highlight relevant experience, skills, and achievements to maximize interview chances","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftailored-resume-generator\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":91,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7AQTD7D5MYET2YWG7HG9WM3","slack-gif-creator","Toolkit for creating animated GIFs optimized for Slack, with validators for size constraints and composable animation primitives. This skill applies when users request animated GIFs or emoji animations for Slack from descriptions like \"make me a GIF for Slack of X doing Y\".","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FSKILL.md",[],[]]