Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

redis-state-management

БесплатноБез исполняемых скриптовНе проверен

Comprehensive guide for Redis state management including caching strategies, session management, pub/sub patterns, distributed locks, and data structures

manutejот manutej★ 64 звезды на GitHub14 установок в других каталогах

Об этом скилле

Redis State Management

A comprehensive skill for mastering Redis state management patterns in distributed systems. This skill covers caching strategies, session management, pub/sub messaging, distributed locks, data structures, and production-ready patterns using redis-py.

When to Use This Skill

Use this skill when:

  • Implementing high-performance caching layers for web applications
  • Managing user sessions in distributed environments
  • Building real-time messaging and event distribution systems
  • Coordinating distributed processes with locks and synchronization
  • Storing and querying structured data with Redis data structures
  • Optimizing application performance with Redis
  • Scaling applications horizontally with shared state
  • Implementing rate limiting, counters, and analytics
  • Building microservices with Redis as a communication layer
  • Managing temporary data with automatic expiration (TTL)
  • Implementing leaderboards, queues, and real-time features

Core Concepts

Redis Fundamentals

Redis (Remote Dictionary Server) is an in-memory data structure store used as:

  • Database: Persistent key-value storage
  • Cache: High-speed data layer
  • Message Broker: Pub/sub and stream messaging
  • Session Store: Distributed session management

Key Characteristics:

  • In-memory storage (microsecond latency)
  • Optional persistence (RDB snapshots, AOF logs)
  • Rich data structures beyond key-value
  • Atomic operations on complex data types
  • Built-in replication and clustering
  • Pub/sub messaging support
  • Lua scripting for complex operations
  • Pipelining for batch operations

Redis Data Structures

Redis provides multiple data types for different use cases:

  1. Strings: Simple key-value pairs, binary safe

    • Use for: Cache values, counters, flags, JSON objects
    • Max size: 512 MB
    • Commands: SET, GET, INCR, APPEND
  2. Hashes: Field-value maps (objects)

    • Use for: User profiles, configuration objects, small entities
    • Efficient for storing objects with multiple fields
    • Commands: HSET, HGET, HMGET, HINCRBY
  3. Lists: Ordered collections (linked lists)

    • Use for: Queues, activity feeds, recent items
    • Operations at head/tail are O(1)
    • Commands: LPUSH, RPUSH, LPOP, RPOP, LRANGE
  4. Sets: Unordered unique collections

    • Use for: Tags, unique visitors, relationships
    • Set operations: union, intersection, difference
    • Commands: SADD, SMEMBERS, SISMEMBER, SINTER
  5. Sorted Sets: Ordered sets with scores

    • Use for: Leaderboards, time-series, priority queues
    • Range queries by score or rank
    • Commands: ZADD, ZRANGE, ZRANGEBYSCORE, ZRANK
  6. Streams: Append-only logs with consumer groups

    • Use for: Event sourcing, activity logs, message queues
    • Built-in consumer group support
    • Commands: XADD, XREAD, XREADGROUP

Connection Management

Connection Pools: Redis connections are expensive to create. Always use connection pools:

import redis

# Connection pool (recommended)
pool = redis.ConnectionPool(host='localhost', port=6379, db=0, max_connections=10)
r = redis.Redis(connection_pool=pool)

# Direct connection (avoid in production)
r = redis.Redis(host='localhost', port=6379, db=0)

Best Practices:

  • Use connection pools for all applications
  • Set appropriate max_connections based on workload
  • Enable decode_responses=True for string data
  • Configure socket_timeout and socket_keepalive
  • Handle connection errors with retries

Data Persistence

Redis offers two persistence mechanisms:

RDB (Redis Database): Point-in-time snapshots

  • Compact binary format
  • Fast restart times
  • Lower disk I/O
  • Potential data loss between snapshots

AOF (Append-Only File): Log of write operations

  • Better durability (fsync policies)
  • Larger files, slower restarts
  • Can be automatically rewritten/compacted
  • Minimal data loss potential

Hybrid Approach: RDB + AOF for best of both worlds

RESP 3 Protocol

Redis Serialization Protocol version 3 offers:

  • Client-side caching support
  • Better data type support
  • Push notifications
  • Performance improvements
import redis
from redis.cache import CacheConfig

# Enable RESP3 with client-side caching
r = redis.Redis(host='localhost', port=6379, protocol=3,
                cache_config=CacheConfig())

Caching Strategies

Cache-Aside (Lazy Loading)

Pattern: Application checks cache first, loads from database on miss

import redis
import json
from typing import Optional, Dict, Any

r = redis.Redis(decode_responses=True)

def get_user(user_id: int) -> Optional[Dict[str, Any]]:
    """Cache-aside pattern for user data."""
    cache_key = f"user:{user_id}"

    # Try cache first
    cached_data = r.get(cache_key)
    if cached_data:
        return json.loads(cached_data)

    # Cache miss - load from database
    user_data = database.get_user(user_id)  # Your DB query
    if user_data:
        # Store in cache with 1
Полный SKILL.md на GitHub

Установить redis-state-management в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

EXAMPLES.mdREADME.mdVALIDATION.md

FAQ

Что делает скилл redis-state-management?

Comprehensive guide for Redis state management including caching strategies, session management, pub/sub patterns, distributed locks, and data structures

Как установить скилл redis-state-management?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл redis-state-management запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить redis-state-management с