Databases 12 min read

Best Practices and Development Guidelines for Using Alibaba Cloud Redis

This article outlines comprehensive development guidelines for Alibaba Cloud Redis, covering key naming conventions, value design, command best practices, client usage patterns, related tools, and detailed code examples for safely deleting large keys across various data structures.

Top Architect
Top Architect
Top Architect
Best Practices and Development Guidelines for Using Alibaba Cloud Redis

Introduction

The article presents development specifications for Alibaba Cloud Redis, aiming to reduce issues during Redis usage.

1. Key Design

Key Naming

Use business or database name as a prefix, separated by colons (e.g., business:table:id ) to avoid collisions.

Readability and Manageability

Keys should be readable and manageable, with concise length to limit memory consumption.

Simplicity

Keep keys short while preserving semantics, e.g., user:{uid}:friends:messages:{mid} can be simplified to u:{uid}:fr:m:{mid} .

Avoid Special Characters

Do not include spaces, line breaks, quotes, or other escape characters in keys.

2. Value Design

Avoid Big Keys

Limit string values to 10KB, and keep hash, list, set, and sorted set element counts under 5,000 to prevent network congestion and slow queries.

Select Appropriate Data Types

Choose data structures that balance memory encoding and performance, such as using ziplist for small hashes.

Control Key Lifecycle

Set expiration times with EXPIRE and stagger expirations to avoid spikes; monitor idle time for non‑expiring keys.

Memory Eviction Policies

Configure maxmemory-policy according to business needs (e.g., volatile-lru , allkeys-lru , noeviction , etc.).

3. Command Usage

O(N) Commands

Commands like HGETALL , LRANGE , SMEMBERS , ZRANGE should be used with awareness of the underlying N; prefer HSCAN , SSCAN , ZSCAN for large collections.

Disable Dangerous Commands

Prohibit KEYS , FLUSHALL , FLUSHDB in production; use Redis rename mechanism or SCAN for safe iteration.

Selective DB Usage

Avoid excessive use of SELECT as multiple databases share the same single‑threaded engine and can cause interference.

Batch Operations

Use native batch commands like MGET , MSET or pipelines for higher throughput, limiting batch size (e.g., ≤500 elements) based on element byte size.

Transactions

Redis transactions are weak (no rollback) and require all keys in a slot for cluster mode; use hashtags if needed.

Lua Scripts in Cluster

All keys must be passed via the KEYS array, and they must reside in the same slot; otherwise an error is returned.

MONITOR Command

Use MONITOR sparingly and avoid long‑running sessions.

4. Client Usage

Separate Instances

Do not share a single Redis instance across unrelated applications; isolate business data via services.

Connection Pooling

Employ connection pools (e.g., JedisPool) to control connections and improve efficiency. Example Java code:

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

Circuit Breaker

Integrate circuit‑breaker libraries (e.g., Netflix Hystrix) for high‑concurrency scenarios.

Encryption

Set strong passwords and enable SSL/TLS if required (supported by Alibaba Cloud Redis).

5. Related Tools

Data synchronization can be performed with redis‑port . Big‑key search tools and hot‑key detection utilities (e.g., redis‑faina ) are recommended.

6. Deleting Big Keys

Use incremental scan‑and‑delete patterns to avoid blocking the server.

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
> scanResult = jedis.hscan(bigHashKey, cursor, scanParams);
        List
> entryList = scanResult.getResult();
        if (entryList != null && !entryList.isEmpty()) {
            for (Entry
entry : entryList) {
                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 counter = 0;
    int left = 100;
    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
scanResult = jedis.sscan(bigSetKey, cursor, scanParams);
        List
memberList = scanResult.getResult();
        if (memberList != null && !memberList.isEmpty()) {
            for (String member : memberList) {
                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
scanResult = jedis.zscan(bigZsetKey, cursor, scanParams);
        List
tupleList = scanResult.getResult();
        if (tupleList != null && !tupleList.isEmpty()) {
            for (Tuple tuple : tupleList) {
                jedis.zrem(bigZsetKey, tuple.getElement());
            }
        }
        cursor = scanResult.getStringCursor();
    } while (!"0".equals(cursor));
    jedis.del(bigZsetKey);
}

Conclusion

Following these guidelines helps maintain Redis performance, stability, and scalability in production environments.

JavaperformanceCachedatabaseRedisAlibaba CloudKey Design
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login 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.