Databases 18 min read

Boost Redis Performance: 13 Proven Optimization Techniques

Learn how to dramatically improve Redis performance by shortening key-value sizes, enabling lazy free, setting expirations, disabling costly commands, using slowlog, leveraging pipeline, preventing mass expirations, optimizing client connections, limiting memory, running on physical servers, configuring persistence, disabling THP, and adopting distributed architectures.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Boost Redis Performance: 13 Proven Optimization Techniques

1. Shorten key-value length

The size of a key‑value pair is inversely proportional to performance; larger values slow writes because Redis chooses more complex internal encodings (int, raw, embstr). Bigger values also increase persistence time, network transfer, and memory pressure, triggering more frequent eviction.

Longer persistence time reduces overall throughput.

More data to transfer over the network slows operations.

Higher memory usage leads to frequent eviction cycles.

Therefore, keep stored data as compact as possible. When necessary, serialize and compress values (e.g., using Protostuff, Kryo, or Snappy in Java).

2. Use lazy free

Lazy free, introduced in Redis 4.0, performs asynchronous deletion in a background I/O thread, preventing the main thread from blocking on large‑key deletions.

lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
slave-lazy-flush no

lazyfree-lazy-eviction : Enables lazy deletion when memory exceeds maxmemory.

lazyfree-lazy-expire : Enables lazy deletion for keys that expire.

lazyfree-lazy-server-del : Enables lazy deletion for implicit DEL operations (e.g., RENAME on a big key).

slave-lazy-flush : Enables lazy deletion during full‑sync flush on replicas.

It is recommended to enable lazyfree-lazy-eviction, lazyfree-lazy-expire and lazyfree-lazy-server-del to reduce main‑thread blocking.

3. Set key expiration

Configure appropriate TTLs based on business needs so Redis can automatically reclaim memory and avoid excessive eviction pressure.

4. Disable long‑running query commands

Most Redis commands have O(1)–O(N) complexity. Commands with O(N) can block the single thread, especially on large datasets. The official command‑complexity chart (see image) highlights which commands to avoid.

Redis command complexity chart
Redis command complexity chart

Prohibit the KEYS command.

Use SCAN for incremental iteration instead of full scans.

Control the size of HASH, SET, ZSET structures.

Perform sorting, union, and intersection on the client side.

Use asynchronous UNLINK instead of blocking DEL for large keys.

5. Optimize with slowlog

Enable slowlog to identify and tune the most time‑consuming commands. slowlog-log-slower-than: Threshold (in microseconds) for logging a command as slow. slowlog-max-len: Maximum number of entries kept in the log.

Retrieve entries with slowlog get N and optimize the corresponding business logic.

6. Use Pipeline for batch operations

Pipeline batches multiple commands, reducing round‑trip latency.

public class PipelineExample {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        long beginTime = System.currentTimeMillis();
        Pipeline pipe = jedis.pipelined();
        for (int i = 0; i < 100; i++) {
            pipe.set("key" + i, "val" + i);
            pipe.del("key" + i);
        }
        pipe.sync();
        long endTime = System.currentTimeMillis();
        System.out.println("执行耗时:" + (endTime - beginTime) + "毫秒");
    }
}
执行耗时:297毫秒

Non‑pipeline version:

public class PipelineExample {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        long beginTime = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            jedis.set("key" + i, "val" + i);
            jedis.del("key" + i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("执行耗时:" + (endTime - beginTime) + "毫秒");
    }
}
执行耗时:17276毫秒

Pipeline reduces execution time by roughly 58×.

7. Avoid massive simultaneous expiration

Redis performs ten expiration scans per second (default hz 10). When many keys expire together, repeated scans cause noticeable latency and CPU pressure.

Redis expiration scan illustration
Redis expiration scan illustration

Mitigate by adding a random offset to each key’s TTL, spreading expirations over time.

8. Optimize client usage

Besides pipeline, use a connection pool to avoid frequent creation/destruction of connections, reducing network overhead and unnecessary command calls.

9. Limit Redis memory size

Set maxmemory <bytes> to a fixed value; when reached, Redis triggers an eviction policy. Available policies (Redis 4.0+):

noeviction : No eviction; writes fail when memory is exhausted.

allkeys-lru : Evict least‑recently‑used keys among all keys.

allkeys-random : Random eviction among all keys.

volatile-lru : Evict LRU among keys with an expiration.

volatile-random : Random eviction among expiring keys.

volatile-ttl : Evict keys with the nearest expiration time.

volatile-lfu : Evict least‑frequently‑used expiring keys.

allkeys-lfu : Evict least‑frequently‑used keys among all keys.

Choose a policy that matches the application’s tolerance for data loss.

10. Deploy on physical machines

Virtualized environments share network interfaces and memory, causing higher latency. Use ./redis-cli --intrinsic-latency 100 to measure latency and prefer bare‑metal deployment for latency‑sensitive workloads.

11. Check persistence strategy

Redis offers three persistence modes:

RDB : Snapshot of memory at a point in time.

AOF : Append‑only log of every write command.

Hybrid (RDB+AOF) : Writes an RDB snapshot header followed by incremental AOF entries, combining fast restart with reduced data loss.

Hybrid persistence is recommended for most production scenarios.

config get aof-use-rdb-preamble
Hybrid persistence config result
Hybrid persistence config result

Enable it either at runtime: config set aof-use-rdb-preamble yes or permanently by editing redis.conf and setting aof-use-rdb-preamble yes, then restarting Redis.

12. Disable Transparent Huge Pages (THP)

THP (2 MiB pages) slows fork and write operations. Disable it with:

echo never > /sys/kernel/mm/transparent_hugepage/enabled

Persist the setting by adding the same command to /etc/rc.local so it survives reboots.

13. Use distributed architecture to increase read/write throughput

Three main approaches:

Master‑slave replication – writes go to the master, reads can be served by slaves.

Sentinel – adds automatic failover to master‑slave setups.

Redis Cluster – shards data across multiple nodes using hash slots (0‑16383), balancing load and providing built‑in fault tolerance.

For most scenarios, Redis Cluster is the preferred solution because it distributes load and offers automatic resilience.

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.

Performance OptimizationMemory ManagementRedisPersistencePipelineDatabase TuningLazy Free
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

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.