Video in progress

Strong Junior ⚡ Redis and caching

What is Redis pipelining, and when does it give a noticeable speedup?

Pipelining means sending several commands back to back without waiting for each reply, then reading the replies together. It removes the network round trip per command, especially when you send thousands of small commands.

📖 Answer

Redis itself runs a command in microseconds; most of the time goes to the network. If the application and Redis are 0.5 ms apart, 10,000 SET commands in sequence take at least 5 seconds. With a pipeline, a few tens of milliseconds.

List<Object> results = redis.executePipelined((RedisCallback<Object>) conn -> {
    for (var p : products) {
        conn.stringCommands().set(
            ("product:" + p.id()).getBytes(), toJson(p).getBytes());
    }
    return null;   // the results come back from executePipelined
});

Things to know:

  • a pipeline is not atomic: other clients' commands can land between yours;
  • inside it you can't make a decision based on the reply to an earlier command;
  • split a very large pipeline into chunks (say, 1000 commands each), otherwise Redis accumulates the replies in memory.

To read several keys, there are also MGET/MSET before reaching for a pipeline, and each is a single command.