Scrivio Interview library
CodingIntermediate7 min read · updated 13 November 2026

Spring Data Redis and Lettuce offer several ways to send many commands efficiently, and some of them affect other code that shares the same connection.

Show how to read 500 hashes in one round trip with RedisTemplate.executePipelined, and how to batch commands by hand with the Lettuce async API. What mistakes do teams make with each?

With RedisTemplate we call executePipelined with a RedisCallback that issues 500 HGETALL commands and returns null; Spring sends them together and hands back a list of 500 deserialized maps in the same order. With Lettuce we take a dedicated connection, turn off auto-flush, queue the async commands, call flushCommands() and wait with LettuceFutures.awaitAll. The common mistakes are reading results inside the loop, turning off auto-flush on a shared connection, sending unbounded batches and assuming pipelining makes heavy commands cheap.

Why this question is asked

Most slow Redis code is not slow because Redis is slow. It is slow because the application waits for one reply before it sends the next command, so 500 reads cost 500 network round trips. Pipelining removes that waiting, and interviewers ask about it because it is easy to use wrongly: the Spring API has a strange-looking contract, and the Lettuce API has a switch that can freeze other threads. In this answer, we will recap what a round trip and a pipeline are, write the RedisTemplate version and the Lettuce version, and then go through the mistakes teams make with each, including the cost of the commands themselves.

1A Quick Recap of Round Trips and Pipelining

Every Redis command is a request and a reply over a TCP connection. If the application and Redis are in the same data centre, one round trip, the time for a request to reach the server and the reply to come back, is often 0.2 to 0.5 ms. Redis itself usually needs a few microseconds to run a simple command, so for small commands almost all the time is spent travelling, not working.

Pipelining means writing many commands onto the connection without waiting for each reply, and then reading all the replies afterwards. Redis processes them in order and answers in order. Notice that a pipeline is not a transaction: other clients' commands can run in between ours, and each command succeeds or fails on its own. It only saves waiting. For 500 reads at 0.3 ms each, that is the difference between about 150 ms and a few milliseconds.

2Reading 500 Hashes With executePipelined

Spring Data Redis gives us executePipelined. We pass it a callback that receives the low-level RedisConnection, and every command we issue on that connection is queued instead of executed immediately.

Java
List<String> keys = productIds.stream().map(id -> "product:" + id).toList(); // 500 keys
List<Object> results = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
for (String k : keys) {
connection.hashCommands().hGetAll(k.getBytes(StandardCharsets.UTF_8)); // returns null here
}
return null; // must be null, or Spring throws
});
results.size(); // 500
Map<Object, Object> first = (Map<Object, Object>) results.get(0); // fields of product:<first id>

There are three rules hidden in this snippet. First, the callback must return null. Spring throws an InvalidDataAccessApiUsageException if it returns anything else, because the real results are only known after the pipeline is closed. Second, the values inside the loop are always null, so we cannot use the result of one command to decide the next one. If we need that, the commands are dependent and pipelining is the wrong tool; a Lua script fits better. Third, when the callback finishes, Spring reads all the replies and deserializes them with the template's serializers, so we get back a List<Object> in exactly the order we issued the commands, with an empty map for keys that do not exist.

Because the result is a plain list, we match it back to our keys by index. That is why we build the key list first and keep it.

3Batching by Hand With the Lettuce Async API

Lettuce, the default client in Spring Boot, is built on Netty and is asynchronous underneath. When several threads send commands on one shared connection at the same time, Lettuce already writes them onto the socket back to back, so they are pipelined on the wire without us doing anything. What we sometimes want is an explicit batch: queue many commands and send them in one write. For that, Lettuce lets us turn off automatic flushing.

Java
try (StatefulRedisConnection<String, String> conn = redisClient.connect()) { // dedicated connection
RedisAsyncCommands<String, String> async = conn.async();
conn.setAutoFlushCommands(false); // commands now stay in the local buffer
List<RedisFuture<Map<String, String>>> futures = new ArrayList<>();
for (String k : keys) {
futures.add(async.hgetall(k)); // queued, nothing sent yet
}
conn.flushCommands(); // all 500 written to the socket at once
boolean done = LettuceFutures.awaitAll(Duration.ofSeconds(2),
futures.toArray(new RedisFuture[0])); // true when all completed in time
Map<String, String> first = futures.get(0).get(); // fields of the first key
}

Notice that we opened a connection just for this batch. The reason is the setting itself: setAutoFlushCommands(false) changes the behaviour of the whole connection, not of our method. awaitAll returns false on timeout, and each future still carries its own success or exception, so we check them one by one.

4Mistakes Teams Make With Each Approach

