[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M70H1F4SYKS5H5DVYYT8MT5G":3,"skill-same:01M70H1F4SYKS5H5DVYYT8MT5G":78},{"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":28,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":56,"commitSha":57,"skillDirectory":58,"forksCount":59,"repositoryHtmlUrl":60,"repositoryHomepageUrl":6,"ownerHtmlUrl":61,"ownerBlogUrl":6,"ownerDescription":62,"updatedAt":63,"install":64,"resources":77},"01M70H1F4SYKS5H5DVYYT8MT5G","redis-patterns",null,"Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub\u002Fsub, and connection management for production applications. Use when adding caching, a distributed lock, rate limiting, or pub\u002Fsub with Redis, or when key design needs review.","mdnaimul22\u002Fhuman-skills","mdnaimul22","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F64520358?v=4","01M70FH95MH2H796Q01TYSFZ03","Naimul","01M70FH96798CQR4YHA13F17GA",3,"MIT","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fredis-patterns\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000015","视觉设计","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"patterns","redis","redis patterns","connection management","rate limiting","with","caching strategies","distributed","use","applications","for","data","rate","structure","strategies","lock","review","caching","when","design","2026-11-10 10:12:30",false,"---\nname: redis-patterns\ndescription: Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub\u002Fsub, and connection management for production applications. Use when adding caching, a distributed lock, rate limiting, or pub\u002Fsub with Redis, or when key design needs review.\nmetadata:\n  origin: ECC\n---\n\n# Redis Patterns\n\nQuick reference for Redis best practices across common backend use cases.\n\n## How It Works\n\nRedis is an in-memory data structure store that supports strings, hashes, lists, sets, sorted sets, streams, and more. Individual Redis commands are atomic on a single instance; multi-step workflows require Lua scripts, MULTI\u002FEXEC transactions, or explicit synchronization to stay atomic. Data is optionally persisted via RDB snapshots or AOF logs. Clients communicate over TCP using the RESP protocol; connection pools are essential to avoid per-request handshake overhead.\n\n## When to Activate\n\n- Adding caching to an application\n- Implementing rate limiting or throttling\n- Building distributed locks or coordination\n- Setting up session or token storage\n- Using Pub\u002FSub or Redis Streams for messaging\n- Configuring Redis in production (pooling, eviction, clustering)\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    # Write to DB first\n    db.execute(\"UPDATE products SET ... WHERE id = %s\", product_id)\n\n    # Immediately update cache\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# Tag-based invalidation — group related keys under a set\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> For multi-node setups use the `redlock-py` library which implements the full Redlock algorithm.\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> Prefer **Streams** over Pub\u002FSub when you need delivery guarantees, consumer groups, or replay.\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\nAlways set a TTL. Keys without TTL accumulate indefinitely and cause memory pressure.\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\nSet via `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> Note: for multi-process deployments, replace the in-process lock with `acquire_lock`\u002F`release_lock` from the Distributed Locks section above.\n\n## Examples\n\n**Add caching to a Django\u002FFlask API endpoint:**\nUse cache-aside with `setex` and a 5-minute TTL on the response. Key on the request parameters.\n\n**Rate-limit an API by user:**\nUse fixed-window with `pipeline(transaction=True)` for low-traffic endpoints; use sliding-window Lua for accurate per-user throttling.\n\n**Coordinate a background job across workers:**\nUse `acquire_lock` with a TTL that exceeds the expected job duration. Always release in a `finally` block.\n\n**Fan-out notifications to multiple subscribers:**\nUse Pub\u002FSub for fire-and-forget. Switch to Streams if you need guaranteed delivery or replay for late consumers.\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` — relational data patterns\n- Skill: `backend-patterns` — API and service layer patterns\n- Skill: `database-migrations` — schema versioning\n- Skill: `django-patterns` — Django cache framework integration\n- Agent: `database-reviewer` — full database review workflow\n","# Redis Patterns\n\nQuick reference for Redis best practices across common backend use cases.\n\n## How It Works\n\nRedis is an in-memory data structure store that supports strings, hashes, lists, sets, sorted sets, streams, and more. Individual Redis commands are atomic on a single instance; multi-step workflows require Lua scripts, MULTI\u002FEXEC transactions, or explicit synchronization to stay atomic. Data is optionally persisted via RDB snapshots or AOF logs. Clients communicate over TCP using the RESP protocol; connection pools are essential to avoid per-request handshake overhead.\n\n## When to Activate\n\n- Adding caching to an application\n- Implementing rate limiting or throttling\n- Building distributed locks or coordination\n- Setting up session or token storage\n- Using Pub\u002FSub or Redis Streams for messaging\n- Configuring Redis in production (pooling, eviction, clustering)\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    # Write to DB first\n    db.execute(\"UPDATE products SET ... WHERE id = %s\", product_id)\n\n    # Immediately update cache\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# Tag-based invalidation — group related keys under a set\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> For multi-node setups use the `redlock-py` library which implements the full Redlock algorithm.\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> Prefer **Streams** over Pub\u002FSub when you need delivery guarantees, consumer groups, or replay.\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\nAlways set a TTL. Keys without TTL accumulate indefinitely and cause memory pressure.\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\nSet via `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> Note: for multi-process deployments, replace the in-process lock with `acquire_lock`\u002F`release_lock` from the Distributed Locks section above.\n\n## Examples\n\n**Add caching to a Django\u002FFlask API endpoint:**\nUse cache-aside with `setex` and a 5-minute TTL on the response. Key on the request parameters.\n\n**Rate-limit an API by user:**\nUse fixed-window with `pipeline(transaction=True)` for low-traffic endpoints; use sliding-window Lua for accurate per-user throttling.\n\n**Coordinate a background job across workers:**\nUse `acquire_lock` with a TTL that exceeds the expected job duration. Always release in a `finally` block.\n\n**Fan-out notifications to multiple subscribers:**\nUse Pub\u002FSub for fire-and-forget. Switch to Streams if you need guaranteed delivery or replay for late consumers.\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` — relational data patterns\n- Skill: `backend-patterns` — API and service layer patterns\n- Skill: `database-migrations` — schema versioning\n- Skill: `django-patterns` — Django cache framework integration\n- Agent: `database-reviewer` — full database review workflow\n",{"name":5,"metadata":54,"description":7},{"origin":55},"ECC","main","74715deacdc69119d739f38916f8ee4f0f979ebf","skills\u002Fstorage\u002Faffaan-m_ECC\u002Fredis-patterns",0,"https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills","https:\u002F\u002Fgithub.com\u002Fmdnaimul22","AI Agents Workflows Automation | Specializing in Python, FastAPI, MCP Agents & Custom ERP.","2026-11-11 21:16:57",{"source":8,"skillName":5,"commands":65,"prompt":75,"zipAvailable":76},[66,69,72],{"tool":67,"command":68},"npx","npx skills add mdnaimul22\u002Fhuman-skills --skill redis-patterns",{"tool":70,"command":71},"bunx","bunx skills add mdnaimul22\u002Fhuman-skills --skill redis-patterns",{"tool":73,"command":74},"pnpm","pnpm dlx skills add mdnaimul22\u002Fhuman-skills --skill redis-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fredis-patterns\u002FSKILL.md",true,[],[79,87,95,102,109,116],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":86},"01M767791C1KRP2ZRW2Z73VZ5Q","system-lifecycle-designer","Universal architectural methodology for designing granular, atomic, and sub-atomic lifecycles and end-to-end workflows for single functionality integrations across any domain (daemons, batch jobs, request transactions, resource pools). Provides patterns for deterministic identity, pre-commit validation, differential reconciliation, sticky leasing, state machines, transactional persistence, and closed-loop feedback.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fmy_skills\u002Fsystem-lifecycle-designer\u002FSKILL.md",[],[],"2026-11-12 13:55:43",{"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":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":94},"01M748ABPN5F1FANHH6HKZQMXT","style-sampling","Make a new episode in a proven video style - Collage Explainer, Finance Explainer, Animated Science Explainer, 3D Brand Explainer, 3D True Crime - on the person's topic. Use for \"an episode of\", \"in the style of\", \"sample this style\", 「用这个风格做一集」. One video to copy is reverse-any-video.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fheygen-com_hyperframes\u002Fstyle-sampling\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":94},"01M748A59V04PKW4HA0XQ81FGP","reverse-any-video","Rebuild any video file as an editable HyperFrames project - motion graphics, talking heads, live action or AI-generated footage - checked against the original frame by frame. Use to reverse, recreate, remake, replicate or copy a video, or 「复刻这个视频」「照着这个视频做一个」.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Fheygen-com_hyperframes\u002Freverse-any-video\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":94},"01M7487T50P55CSXMWXZ0G9KRG","typescript-patterns","TypeScript patterns for strict, type-safe, maintainable code in modern TypeScript and JavaScript applications. Covers strict compiler configuration, type design, narrowing, discriminated unions, generics, async and error handling, module boundaries, dependency hygiene, and type-level testing. Use when writing or reviewing TypeScript or JavaScript code.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Ftypescript-patterns\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":94},"01M7487ERZRGPC5NJ75077Y238","test-collaboration","Inventory and govern a project's test assets. Connect requirements, business rules, risks, bugs, and cross-boundary contracts to stable TEST-IDs and executable evidence in the repository's existing test registry or TESTS.md. Use for test inventory, test gap analysis, unit\u002Fintegration\u002Fcontract\u002FE2E\u002Fsmoke classification, bug-to-test regression protection, consumer\u002Fprovider contract testing, test-necessity review, and pre-delivery evidence review.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Ftest-collaboration\u002FSKILL.md",[],[],{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":122,"publishedAt":94},"01M748721J3GKR2WS6K0QWFC35","story-lifecycle","Manage a file-based epic → story → sprint development loop without requiring an external project management tool. Creates and tracks epics, breaks them into user stories, assigns them to sprints, and drives implementation story by story. Use when starting a new feature initiative or when the team has no Jira\u002FLinear\u002FTaiga but needs structured delivery tracking.","https:\u002F\u002Fgithub.com\u002Fmdnaimul22\u002Fhuman-skills\u002Fblob\u002Fmain\u002Fskills\u002Fstorage\u002Faffaan-m_ECC\u002Fstory-lifecycle\u002FSKILL.md",[],[]]