Databases 11 min read

Master Redis Key Design and Operations: Best Practices & Code Samples

This guide presents comprehensive Redis best practices covering key naming, value design, command selection, client configuration, memory‑efficient data structures, and practical Java code for safely deleting large keys, helping developers build high‑performance, reliable Redis deployments.

ITFLY8 Architecture Home
ITFLY8 Architecture Home
ITFLY8 Architecture Home
Master Redis Key Design and Operations: Best Practices & Code Samples

1. Key Design

Key naming

Use readable, manageable prefixes such as business:table:id to avoid collisions.

Keep keys concise; long keys increase memory usage. Example: user:{uid}:friends:messages:{mid} can be shortened to u:{uid}:fr:m:{mid}.

Avoid special characters, spaces, line breaks, or quotes.

Value design

Reject big keys to prevent network congestion and slow queries; keep strings under 10KB and limit collection sizes (e.g., hash, list, set, zset) to fewer than 5,000 elements.

Choose appropriate data types and consider memory‑optimized encodings (e.g., ziplist) while balancing performance.

Control key lifecycle with EXPIRE; stagger expirations to avoid spikes, and monitor idle time for non‑expiring keys.

2. Command Usage

Prefer O(N) commands only when the element count (N) is known; use HSCAN, SSCAN, ZSCAN for large scans.

Disable risky commands such as KEYS, FLUSHALL, FLUSHDB via Redis rename or progressive scanning.

Use SELECT sparingly; multiple databases share a single thread and many clients have limited support.

Batch operations improve efficiency: native commands like MGET / MSET or pipelines for non‑atomic bulk actions (keep batch size ≤ 500 items, adjust for payload size).

Redis transactions are limited (no rollback) and require all keys in a transaction to reside in the same slot; use hashtags if needed.

When using Lua scripts in cluster mode, pass all keys via the KEYS array and ensure they belong to the same slot.

Use MONITOR cautiously; avoid long‑running sessions.

3. Client Usage

Avoid sharing a single Redis instance across unrelated applications; isolate business domains.

Employ connection pools (e.g., JedisPool) to manage connections efficiently. Example Java usage:

Jedis jedis = null;
try {
    jedis = jedisPool.getResource();
    // execute commands
    jedis.executeCommand();
} catch (Exception e) {
    logger.error("op key {} error: " + e.getMessage(), key, e);
} finally {
    if (jedis != null) jedis.close(); // returns to pool
}

Consider circuit‑breaker patterns (e.g., Netflix Hystrix) under high concurrency. Secure access with strong passwords and SSL when supported. Configure an appropriate maxmemory-policy (default volatile-lru ) and understand alternatives such as allkeys-lru , allkeys-random , volatile-random , volatile-ttl , and noeviction .

4. Related Tools

Data synchronization between Redis instances (e.g., redis-port).

Big‑key detection tools.

Hot‑key discovery (e.g., Facebook's redis-faina); Alibaba Cloud Redis already mitigates hot‑key issues at the kernel level.

5. Appendix: Deleting Big Keys

Use pipelines for faster deletion. Redis 4.0 supports asynchronous key deletion.

Hash deletion (hscan + hdel)

public void delBigHash(String host, int port, String password, String bigHashKey) {
    Jedis jedis = new Jedis(host, port);
    if (password != null && !"".equals(password)) {
        jedis.auth(password);
    }
    ScanParams scanParams = new ScanParams().count(100);
    String cursor = "0";
    do {
        ScanResult<Entry<String, String>> scanResult = jedis.hscan(bigHashKey, cursor, scanParams);
        for (Entry<String, String> entry : scanResult.getResult()) {
            jedis.hdel(bigHashKey, entry.getKey());
        }
        cursor = scanResult.getStringCursor();
    } while (!"0".equals(cursor));
    jedis.del(bigHashKey);
}

List deletion (ltrim)

public void delBigList(String host, int port, String password, String bigListKey) {
    Jedis jedis = new Jedis(host, port);
    if (password != null && !"".equals(password)) {
        jedis.auth(password);
    }
    long llen = jedis.llen(bigListKey);
    int left = 100;
    int counter = 0;
    while (counter < llen) {
        jedis.ltrim(bigListKey, left, llen);
        counter += left;
    }
    jedis.del(bigListKey);
}

Set deletion (sscan + srem)

public void delBigSet(String host, int port, String password, String bigSetKey) {
    Jedis jedis = new Jedis(host, port);
    if (password != null && !"".equals(password)) {
        jedis.auth(password);
    }
    ScanParams scanParams = new ScanParams().count(100);
    String cursor = "0";
    do {
        ScanResult<String> scanResult = jedis.sscan(bigSetKey, cursor, scanParams);
        for (String member : scanResult.getResult()) {
            jedis.srem(bigSetKey, member);
        }
        cursor = scanResult.getStringCursor();
    } while (!"0".equals(cursor));
    jedis.del(bigSetKey);
}

SortedSet deletion (zscan + zrem)

public void delBigZset(String host, int port, String password, String bigZsetKey) {
    Jedis jedis = new Jedis(host, port);
    if (password != null && !"".equals(password)) {
        jedis.auth(password);
    }
    ScanParams scanParams = new ScanParams().count(100);
    String cursor = "0";
    do {
        ScanResult<Tuple> scanResult = jedis.zscan(bigZsetKey, cursor, scanParams);
        for (Tuple tuple : scanResult.getResult()) {
            jedis.zrem(bigZsetKey, tuple.getElement());
        }
        cursor = scanResult.getStringCursor();
    } while (!"0".equals(cursor));
    jedis.del(bigZsetKey);
}

Source: https://yq.aliyun.com/articles/531067

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

databaseredisKey Design
ITFLY8 Architecture Home
Written by

ITFLY8 Architecture Home

ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.