[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6JDFK74RB9HTX0E6G939F8R":3,"skill-same:01M6JDFK74RB9HTX0E6G939F8R":61},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":33,"linkOnly":34,"markdownContent":35,"markdownBody":36,"frontMatter":37,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":42,"repositoryHtmlUrl":43,"repositoryHomepageUrl":44,"ownerHtmlUrl":45,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":46,"install":47,"resources":60},"01M6JDFK74RB9HTX0E6G939F8R","redis-patterns",null,"Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub\u002Fsub, and connection management for production applications.","S3YED\u002Fappie-kit","S3YED","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F62743867?v=4","01M6JBKBRRVP6KMS0VWZ27T3R6","01M6JBKBX0KG30284PW1DBYJT1",14,"MIT","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fecc\u002Fredis-patterns\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],"redis","patterns","redis patterns","distributed","data","Production","applications","management","structure","caching","strategies","caching strategies","rate limiting","connection","for","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.\norigin: 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,"origin":38,"description":7},"ECC","master","8ec37df6d71fb664ea19d32c079e7d3ff931a8e0","skills\u002Fecc\u002Fredis-patterns",3,"https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit","https:\u002F\u002Fweblyfe.ai","https:\u002F\u002Fgithub.com\u002FS3YED","2026-08-27 01:54:02",{"source":8,"skillName":5,"commands":48,"prompt":58,"zipAvailable":59},[49,52,55],{"tool":50,"command":51},"npx","npx skills add S3YED\u002Fappie-kit --skill redis-patterns",{"tool":53,"command":54},"bunx","bunx skills add S3YED\u002Fappie-kit --skill redis-patterns",{"tool":56,"command":57},"pnpm","pnpm dlx skills add S3YED\u002Fappie-kit --skill redis-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fecc\u002Fredis-patterns\u002FSKILL.md",true,[],[62,98,133,159,190,214],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":79,"publishedAt":33},"01M6JFD4M6N4DSGC7TXEJ5R3J2","ai-music","AI music generation and audio tools: HeartMuLa lyrics-to-music generation, songwriting craft (+ Suno prompts), and audio spectrogram\u002Ffeature visualization.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fwethlete\u002Fai-music\u002FSKILL.md",[68,73,76],{"categoryNo":69,"categoryName":70,"taxonomyType":71,"taxonomyTypeDesc":72},"01JBSEEDCAT000000000000013","分析与可视化","SCENARIO","使用场景",{"categoryNo":74,"categoryName":75,"taxonomyType":71,"taxonomyTypeDesc":72},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":77,"categoryName":78,"taxonomyType":71,"taxonomyTypeDesc":72},"01JBSEEDCAT000000000000023","Skill与智能体开发",[80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97],"music","ai music","humanizer","visualization","Tools","Audio","hermes","hermes agent","songwriting","suno","lyrics","prompts","heartmula","craft","generation","feature","ai music generation","music generation",{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":112,"publishedAt":33},"01M6JFCZE4XNFQFMNZDHKHT5V5","agentic-webdesign-design-system-ingestion","Use v0 Design Systems 2.0, Bolt Design System Agents, or Lovable to generate production UI from a client's real design system components — not generic Tailwind. Use when building a client website where brand consistency matters.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-design\u002Fagentic-webdesign-design-system-ingestion\u002FSKILL.md",[104,107],{"categoryNo":105,"categoryName":106,"taxonomyType":71,"taxonomyTypeDesc":72},"01JBSEEDCAT000000000000015","视觉设计",{"categoryNo":108,"categoryName":109,"taxonomyType":110,"taxonomyTypeDesc":111},"01JBSEEDCAT000000000000032","设计师","PROFESSION","适用职业",[113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132],"design","agentic","design system","system","ingestion","webdesign","agentic webdesign design system ingestion","components","generate","design systems","website","ui","Tailwind","bolt","lovable","v0","design-system","wed","design system components","appie",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":141,"publishedAt":33},"01M6JFCVPX3913CFAS6QQJ33ZB","agentic-webdesign-agent-elements","Use 21st.dev Agent Elements — 25 shadcn\u002Fui components purpose-built for AI agent UIs. Tool cards (Bash, Edit, Search, Plan, Subagent, MCP), chat, input, streaming. Open source, shadcn-registry install, no runtime lock-in.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-design\u002Fagentic-webdesign-agent-elements\u002FSKILL.md",[139,140],{"categoryNo":77,"categoryName":78,"taxonomyType":71,"taxonomyTypeDesc":72},{"categoryNo":108,"categoryName":109,"taxonomyType":110,"taxonomyTypeDesc":111},[114,142,118,143,144,145,120,146,147,148,149,150,151,152,153,154,155,156,157,158],"elements","agentic webdesign agent elements","MCP","ai agent","registry","search","streaming","open source","open","Bash","plan","subagent","edit","install","input","lock","source",{"skillNo":160,"name":161,"nameZh":6,"description":162,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":163,"categories":164,"keywords":169,"publishedAt":33},"01M6JFCQC7H65M9QJ6TRE71BS1","vercel-deployment","Deploy static sites and frontends to Vercel — handles both CLI and REST API paths, including the CLI token sanitization workaround.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fvercel-deployment\u002FSKILL.md",[165,168],{"categoryNo":166,"categoryName":167,"taxonomyType":71,"taxonomyTypeDesc":72},"01JBSEEDCAT000000000000011","运维与部署",{"categoryNo":77,"categoryName":78,"taxonomyType":71,"taxonomyTypeDesc":72},[170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189],"deployment","vercel deployment","vercel","macos","cli","linux","windows","deploy","vercel deploy","REST","api","site","deploy to vercel","token","rest api","host","sites","paths","sanitization","static site",{"skillNo":191,"name":192,"nameZh":6,"description":193,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":194,"categories":195,"keywords":197,"publishedAt":33},"01M6JFCM4SMTXBM5A01BK2YQG1","software-quality-workflows","Umbrella workflow for TDD, debugging, code simplification, spikes, pre-commit review, and debugger-assisted investigation.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fsoftware-quality-workflows\u002FSKILL.md",[196],{"categoryNo":77,"categoryName":78,"taxonomyType":71,"taxonomyTypeDesc":72},[198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,32],"workflows","quality","software","software quality workflows","review","tdd","workflow","commit","debugging","code","debugger","pre-commit","investigation","code simplification","user","simplification",{"skillNo":215,"name":216,"nameZh":6,"description":217,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":218,"categories":219,"keywords":227,"publishedAt":33},"01M6JFCGD0M6CEATY01W7YN6DB","react-component-refactoring","Safely refactor large React components into smaller, maintainable pieces using proven patterns","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Freact-component-refactoring\u002FSKILL.md",[220,223,226],{"categoryNo":221,"categoryName":222,"taxonomyType":71,"taxonomyTypeDesc":72},"01JBSEEDCAT000000000000007","代码审查",{"categoryNo":224,"categoryName":225,"taxonomyType":71,"taxonomyTypeDesc":72},"01JBSEEDCAT000000000000009","前端开发",{"categoryNo":77,"categoryName":78,"taxonomyType":71,"taxonomyTypeDesc":72},[228,229,230,231,232,233,234,235,173,236,237,120,238,176,239,207,240,241,19,242],"react","component","refactoring","component refactoring","react component","react component refactoring","frontend","writing","safe","typescript","react components","modular","refactor","simplify","test-driven-development"]