[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CSR3DQAGSC9SQQWNWA23KM":3,"skill-same:01M7CSR3DQAGSC9SQQWNWA23KM":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":26,"commitSha":27,"skillDirectory":28,"forksCount":14,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7CSR3DQAGSC9SQQWNWA23KM","redis-patterns",null,"Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub\u002Fsub, and connection management for production applications.","Henrique1601\u002FSkiilsToIAs","Henrique1601","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F92006691?v=4","01M7CRXVT0GVXVK80JT1GR687S","Henrique Bezerra Dos Santos","01M7CRXVTN5Y8TMWJ1MDSKCQ1T",0,"MIT","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fredis-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: redis-patterns\ndescription: Redis data structure patterns, caching strategies, distributed locks, rate limiting, pub\u002Fsub, and connection management for production applications.\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":24,"description":7},{"origin":25},"ECC","main","a73152352c0612252131e5cf84e91312a6cf17dc","backend-database\u002Fredis-patterns","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs","https:\u002F\u002Fgithub.com\u002FHenrique1601","https:\u002F\u002Fbezerraportifolio.netlify.app\u002F","Full Stack Developer | React, Next.js, TypeScript, Node.js & IA | Construindo produtos digitais e soluções SaaS","2026-11-15 02:56:04",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add Henrique1601\u002FSkiilsToIAs --skill redis-patterns",{"tool":40,"command":41},"bunx","bunx skills add Henrique1601\u002FSkiilsToIAs --skill redis-patterns",{"tool":43,"command":44},"pnpm","pnpm dlx skills add Henrique1601\u002FSkiilsToIAs --skill redis-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fredis-patterns\u002FSKILL.md",true,[],[49,56,63,71,78,85],{"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":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7E2ANBW9V6AVX5JXNCEAWF8","rag-architect-agent","Agente Arquiteto de RAG, Embeddings & Busca Vetorial. Especialista em design e implementação de pipelines de Retrieval-Augmented Generation de alta fidelidade: chunking semântico, modelagem pgvector no PostgreSQL (Neon\u002FSupabase), busca híbrida (cosseno + BM25), reranking, validação via TypeSafe AI e filosofia Ponytail (anti-overengineering).","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fcustom-agents\u002Frag-architect-agent\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7E29KKF8R02ZRGYE2MJM67G","rag-architecture-patterns","Padrões arquiteturais e implementação de pipelines RAG (Retrieval-Augmented Generation) de alta fidelidade para qualquer projeto ou sistema. Cobre chunking semântico, embeddings, busca híbrida (pgvector + BM25), reranking, validação via TypeSafe AI e filosofia Ponytail (anti-overengineering).","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fai-agents\u002Frag-architecture-patterns\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":67,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7CWRA8E3BJ7CPY8N8EG28J1","skill-repair","Use this to fix and re-install agent skills that have failed installation.\nThis skill provides the necessary context and permissions to surgically update\nthe `manifest.json` after a fix has been applied.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fskill-repair\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M7CWR66FZP8FA47WVZ4Z2EXC","security-scan","Scan your Claude Code configuration (.claude\u002F directory) for security vulnerabilities, misconfigurations, and injection risks using AgentShield. Checks CLAUDE.md, settings.json, MCP servers, hooks, and agent definitions.","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fsecurity-scan\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M7CWR0QPY58QPTR1P759TFNG","security-review","Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment\u002Fsensitive features. Provides comprehensive security checklist and patterns.","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fsecurity-review\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7CWQXCE40XWT4FZ3VWZFGDP","security-bounty-hunter","Hunt for exploitable, bounty-worthy security issues in repositories. Focuses on remotely reachable vulnerabilities that qualify for real reports instead of noisy local-only findings.","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fsecurity-bounty-hunter\u002FSKILL.md",[],[]]