TExcelTAD
Home › Redis › Redis Pipelining

Redis Pipelining

Redis executes a command in microseconds, yet an application that sends one command at a time often manages only a few thousand commands per second. The bottleneck is not Redis: it is the round-trip time (RTT), the time a request needs to travel to the server and the reply to come back. Pipelining removes most of that waiting by sending many commands without waiting for each reply.

The problem: request, wait, repeat

Without pipelining, a client works like a phone call where you hang up after every sentence:

text
client: SET a 1     ──────────►  server
client:             ◄──────────  OK          (1 round trip)
client: SET b 2     ──────────►
client:             ◄──────────  OK          (2 round trips)
client: SET c 3     ──────────►
client:             ◄──────────  OK          (3 round trips)

With pipelining, the client writes all three commands into the socket at once and then reads the three replies:

text
client: SET a 1 / SET b 2 / SET c 3  ──────────►  server
client:                              ◄──────────  OK / OK / OK   (1 round trip)

The server still executes the commands one by one, in order. Only the waiting is shared.

How much does it help?

Let's put numbers on it. The model below assumes a network round trip of 0.5 ms (typical inside one data centre; across regions it can be 50 ms or more) and a server cost of 0.002 ms per command:

python · try it yourself
RTT_MS = 0.5          # network round trip
SERVER_MS = 0.002     # time Redis needs per simple command

def total_ms(commands, batch_size):
    batches = -(-commands // batch_size)          # ceiling division
    return batches * RTT_MS + commands * SERVER_MS

commands = 10_000
print(f"{'batch size':>10} {'round trips':>12} {'total ms':>10} {'cmds/sec':>10}")
for batch in (1, 10, 100, 1000):
    ms = total_ms(commands, batch)
    trips = -(-commands // batch)
    print(f"{batch:>10} {trips:>12} {ms:>10.1f} {commands / ms * 1000:>10.0f}")
batch size  round trips   total ms   cmds/sec
         1        10000     5020.0       1992
        10         1000      520.0      19231
       100          100       70.0     142857
      1000           10       25.0     400000

Going from one command per round trip to batches of 100 makes the same work about 70 times faster. Beyond a point the gain flattens, because the server time and the size of the batch start to dominate. Batches of a few hundred to a few thousand commands are a common sweet spot.

Note: Real numbers also include system-call overhead on both sides: reading and writing a socket costs CPU, and pipelining reduces the number of these calls too.

Pipelining in client libraries

Every major client supports pipelines. In redis-py, commands on a pipeline object are buffered and sent on execute(), which returns all replies in order:

python
import redis

r = redis.Redis(decode_responses=True)

pipe = r.pipeline(transaction=False)   # plain pipeline, no MULTI/EXEC
for user_id in range(1, 1001):
    pipe.hset(f"user:{user_id}", mapping={"plan": "free", "credits": 10})
results = pipe.execute()               # one network flush, 1000 replies
print(len(results))                    # 1000

In Node.js, node-redis pipelines automatically: commands issued in the same tick are sent together. You can also make it explicit:

js
import { createClient } from 'redis';

const client = await createClient().connect();
const replies = await client.multi()     // .multi() = transaction; .execAsPipeline() = plain pipeline
  .set('a', '1')
  .incr('visits')
  .get('a')
  .execAsPipeline();
console.log(replies);                    // [ 'OK', 1, '1' ]

Pipeline versus transaction

They are often confused because client libraries use the same pipeline() object for both.

Pipeline Transaction (MULTI/EXEC)
Purpose save round trips make commands run without interleaving
Other clients' commands in between possible impossible
Replies as they are produced all together at EXEC
Combine both? yes: a transaction sent in one pipeline is common (redis-py's default pipeline())

The limits of a pipeline

A pipeline sends commands blindly: you cannot use the reply of the first command to build the second, because no reply has arrived yet. If the second step depends on the first, use a Lua script (one round trip, logic on the server) or two separate round trips.

The model below contrasts the three approaches for "read a counter, then write it doubled into another key" under the same 0.5 ms RTT:

python · try it yourself
RTT_MS = 0.5
approaches = [
    ("GET, then SET (2 round trips)", 2),
    ("pipeline (cannot use the GET reply)", 1),
    ("Lua script (logic runs on server)", 1),
]
for name, trips in approaches:
    print(f"{name:<40} {trips * RTT_MS:.1f} ms")
GET, then SET (2 round trips)            1.0 ms
pipeline (cannot use the GET reply)      0.5 ms
Lua script (logic runs on server)        0.5 ms

The pipeline is fast but cannot express the dependency; the script is both fast and correct.

Bulk loading with redis-cli --pipe

For loading millions of keys, redis-cli --pipe streams a file of commands (or raw RESP) to the server as fast as possible and reports the result at the end:

bash
# commands.txt contains lines like: SET product:1 "Mug"
cat commands.txt | redis-cli --pipe
# All data transferred. Waiting for the last reply...
# Last reply received from server.
# errors: 0, replies: 1000000

Tips

  • Do not build a single pipeline with millions of commands in memory: send them in chunks of, say, 1,000.
  • A pipeline is not atomic. If you need "all or nothing visible", wrap it in MULTI/EXEC or use a script.
  • In Redis Cluster, a pipeline can only be sent to one node at a time; cluster-aware clients split it by hash slot for you.

Test yourself

What does pipelining reduce?

  1. The CPU time of each command on the server
  2. The number of network round trips
  3. The memory used by keys
  4. The number of commands executed

Is a plain pipeline atomic?

  1. Yes, always
  2. No: other clients' commands may run between the pipelined commands
  3. Only for writes
  4. Only in Redis Cluster

The second command needs the result of the first. Which approach does it in one round trip?

  1. A pipeline
  2. A Lua script
  3. Two pipelines
  4. PUBLISH