Databases 11 min read

Best Practices for Using Alibaba Cloud Redis: Key Design, Commands, and Client Tips

This guide outlines comprehensive best‑practice recommendations for Alibaba Cloud Redis, covering readable key naming, value size limits, safe command usage, client connection pooling, encryption, eviction policies, and efficient big‑key deletion techniques to improve performance and reliability.

21CTO
21CTO
21CTO
Best Practices for Using Alibaba Cloud Redis: Key Design, Commands, and Client Tips

1. Key Design

Key naming : Use a readable, manageable format with a business or database prefix to avoid collisions, separated by colons, e.g., business:table:id. Keep keys short to reduce memory usage, for example ugc:video:1 or a shortened form u:{uid}:fr:m:{mid}. Avoid special characters, spaces, line breaks, quotes, or escape sequences.

Value design : Reject big keys. Limit string values to 10 KB, and keep the number of elements in hash, list, set, or sorted set under 5 000. Use appropriate data types and memory‑optimized encodings (e.g., ziplist) while balancing performance.

2. Command Usage

O(N) commands : Be aware of the size N when using commands like HGETALL, LRANGE, SMEMBERS, ZRANGE, SINTER. Prefer HSCAN, SSCAN, ZSCAN for incremental scans.

Disabled commands : Prohibit KEYS, FLUSHALL, FLUSHDB in production. Use RENAME to block them or employ SCAN for gradual processing.

Select usage : Redis multiple databases are weakly supported and can cause interference; avoid relying on them.

Batch operations : Use native batch commands (e.g., MGET, MSET) or pipelines for higher throughput, limiting batch size to around 500 elements or based on byte size. Pipelines are non‑atomic, can combine different commands, and require client and server support.

Transactions : Redis transactions are limited (no rollback) and in cluster mode all keys in a transaction must reside in the same slot; use hashtags to satisfy this.

Lua scripts in cluster : All keys must be passed via the KEYS array, and they must belong to the same slot; otherwise an error is returned.

MONITOR command : Use sparingly and avoid long‑running sessions.

3. Client Usage

Instance isolation : Do not share a single Redis instance among unrelated applications; separate business data into distinct services.

Connection pooling : Employ a connection pool to control connections and improve efficiency. Example (Jedis):

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

Circuit breaker : Add a circuit‑breaker (e.g., Netflix Hystrix) under high concurrency.

Encryption : Set a strong password and enable SSL if needed (supported by Alibaba Cloud Redis).

Eviction policy : Choose an appropriate maxmemory-policy based on business needs and set expiration times. Default volatile‑lru evicts LRU keys among those with TTL, which may still cause OOM for non‑expiring data. Other policies include allkeys‑lru, allkeys‑random, volatile‑random, volatile‑ttl, and noeviction.

4. Related Tools

Data synchronization: redis‑port Big‑key search tools for Redis

Hot‑key detection (e.g., facebook/redis‑faina; Alibaba Cloud Redis mitigates hot‑key issues at the kernel level)

5. Deleting Big Keys

Use pipelines to accelerate 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);
}

Sorted Set 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: Alibaba Cloud Database – https://developer.aliyun.com/article/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.

RedisAlibaba CloudKey DesignCommand UsageBigKey ManagementClient Best Practices
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

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.