.mdc Python Redis database

Redis データモデリング・パフォーマンスルール

Redisのベストプラクティス: 階層型キー命名、ハッシュタグによるクラスター対応、コネクションプール、パイプライン、SCAN活用、セキュリティ設定。

.mdc · 115 lines
# Redis Best Practices

Redis is a powerful, single-threaded, in-memory database. Its efficiency hinges on how you interact with it.

## 1. Data Modeling & Key Design

### Use Hierarchical Key Naming

Good: `user:1:profile:name`, `order:456:cart:items`
Bad: `user:1:name`, `order:456:items`

### Avoid Large Objects in Single Keys

Use Redis Hash for structured data:
```python
redis_client.hset("user:1:profile", mapping={
    "id": 1, "name": "Alice", "email": "[email protected]"
})
```

### Use Hashtags for Cluster Multi-Key Operations

Keys with the same hashtag are guaranteed to be on the same hash slot:
```python
# Good: guaranteed co-location in cluster
redis_client.mget("{user:1}:profile", "{user:1}:orders")
```

### Never Use Numbered Databases (`SELECT`)

Numbered databases are an anti-pattern. Use key prefixes instead: `app:cache:mykey`, `app:sessions:mykey`.

## 2. Connection & Memory Management

### Always Use Connection Pooling

```python
pool = redis.ConnectionPool(host='localhost', port=6379, max_connections=10)
redis_client = redis.Redis(connection_pool=pool)
```

### Configure Memory Policies

```redis
# redis.conf
maxmemory 8gb
maxmemory-policy allkeys-lru
lazyfree-lazy-eviction yes
lazyfree-lazy-expire yes
```

## 3. Cluster-Aware Client Usage

### Use Cluster-Aware Clients

```python
from redis.cluster import RedisCluster
client = RedisCluster(host='cluster-node-1', port=6379, decode_responses=True)
```

### Implement Exponential Backoff for Client Discovery

```python
def connect_with_backoff(hosts, max_retries=5):
    for i in range(max_retries):
        try:
            client = RedisCluster(startup_nodes=hosts, decode_responses=True)
            client.ping()
            return client
        except RedisClusterException:
            sleep_time = (2 ** i) + random.uniform(0, 1)
            time.sleep(sleep_time)
    raise ConnectionError("Failed to connect after retries")
```

## 4. Query Optimization

### Use Pipelining for Batch Operations

```python
pipe = redis_client.pipeline()
pipe.set("key1", "value1")
pipe.set("key2", "value2")
pipe.get("key1")
results = pipe.execute()  # Single round-trip
```

### Never Use `KEYS` in Production — Use `SCAN`

```python
cursor = 0
while True:
    cursor, keys = redis_client.scan(cursor, match="user:*", count=100)
    for key in keys:
        pass  # Process key
    if cursor == 0:
        break
```

## 5. Security

- Always set a strong password: `requirepass your_strong_password`
- Isolate Redis behind a firewall or VPC — never expose publicly
- Disable dangerous commands in production: `rename-command FLUSHALL ""`

## 6. Testing

```python
@pytest.fixture(scope="function")
def redis_client():
    client = redis.Redis(host='localhost', port=6379, decode_responses=True)
    client.flushdb()  # Clear database for each test
    yield client
    client.flushdb()
```
Share on X

こちらもおすすめ

database カテゴリの他のルール

もっとルールを探す

CLAUDE.md、.cursorrules、AGENTS.md、Image Prompts の全 223 ルールをチェック。