Batching and pipelining
Many small calls waste time on fixed costs. Learn how batching and pipelining share those costs, and how much waiting time you pay for it.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
This story is made up, but the shape is common. A team runs a nightly job that copies 2,000,000 product prices into Redis. The job runs in one zone and Redis runs in another.
The code is a simple loop: send one SET, wait for the reply, send the next. Each round trip between the zones takes about 0.5 ms.
The job takes 2,000,000 × 0.5 ms = 1,000 seconds, about 17 minutes. Redis is almost idle. The job spends nearly all its time waiting for the network.
An engineer switches to pipelining. She sends all 2,000,000 commands first, then reads the replies. The job is fast now, but Redis memory jumps, because Redis must hold every reply until the client reads it. 1 The final fix sends 10,000 commands at a time, reads those replies, and repeats.
The idea in simple words
Many operations have a fixed cost that does not depend on how much data they carry. The fixed part of a network round trip, a system call, a disk flush or a packet header is the same for 1 item or for 100.
Batching means grouping many items into one operation, so they share that fixed cost. Pipelining means sending the next request before the reply to the last one arrives, so the round trips overlap.
Both raise throughput: more items per second. Both have a price. With batching, an item may wait for more items to arrive and fill its batch. With pipelining, both sides buffer more data, and one slow item can hold up the rest.
The key idea. Batching and pipelining spread a fixed cost over many items. You gain throughput and pay with waiting time and memory. Always put a limit on both the size of a batch and how long an item may wait.
How it works
The arithmetic of batching
Say each call to a service costs 1 ms of fixed overhead, plus 0.01 ms per item. You have 1,000 items.
- One at a time: 1,000 × (1 + 0.01) = 1,010 ms. That is about 990 items a second.
- Batches of 100: 10 × (1 + 100 × 0.01) = 10 × 2 = 20 ms. That is 50,000 items a second.
The work per item did not change. You paid the fixed cost 10 times, not 1,000 times.
Now look at the wait. Items arrive at 2,000 a second. A batch of 100 takes 100 / 2,000 = 0.05 s to fill. So the first item in each batch waits about 50 ms before anything is sent.
In tail latency and queueing, you saw that a busy server builds long queues. Batching adds waiting time to each item. But it also raises capacity, so the server is less busy and its queue is shorter. Here, sending one at a time handles only about 990 items a second. At 2,000 arriving a second, its queue would grow without end.
Two knobs: size and time
Every batcher needs two limits. A size limit sends the batch when it is full. A time limit sends it when the oldest item has waited long enough.
Kafka's producer shows both. It groups records for the same partition into batches. batch.size sets the batch size in bytes, with a default of 16384. 2 linger.ms is how long the producer waits for more records. It sends when the batch is full or the linger time ends, "whichever happens first". 2
The default for linger.ms changed from 0 to 5 in Kafka 4.0. The docs say "the efficiency gains from larger batches typically result in similar or lower producer latency despite the increased linger." 2 But the docs also warn that a value of 50 "would add up to 50ms of latency to records sent in the absence of load". 2
In the example above, a 5 ms time limit at 2,000 items a second gives batches of about 2,000 × 0.005 = 10 items. Each batch costs 1 + 10 × 0.01 = 1.1 ms, or 0.11 ms per item. That is about 9 times better than one at a time. At normal load, an item lingers at most about 5 ms. Kafka warns that broker backpressure can make the real wait longer. 2
Group commit in databases
A durable commit must reach the disk with fsync. That flush is a large fixed cost. If several transactions commit at the same moment, one flush can cover all of them. This is group commit.
With made-up numbers: one flush takes 2 ms. One commit per flush allows at most 1,000 / 2 = 500 commits a second. If 8 commits share each flush, the same disk allows up to 4,000.
PostgreSQL already groups sessions that need to flush while the previous flush runs. 3 The setting commit_delay (in microseconds, 0 by default) adds a short sleep before the flush, so more commit records can be added to it. 3 It skips the sleep if fewer than commit_siblings other sessions are in active transactions. 3
The docs suggest starting at half the flush time that pg_test_fsync reports for one 8 kB write. They also warn that a value that is too high can add so much latency that throughput falls. 3
Nagle's algorithm and TCP_NODELAY
TCP batches too. In 1984, John Nagle described a problem with keyboard traffic. Each typed character went out alone, as a 41-byte packet: 1 byte of data and 40 bytes of headers. 4
His fix, now called Nagle's algorithm: while earlier data on the connection is still unacknowledged, hold new data. Send it together when the acknowledgement comes. 4 Today's version holds data only until it can fill a full-sized packet. 5 TCP should still implement this rule, and must let an application turn it off per connection. 5
The trouble is the receiver. It may hold back its acknowledgement for a short time, so it sends fewer of them. This is a delayed acknowledgement. The delay must be less than 0.5 seconds. 5 RFC 9293 says the two features together "can result in poor application performance" for request-response traffic. 5
RFC 9293 gives no example, so here is a common one. Your client sends a request in two small writes: header, then body. The header goes out at once. Nagle holds the body until the header is acknowledged. The server's TCP delays its acknowledgement. The server app cannot reply yet, because it still waits for the body. Nothing moves until the delayed-acknowledgement timer fires.
The usual fix is the TCP_NODELAY socket option, which turns Nagle off for one connection. 6 5 A better habit is to build the whole request in memory and send it in one write. That is batching in your own code.
Pipelining
Pipelining cuts the cost of round trips. CPUs use the same idea inside: an instruction pipeline starts the next instruction before the last one is done. If the round-trip time is 250 ms, a client that waits for each reply can do at most 4 requests a second, even if the server can handle 100,000. 1
With pipelining, the client sends many commands, then reads all the replies. You pay the round trip once for the group. 1
Step through it. Use Next and Back, or the ← and → keys.
- A: the client sends INCR x and waits. The reply 1 comes back one full round trip later. Only then can the client send the next command.
- A: commands 2, 3 and 4 each wait for the reply before them. Four commands cost four round trips. Redis is idle most of this time.
- B: the same four commands, pipelined. The client sends all four at once, without waiting for any reply.
- B: Redis answers in order: 1, 2, 3, 4. The client reads all the replies together. The four commands cost about one round trip. Redis must keep the replies in memory until the client reads them.
It also cuts system calls. Without pipelining, Redis does a read() and a write() per command. With it, one read() takes in many commands and one write() sends many replies. Redis reports up to 10 times the throughput this way. 1
Pipelining cannot help when the next command needs the last reply. A read, compute, write sequence must wait. Redis suggests a server-side script for that case. 1
HTTP/1.1 pipelining and why it faded
HTTP/1.1 allows pipelining too. But the server must send responses "in the same order that the requests were received". 7 So a slow first response blocks every response behind it. This is head-of-line blocking.
Browsers do not turn HTTP pipelining on by default. MDN gives three reasons: buggy proxies, it is hard to implement correctly, and head-of-line blocking. 9 HTTP/2 replaced it with multiplexing. Each request gets its own stream, so a stalled response does not block the others. 8 But TCP head-of-line blocking remains: a lost packet still delays every stream on the connection. 8 HTTP/3 fixes that; see HTTP/1.1, HTTP/2, HTTP/3 and QUIC.
Adaptive batching
A fixed time limit makes every item wait, even when the system is idle. Martin Thompson describes a better way, which he calls smart batching. 10
One thread sends data as soon as any is available. Items that arrive while a send is in progress form the next batch, up to the buffer size. A lone item goes out alone, with no timer. 10
In his example, writing one buffer to the network and getting it acknowledged takes 100 µs. Then 10 messages arrive at once. If each thread writes its own message, the writes queue up, and the last one finishes after 1,000 µs. With smart batching, no message takes more than 200 µs. 10 Batches grow only when load grows. So at low load you get low latency, and at high load you get big batches. Bound the queue, though. Thompson warns that an unbounded queue "could grow out of control". 10
Trade-offs
| Option | Throughput | Latency | Use it when |
|---|---|---|---|
| One at a time | No Pays the full fixed cost per item. | Lowest at low load. | Traffic is light, or each step needs the last result. |
| Batch with size and time limits | Yes Big gains under load. | Adds up to the time limit per item. | Producers, log shippers, bulk writes. |
| Adaptive (smart) batching | Yes Batches grow with load. | Low at low load, no timer. | You own the sender loop and the downstream is serial. |
| Pipelining | Yes Pays the round trip once per group. | Low, but one slow reply can block in-order replies. | Many independent commands on one connection. |
| Group commit | Yes One flush for many commits. | Adds a short wait, if you set a delay. | Many concurrent writers, flush-bound disk. |
At work: how a senior uses this
- Find the fixed cost first. Ask: "What do we pay per call, whatever its size?" Usually it is round trips, system calls, flushes or headers.
- Never batch without a time limit. Check the worst wait an item can have against your latency target.
- Measure at low load too. A time limit that helps at peak adds pure delay at 3 a.m.
- Decide what happens when one item in a batch fails. Return a result per item, and retry only the failed items.
- Plan for a bad item (sometimes called a poison message). One bad record should not block the whole batch forever. Move it to a dead letter queue.
- For request-response protocols over TCP, send each request in one write, or set
TCP_NODELAY.
With AI
What to ask the agent
"This loop calls Redis once per item. Rewrite it to pipeline in chunks of 10,000 commands, and keep a result for each item."
"Our Kafka producer sends 200 records a second at night and 20,000 at peak. Estimate the batch size and added latency for linger.ms = 5 and 50. Show the arithmetic."
What to check yourself
- Every batch has both a size limit and a time limit, and the numbers came from your traffic, not a guess.
- A failure of one item does not lose or silently retry the other items in the batch.
- The new code does not depend on the reply to a command that is still in the same pipeline.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 10 sources and related lessons
- Redis, “Redis pipelining”, Redis documentation (opens in a new tab)
Round-trip time, how pipelining sends many commands before reading replies, the cost of read() and write() system calls, and the advice to send batches of about 10k commands. - Apache Kafka, “Producer Configs”, Apache Kafka 4.4 documentation (opens in a new tab)
The batch.size and linger.ms settings, their defaults, and why the linger.ms default changed from 0 to 5 in Kafka 4.0. - PostgreSQL Global Development Group, “28.5. WAL Configuration”, PostgreSQL 18 documentation (opens in a new tab)
Group commit, commit_delay and commit_siblings, and how to pick a starting value with pg_test_fsync. - John Nagle, “Congestion Control in IP/TCP Internetworks”, RFC 896, January 1984 (opens in a new tab)
The small-packet problem (41-byte packets for 1 byte of data) and the rule now called Nagle's algorithm. - Wesley Eddy (ed.), “Transmission Control Protocol (TCP)”, RFC 9293, August 2022 (opens in a new tab)
Section 3.7.4 on Nagle's algorithm, section 3.8.6.3 on delayed acknowledgements, and Appendix A.3 on how the two interact badly. - Linux man-pages, “tcp(7) - Linux manual page” (opens in a new tab)
The TCP_NODELAY socket option, which turns off Nagle's algorithm. - Roy Fielding, Mark Nottingham and Julian Reschke (eds.), “HTTP/1.1”, RFC 9112, June 2022 (opens in a new tab)
Section 9.3.2 on pipelining, the rule that responses come back in request order, and retries. - Martin Thomson and Cory Benfield (eds.), “HTTP/2”, RFC 9113, June 2022 (opens in a new tab)
Why HTTP/1.1 pipelining only partly solved concurrency, and how HTTP/2 streams avoid head-of-line blocking at the HTTP layer. - MDN Web Docs, “Connection management in HTTP/1.x” (opens in a new tab)
Why browsers do not turn on HTTP pipelining, and how HTTP/2 multiplexing replaced it. - Martin Thompson, “Smart Batching”, Mechanical Sympathy blog, 19 October 2011 (opens in a new tab)
Batching whatever arrived while the last send was in progress, with no timer, and a worked example with 100 µs writes.
Case studies: LinkedIn: How Kafka reached 2 million writes a second on cheap machines
Related: Tail latency and queueing · Latency numbers and back-of-envelope maths · Mechanical sympathy: CPU caches and memory · Queues vs logs and delivery guarantees · Stream processing · OS essentials for backend engineers · HTTP/1.1, HTTP/2 and HTTP/3 · TCP/IP and the network stack