Redis Usage Best Practices and Guidelines
This article presents comprehensive Redis usage standards—including key naming conventions, avoiding big keys, efficient serialization, safe command usage, data persistence strategies, and operational recommendations—to ensure high performance, memory efficiency, and reliable service under heavy traffic.
After a traffic surge caused Redis connection errors ("Could not get a resource from the pool") during a promotional event, the author shares a set of Redis usage standards to avoid similar incidents.
Key‑Value Usage Guidelines
Key naming : Use a business‑module prefix followed by a colon and the specific entity, e.g., set business:table:id 100000 . This improves readability and aids troubleshooting. Keep keys concise because Redis stores them as SDS strings, where longer keys consume more metadata memory.
Avoid big keys : Large values block Redis’s single‑threaded processing. Limit string values to 10KB and collection elements to 5000 . For larger data, compress with gzip or split collections into smaller ones. Example compression utilities are provided:
/**
* 使用gzip压缩字符串
*/
public static String compress(String str) {
if (str == null || str.length() == 0) {
return str;
}
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out)) {
gzip.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
/**
* 使用gzip解压缩
*/
public static String uncompress(String compressedStr) {
if (compressedStr == null || compressedStr.length() == 0) {
return compressedStr;
}
byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
String decompressed = null;
try (ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(compressed);
GZIPInputStream ginzip = new GZIPInputStream(in)) {
byte[] buffer = new byte[1024];
int offset;
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
decompressed = out.toString();
} catch (IOException e) {
e.printStackTrace();
}
return decompressed;
}Redis maintains an integer object pool (0‑9999) to save memory, but it is disabled when LRU eviction policies are used or when collections are encoded as ziplist with integer elements.
Command Usage Guidelines
Avoid commands that can block the main thread:
KEYS – performs a full scan; use SCAN instead.
FLUSHALL and FLUSHDB – delete all data and can block; use the ASYNC option or rename them via rename‑command .
MONITOR – continuously writes monitored traffic to the output buffer and may overflow it.
Full‑collection commands such as HGETALL , LRANGE , SMEMBERS , ZRANGE – cause full scans; prefer SSCAN , HSCAN or split large collections.
Data Persistence Guidelines
Separate hot and cold data: keep only frequently accessed (hot) data in Redis as a cache, and persist less‑used data elsewhere.
Set appropriate expiration times to prevent memory bloat and avoid cache avalanche caused by massive simultaneous expirations.
Limit a single Redis instance’s memory to 2‑6 GB to ensure fast RDB snapshots and replication.
Operational Guidelines
Deploy Redis in a Cluster or Sentinel setup for high availability.
Configure a reasonable maximum number of client connections.
Disable AOF or set it to write every second to reduce disk I/O.
Adjust repl‑backlog to lower full‑sync probability.
Set appropriate slave‑client‑output‑buffer‑limit to avoid replication stalls.
Choose suitable memory eviction policies based on workload.
Always use a connection pool when accessing Redis.
Additional Resources
Recommended reading includes articles on distributed locks with Redis/Redisson, high‑frequency Java interview questions, and a MySQL bug that many developers encounter.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.