The worst mistake is calling setAutoFlushCommands(false) on the shared connection that RedisTemplate and every other thread use. Lettuce shares one connection by default in Spring Boot, so from that moment every other thread's command sits in the buffer until someone happens to call flushCommands(). Requests hang, then time out, and the cause is far away from the symptom. Always use a dedicated connection for manual flushing, and turn auto-flush back on or close the connection afterwards.

The second mistake is unbounded batches. A pipeline of 100,000 HGETALL calls makes Redis build all the replies in the client's output buffer, and makes our JVM hold all the futures and maps at once. If the output buffer passes the client-output-buffer-limit, Redis drops the connection. Split work into batches of a few hundred to a few thousand commands and process each batch before sending the next.

The third mistake is ignoring partial failure. In a pipeline each command is independent: one key may hold the wrong type and fail with WRONGTYPE while the other 499 succeed. In executePipelined, an error reply makes Spring throw after the pipeline closes, so we lose the good results unless we catch it; with Lettuce each future fails on its own. Decide whether to retry the failed keys, skip them or fail the request.

The last mistake is believing that pipelining makes big reads cheap. It removes waiting, not work. HGETALL is O(N) in the number of fields, so 500 hashes of 2,000 fields each still make Redis serialize a million field-value pairs on its single main thread, and every other client waits behind that. If we need three fields, HMGET key name price stock returns just those.

Two ways to batch, side by side
AspectexecutePipelinedLettuce manual flush
ConnectionBound to the callback by SpringOne we open and own
ResultsList<Object>, in order, after the callbackOne RedisFuture per command
Inside the loopEvery command returns nullFutures not complete until flush
Main riskExpecting values inside the loopDisabling auto-flush on a shared connection
ErrorsException after the pipeline closesEach future fails on its own

5Follow-up questions

How does Lettuce handle a pipeline whose keys span several cluster nodes?

In cluster mode Lettuce computes the hash slot of each key and sends each command on the connection to the node that owns that slot, so one logical batch becomes several smaller pipelines, one per node, running in parallel. With auto-flush off on a cluster connection, flushCommands() flushes all the node connections. The replies come back per node, but each future still completes with its own command's result, so our ordering by index is preserved. Multi-key commands such as MGET must have all their keys in one slot, which is why we use hash tags like {user42} when keys must stay together. Spring's pipelining support on cluster connections differs between drivers, so check your version before relying on it.

When should I use MGET instead of a pipeline?

When all the reads are plain string GETs, MGET is one command with one reply, which is slightly cheaper for Redis than many GETs. A pipeline is more general: it can mix HGETALL, ZSCORE and anything else. In a cluster, MGET needs all keys in one slot, while a pipeline of GETs does not.

Is a pipeline atomic?

No. Other clients' commands can be interleaved with ours, and a failed command does not undo the others. If we need all-or-nothing execution we use MULTI and EXEC, or a Lua script or function, which runs as one unit on the server.

6Conclusion

In this answer, we saw that pipelining saves round trips by sending many commands before reading the replies. RedisTemplate.executePipelined takes a callback that must return null and gives back the deserialized results in order once it finishes. Lettuce already pipelines concurrent commands, and for explicit batches we use a dedicated connection with auto-flush off, flushCommands() and LettuceFutures.awaitAll. The traps are disabling auto-flush on a shared connection, unbounded batches, ignoring per-command failures and expecting pipelining to make O(N) commands cheap.

What to say in the interviewAbout 80 seconds aloud

Open with

For 500 hashes I would use redisTemplate.executePipelined with a RedisCallback. Inside the callback I loop over the keys and call connection.hashCommands().hGetAll for each one, and I return null, because Spring requires that and fills in the real results afterwards.

Then, if they want more

The method returns a list of 500 deserialized maps in the order I issued the commands, so I match them back to my keys by index. Inside the loop every call returns null, so I cannot make one command depend on another; for that I would use a Lua script.

With Lettuce directly, concurrent commands on one connection are already pipelined, but for an explicit batch I open a dedicated connection, call setAutoFlushCommands(false), issue the async commands, call flushCommands, and wait with LettuceFutures.awaitAll with a timeout.

The mistakes I watch for are turning off auto-flush on the shared connection, which leaves every other thread's commands unsent, sending huge batches that blow up the output buffer and the heap, and treating the pipeline as atomic when each command can fail on its own.

And pipelining only removes waiting: HGETALL on big hashes is still O(N), so if I only need a few fields I use HMGET.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Redis documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to read 500 hashes in one round trip with RedisTemplate.executePipelined, and...": https://scrivio-interview-library.netlify.app/databases/redis-internals/d25b6d2954/