Files
life-echo/api/.agents/skills/redis-development/rules/conn-pooling.md
Sully 53e0065e3e refactor(api): TOML 配置 SSOT、统一错误契约、Auth/事务加固与可观测性 (#33)
配置 SSOT(TOML + .env)
统一错误契约
Auth 与事务边界
Redis / Celery 可靠性:业务 Redis(DB/0)与 Celery broker/backend(DB/1)显式拆分;连接池、sync client
可观测性(OpenTelemetry + LGTM)
2026-05-22 13:44:50 +08:00

2.1 KiB

title, impact, impactDescription, tags, description, alwaysApply
title impact impactDescription tags description alwaysApply
Use Connection Pooling or Multiplexing HIGH Reduces connection overhead by 10x or more connections, pooling, multiplexing, performance Use Connection Pooling or Multiplexing true

Use Connection Pooling or Multiplexing

Reuse connections via a pool or multiplexing instead of creating new connections per request.

Correct: Use a connection pool.

Python (redis-py):

import redis

# Good: Connection pool - reuses existing connections
pool = redis.ConnectionPool(host='localhost', port=6379, max_connections=50)
r = redis.Redis(connection_pool=pool)

Java (Jedis):

import redis.clients.jedis.JedisPooled;

// JedisPooled manages a connection pool internally
try (JedisPooled jedis = new JedisPooled("redis://localhost:6379")) {
    jedis.set("testKey", "testValue");
}

Correct: Use multiplexing (Lettuce, NRedisStack).

// Lettuce uses multiplexing by default - single connection handles all traffic
RedisClient client = RedisClient.create("redis://localhost:6379");
StatefulRedisConnection<String, String> connection = client.connect();

// All commands share the single connection efficiently
connection.sync().set("key", "value");

Incorrect: Creating new connections per request.

Python (redis-py):

# Bad: New connection every time
def get_user(user_id):
    r = redis.Redis(host='localhost', port=6379)  # Don't do this
    return r.get(f"user:{user_id}")

Java (Jedis):

// Bad: Creating new client per request
public String getUser(String userId) {
    try (UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379")) {
        return jedis.get("user:" + userId);  // Don't do this
    }
}

Pooling vs Multiplexing:

  • Pooling: Multiple connections shared across requests (redis-py, Jedis, go-redis)
  • Multiplexing: Single connection handles all traffic (NRedisStack, Lettuce)
  • Multiplexing cannot support blocking commands (BLPOP, etc.) as they would stall all callers

Reference: Connection Pools and Multiplexing