Databases 11 min read

Best Practices and Guidelines for Using Alibaba Cloud Redis

This article presents comprehensive Alibaba Cloud Redis development guidelines covering key‑value design, value handling, command usage, client configuration, lifecycle management, related tools, and code examples to help developers avoid common pitfalls and improve performance.

Big Data Technology & Architecture
Big Data Technology & Architecture
Big Data Technology & Architecture
Best Practices and Guidelines for Using Alibaba Cloud Redis

This article introduces Alibaba Cloud Redis development specifications, explaining key design, command usage, client usage, and related tools to reduce problems when using Redis.

1. Key Design

Key naming

Use readable, manageable prefixes such as ugc:video:1 and keep keys concise, e.g., user:{uid}:friends:messages:{mid} shortened to u:{uid}:fr:m:{mid}. Avoid special characters, spaces, line breaks, or quotes.

Value design

Prevent big keys: keep strings under 10 KB, and limit hash, list, set, zset elements to 5000. Use appropriate data types and avoid large structures; for example, replace multiple SET commands with a single HMSET as shown: hmset user:1 name tom age 19 favor football Control key lifecycle by setting expiration with EXPIRE and dispersing TTLs to avoid concentrated expirations.

2. Command Usage

Prefer O(N) commands that are aware of the size N, such as HGETALL, LRANGE, SMEMBERS, and replace full scans with HSCAN, SSCAN, or ZSCAN.

Disable risky commands like KEYS, FLUSHALL, FLUSHDB via Redis rename or use incremental processing with SCAN.

Avoid using multiple logical databases; they add overhead and are weakly supported.

Batch operations improve efficiency; use native MGET / MSET or pipeline for non‑atomic batches, keeping batch size under about 500 elements.

Redis transactions are limited (no rollback) and in cluster mode all keys in a transaction must share a slot.

When using Lua scripts on a cluster, ensure all keys are passed via the KEYS array and reside in the same slot.

Use MONITOR sparingly and only for short periods.

3. Client Usage

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

Employ connection pools (e.g., Jedis) to control connections and improve performance. 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();
}

Consider circuit‑breaker patterns (e.g., Netflix Hystrix) for high concurrency.

Set strong passwords and enable SSL if needed.

Choose an appropriate maxmemory-policy (default volatile‑lru) and configure expiration times to prevent OOM.

4. Related Tools

Data synchronization can be done with redis‑port. For big‑key detection, use the provided Python script (threshold 10240 bytes) which scans keys with low impact; run during low‑traffic periods.

import sys
import redis

def check_big_key(r, k):
    bigKey = False
    length = 0
    try:
        type = r.type(k)
        if type == "string":
            length = r.strlen(k)
        elif type == "hash":
            length = r.hlen(k)
        elif type == "list":
            length = r.llen(k)
        elif type == "set":
            length = r.scard(k)
        elif type == "zset":
            length = r.zcard(k)
    except:
        return
    if length > 10240:
        bigKey = True
    if bigKey:
        print db, k, type, length
# ... (rest of script omitted for brevity)

Hot key detection can be performed with tools like redis‑faina using MONITOR for short durations.

5. Appendices

Examples for deleting large hashes, lists, and sets using HSCAN / HDEL, LTRIM, and SSCAN / SREM respectively are provided in Java code snippets.

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);
}
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.

redisAlibaba CloudKey DesignCommand UsageClient Best PracticesBigKey Detection
Big Data Technology & Architecture
Written by

Big Data Technology & Architecture

Wang Zhiwu, a big data expert, dedicated to sharing big data technology.

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.