Performance
Batching in Kafka and Postgres
A team migrates a logging pipeline to Kafka. Throughput tops out at 40 MB/s and the brokers are bored — disk and network both under 20%. They add producers, add partitions, nothing moves. The cause was one default no one looked at: linger.ms=0. Every message was flushed as its own request the instant send() returned, so “batching” never happened. One line — linger.ms=20, batch.size=131072 — and the same cluster pushed 300 MB/s. The bottleneck was never the brokers. It was a producer that refused to wait.
Every write has a fixed cost (network round-trip, syscall, ACK, an fsync) and a variable cost (the bytes themselves). When the fixed cost dominates — and for small messages it always does — batching amortizes it across N records. The two-dimensional window from the previous lesson (max-size OR max-wait) is exactly how both Kafka and Postgres decide when the batch goes out. The systems differ only in the mechanism, not the idea.
Kafka producer batching
The Kafka producer does not send one request per send(). It accumulates records in an in-memory buffer, one batch per (topic, partition), and ships a batch when either trigger fires first:
batch.sizeis reached — the per-partition byte cap, default 16 KB (16384 bytes).linger.msexpires — the max time the producer will wait for more records to fill a batch.
Here is the trap that bit the team above. Through Kafka 3.x, linger.ms defaulted to 0, meaning “send as soon as you can.” That does not disable batching outright — records that pile up while a request is in flight still coalesce — but under steady, well-paced load it effectively sends tiny batches, capping throughput far below the hardware. Kafka 4.0 changed the default to linger.ms=5 precisely because so many deployments left throughput on the table. The fix for a throughput-bound producer is to deliberately wait: linger.ms in the 5–100 ms range, batch.size raised to 64–512 KB. You trade a few ms of producer-side latency for fewer, fatter requests.
The senior tradeoff is sharp: linger.ms adds latency only when the batch is not already full. Under high load, batch.size fills before the timer expires, so the timer never costs you anything — you get big batches for free. Under low load, linger.ms is a small, bounded tax that buys efficiency. That is why a non-zero linger almost always wins: it can only help when you have spare time anyway.
| Knob | Default | Throughput tuning | What it controls |
|---|---|---|---|
linger.ms | 0 (3.x) → 5 (4.0) | 5–100 ms | Max wait to fill a batch (time trigger) |
batch.size | 16 KB | 64–512 KB | Per-partition byte cap (size trigger) |
compression.type | none | lz4 / zstd | Per-batch compression on the wire + on disk |
buffer.memory | 32 MB | raise if blocking on send | Total producer buffer across all partitions |
Postgres bulk writes: INSERT vs COPY
The same shape appears on the database side, three rungs of amortization:
- Per-row
INSERT— every statement is parsed, planned, executed, and (with autocommit) committed on its own. The commit forces a WAL flush. Throughput lands around 1–5k rows/s. In a hot path this is where ingestion goes to die. - Multi-row
INSERT ... VALUES (...), (...), ...— one parse, one plan, one commit for the whole statement. Now the fixed cost is amortized across the rows in the statement: roughly 5–50k rows/s. The catch is a practical cap on rows per statement (parameter limits, statement size), so you chunk into batches of a few hundred to a few thousand. COPY— Postgres’s bulk path. It streams rows over a dedicated wire protocol, bypassing the per-row SQL parser and planner entirely, and commits once. The docs are explicit thatCOPYis “significantly more optimized” than a series ofINSERTs and that disabling autocommit isn’t even needed because it is already a single command. Throughput reaches 50–500k rows/s.
ORMs expose the middle and top rungs so you rarely hand-write them: Django’s bulk_create, SQLAlchemy’s executemany and COPY helpers, Rails’ insert_all. The senior move is to recognize which rung a code path is silently on — an ORM loop that calls save() per object is per-row INSERT wearing a nicer API, and it will quietly cap a bulk import at a few thousand rows a second.
| Method | Parse / plan | Commits | Rows/s (order of magnitude) |
|---|---|---|---|
Per-row INSERT | Per row | Per row (autocommit) | 1–5k |
Multi-row INSERT VALUES | Once per statement | Once per statement | 5–50k |
COPY | None (streaming protocol) | Once | 50–500k |
Why compression needs batching first
Compression and batching are not two separate wins — compression depends on batching. Dictionary-based codecs (lz4, snappy, zstd) find repetition within their input window. A single 200-byte log line has almost no internal repetition, so compressing it alone saves little and can even add overhead. Batch a few hundred of those similar lines together and the shared structure — same field names, same hostnames, same JSON keys — becomes highly compressible. In Kafka the codec runs per batch, on the whole record set, which is why compression.type does so little with linger.ms=0 and so much with fat batches.
The numbers favor it overwhelmingly. A 128 KB batch of repetitive event data routinely compresses 2–4x with lz4 or zstd (zstd typically 20–30% better than lz4 at higher CPU cost). Compression CPU runs around 50–100 MB/s per core — cheap next to the network bytes and the broker fsync you avoid, since the compressed batch is what hits the disk and what replicas copy. Batch first, then compress: the order is not optional.
Why this works
The two classic Kafka producer failures are mirror images. linger.ms=0 (the old default) silently caps throughput because batches never fill. The opposite — a huge batch.size/buffer.memory in front of a slow or lagging broker — lets the producer buffer until buffer.memory is exhausted, at which point send() blocks (or throws after max.block.ms) and backpressure rips through the app. Bigger batches help right up until the broker can’t keep up; then the buffer is just a queue hiding a capacity problem.
A Kafka producer is throughput-bound: brokers are idle but you can't push more than a fraction of the cluster's capacity. The producer runs Kafka 3.x defaults. What's the first fix?
You're loading 50 million rows into Postgres for a one-time import. Which path is fastest?
Order these write paths from lowest to highest throughput:
- 1 Per-row INSERT with autocommit (~1–5k rows/s)
- 2 Multi-row INSERT VALUES, batched (~5–50k rows/s)
- 3 COPY streaming protocol, single commit (~50–500k rows/s)
A Kafka producer ships clickstream events with a relaxed latency budget (a few hundred ms is fine) and a tight cost budget on network egress. Pick the config a senior defends.
- 01What two triggers cause a Kafka producer to send a batch, and why does a non-zero linger.ms usually win on throughput without hurting latency much?
- 02Why does Postgres COPY outperform INSERT VALUES, and why does compression need batching first?
Kafka and Postgres batch with the same two-dimensional window. The Kafka producer buffers records per (topic, partition) and ships a batch when batch.size (default 16 KB) is hit or linger.ms expires; the old linger.ms=0 default silently caps throughput, which is why 4.0 raised it to 5 — set it to 5–100 ms with batch.size 64–512 KB to trade a few ms of latency for far fatter requests. Postgres climbs three rungs: per-row INSERT (1–5k rows/s) pays parse, plan, and commit on every row; multi-row INSERT VALUES (5–50k) amortizes them per statement; COPY (50–500k) streams over a custom protocol that skips per-row parse/plan and commits once. Compression depends on batching — lz4 and zstd find repetition only across a full batch, hitting 2–4x at cheap CPU, so you batch first and compress second. The failure modes are mirror images: linger.ms=0 starves batches, while an oversized buffer in front of a slow broker just hides a capacity problem until send() blocks.
appears again in260
- Why GraphQL gets N+1junior
- DataLoader mechanics: tick-boundary batchingmiddle
- Batch function contracts: ordering, shapes, errorsmiddle
- Federation and lookahead: batching beyond DataLoadermiddle
- Query complexity defences: depth, cost, persisted queriesmiddle
- Senior GraphQL API: scheduling contract, tenant isolation, observabilitysenior
- The journey of a request: seven stops from socket to responsejunior
- Accept and parse: from kernel queue to a typed requestmiddle
- Routing and middleware: choosing what runs, and in what ordermiddle
- Handler and response: from business logic to bytes on the wiremiddle
- Streaming and backpressure: when the client reads slower than you writesenior
- Timeouts and tail latency: budgets, deadlines, and the fan-out trapsenior
- Middleware and DI: the two patterns that shape every backendjunior
- Writing middleware: signatures, next(), and the three framework modelsmiddle
- Inversion of control: how dependencies reach a classmiddle
- DI scopes and lifecycles: singleton, request, transientmiddle
- DI as a testing seam: fakes, mocks, and the boundary that matterssenior
- DI containers in production: resolution graphs, circular deps, and when not tosenior
- Blocking vs non-blocking I/O: two ways to waitjunior
- The event loop: one thread, ordered phasesmiddle
- What blocks the loop: CPU work and sync callsmiddle
- Offloading CPU work: worker threads and the libuv poolmiddle
- Backpressure and bounded concurrencysenior
- Throughput under load: tail latency and saturationsenior
- Why pool: the cost of creating a connectionjunior
- Pool sizing: why bigger is not fastermiddle
- Acquisition and timeouts: the wait queue is the real latency dialmiddle
- Why idempotency: making retries safejunior
- Server-side state machine: four states of an idempotency keymiddle
- Retry strategies: backoff, jitter, and thundering herdmiddle
- Outbox and inbox: effectively-once across the dual-write boundarymiddle
- Concurrency and cache architecture for idempotency at scalesenior
- Observability, production failures, and global-scale designsenior
- The event loop: one thread, three queuesjunior
- Tasks, microtasks, and scheduler.yield()middle
- Timer accuracy, throttling, and idle workmiddle
- Microtask starvation, Long Tasks, and LoAFsenior
- Node.js event loop: phases, nextTick, and loop lagsenior
- React, Vue, and INP observability in productionsenior
- The render pipeline: six stages from bytes to pixelsjunior
- Stage costs and the renderer process modelmiddle
- Invalidation, dirty bits, and containmiddle
- Compositor layers: promotion, overlap, and GPU memorymiddle
- DevTools flame strip and the frame lifecyclemiddle
- Layout thrash: forced synchronous layoutsenior
- BeginMainFrame, compositor-driven animations, and GPU memorysenior
- Production observability: LoAF, INP, and the full attack surfacesenior
- What V8 is and why performance varies 100×junior
- V8''''s four-tier JIT pipeline and profile-guided tieringmiddle
- Hidden classes, transition trees, and memory layoutmiddle
- Inline caches, IC states, and deoptimizationmiddle
- Orinoco GC: parallel scavenger, concurrent marking, and write barriersmiddle
- TurboFan''''s speculative engine and the deopt-loop trapsenior
- V8 in production: isolates, pointer compression, and real failuressenior
- Service worker lifecycle and cache strategiesmiddle
- Service worker edge cases: version skew, durability, and navigation trapssenior
- What the reconciler does: render vs commitjunior
- The fiber object and the double-buffer treemiddle
- Render phase purity and commit phase sub-stepsmiddle
- Reconciliation: diffing heuristics and the key trapmiddle
- Priority lanes, time-slicing, and useTransitionmiddle
- Bailout, memoisation, and tearingsenior
- React Profiler, the Compiler, and production observabilitysenior
- Rendering strategies: SSG, SSR, ISR, streaming, and hydrationjunior
- SSG, SSR, ISR, streaming, and RSC — how each worksmiddle
- Hydration cost: selective, progressive, islands, resumabilitymiddle
- Hydration mismatch: causes, detection, and the determinism rulesenior
- RSC, per-route strategy, and production observabilitysenior
- Core Web Vitals: what LCP, INP, and CLS measurejunior
- LCP: four phases, one dominant costmiddle
- INP: input delay, processing, presentationmiddle
- CLS: why layout shifts happen and how to stop themmiddle
- Lab vs field: why the two disagree and how to use eachmiddle
- Metric tradeoffs, RUM attribution, and the CI+field loopsenior
- The full picture: URL to LCP to INP as a relay racejunior
- Eight layers traced: from the service worker to the second navigationmiddle
- Five canonical breaks: where production reliably diessenior
- The three-track method: reading traces and building a monitored systemsenior
- What is a cache stampede and why it makes things worsejunior
- Lock and single-flight: bounding concurrent rebuildsmiddle
- XFetch: coordination-free probabilistic early expirationmiddle
- Stale-while-revalidate and CDN request coalescingmiddle
- Detecting stampedes and designing TTL for productionmiddle
- Metastable failure, fencing tokens, and production postmortemssenior
- What a relation is: tables, rows, keys, and constraintsjunior
- Constraints, keys, and Postgres data typesmiddle
- Normal forms, denormalization, and why schemas stickmiddle
- JSONB, arrays, and when a side table winsmiddle
- Heap storage, TOAST, and column alignmentsenior
- Schema integrity: deferral, versioning, and production failure modessenior
- Relational vs document, wide-column, graph, and key-valuesenior
- What an index is and how it speeds up queriesjunior
- The leading-column rule and composite index designmiddle
- Partial, expression, and covering indexesmiddle
- Index types: GIN, GiST, BRIN, Hash, Bloom, and HOT updatesmiddle
- Index-only scans, the Visibility Map, and INCLUDEsenior
- Production failure modes and the index audit playbooksenior
- Index design exercise: full-text search strategysenior
- EXPLAIN and execution plans: what the planner decides and whyjunior
- Scan types: Seq, Index, Bitmap, Index-Onlymiddle
- Join algorithms and the row-estimate cascademiddle
- pg_statistic, ANALYZE, and production observabilitymiddle
- Extended statistics: fixing correlated-column estimate failuressenior
- Plan cache, cost-constant tuning, and planner internalssenior
- Production failure modes and plan stabilitysenior
- MVCC: why readers and writers never wait for each otherjunior
- Row versions and snapshots: the on-disk mechanicsmiddle
- HOT updates and isolation levels: what you gain and what you paymiddle
- Vacuum and bloat: keeping the storage tax boundedmiddle
- CLOG, XID wraparound, and MultiXact: deep visibility internalssenior
- SSI internals and production autovacuum tuningsenior
- Real-world MVCC failures, deployment patterns, and distributed snapshotssenior
- Connection pools: amortising the cost of a Postgres backendjunior
- PgBouncer session, transaction, and statement modesmiddle
- Pool sizing: the (cores × 2) + spindles formula and the two-layer stackmiddle
- Pool exhaustion and idle-in-transaction: the 3 AM failure modemiddle
- Migrating to transaction mode: rollout playbook and PgBouncer 1.21 prepared statementsmiddle
- The Postgres process model and why raising max_connections degrades throughputsenior
- Pooler landscape 2026, serverless connection storms, and the full failure-mode taxonomysenior
- What a schema migration is and why it replaces ad-hoc DDLjunior
- ADD COLUMN: instant in PG 11+ vs rewrite in older Postgresjunior
- The lock-queue failure mode: why instant DDL can freeze the databasemiddle
- Safe DDL patterns: NOT VALID, CONCURRENTLY, and unsafe-op fixesmiddle
- Expand-contract: zero-downtime for breaking schema changesmiddle
- Advisory locks, migration tools, and deploy coordinationsenior
- Migration failure taxonomy and production disciplinesenior
- Why sharding exists: the single-Postgres ceilingjunior
- Shard-key selection: hash, range, list, and directory strategiesmiddle
- Partitioning vs sharding: same word, two different thingsmiddle
- Co-location and Citus: the invariant that makes sharding usablemiddle
- The hot-shard failure mode: detection, isolation, and durable policymiddle
- Schema-based sharding and multi-tenancy alternativessenior
- Online resharding, 2PC, and the operational cost of shardingsenior
- The seven acts: from CREATE TABLE to Citusjunior
- Acts 1–3 in depth: schema, indexes, and planner statisticsmiddle
- Acts 4–6 in depth: MVCC bloat, connection pooling, and safe migrationsmiddle
- Act 7 in depth: sharding, co-location, and the seven-tier tradeoff cascademiddle
- Observability, anti-patterns, and production triagesenior
- Raft roles, terms, and why majority quorums prevent split brainjunior
- How Raft replicates a log entry and decides it is safe to commitmiddle
- Raft leader election: timeouts, voting rules, and the four safety propertiesmiddle
- Raft in the real world: partitions, slow disks, and client routingmiddle
- Raft extensions: pre-vote, learners, snapshots, and linearizable readssenior
- Raft in production: membership changes, Multi-Raft, and observabilitysenior
- Where data fetching happens — and why it decides LCPjunior
- Fetch waterfalls — diagnosis and the Promise.all curemiddle
- React Server Components and Suspense streamingmiddle
- Client-side cache: TanStack Query, SWR, and stale-while-revalidatemiddle
- LCP, prefetch, and race conditions in interactive fetchingmiddle
- Senior internals: RSC payload, caching layers, and production failure modessenior
- Bits on the wirejunior
- Latency mathmiddle
- Bufferbloat and congestionsenior
- The physical frontiersenior
- The three-way handshakejunior
- Sequence numbers and connection statemiddle
- Flow control and congestion controlmiddle
- BBR, production observability, and beyond TCPsenior
- DNS: what it does and why it existsjunior
- The resolver walk: referrals, record types, and gluemiddle
- TTL, caching, and DNS propagationmiddle
- The 1-RTT handshake: key shares and ECDHEmiddle
- Session resumption and 0-RTTmiddle
- CDN: putting content next doorjunior
- Anycast and GeoDNS: routing to the nearest edgemiddle
- Tiered cache and Cache-Controlmiddle
- Vary header and cache keysmiddle
- Stale-while-revalidate and cache stampedesenior
- Edge workers and edge-side compositionsenior
- CDN operations and observabilitysenior
- WebSocket: the HTTP upgrade handshakejunior
- WebSocket frame format: opcodes, masking, fragmentationmiddle
- WebSocket vs SSE vs long-polling: choosing the right transportmiddle
- WebSocket backpressure: when clients can''''t keep upmiddle
- Reconnection: jittered backoff, thundering herd, message resumptionsenior
- WebSocket at scale: HTTP/2 multiplexing, permessage-deflate, C10Msenior
- WebSocket in production: proxies, security, and distributed architecturesenior
- What reverse proxies dojunior
- Balancing algorithms: round-robin to power-of-two-choicesmiddle
- L4 vs L7 load balancing and client-IP preservationmiddle
- Health checks, connection draining, and slow startmiddle
- Session affinity, consistent hashing, and the right fixmiddle
- Retry storms, circuit breakers, and load sheddingsenior
- Resilient LB architecture: anycast, zone-aware routing, and observabilitysenior
- Why QUIC and not TCP+TLSjunior
- QUIC streams and head-of-line blockingjunior
- Integrated handshake and 1-RTTmiddle
- Connection IDs and network migrationmiddle
- Loss detection and congestion controlmiddle
- 0-RTT resumption and packet encryptionsenior
- Deployment tradeoffs and CPU costsenior
- DDoS: what it is and why it worksjunior
- Amplification attacks and state exhaustionmiddle
- Rate limiting: algorithms and architecturemiddle
- WAFs, firewalls, mTLS, and HSTSmiddle
- DNS cache poisoning and BGP hijackingsenior
- Defense-in-depth architecture and attack economicssenior
- The twelve layers: one URL, seven actorsjunior
- DNS, TCP, TLS in sequence: where the milliseconds gomiddle
- Critical render path and Core Web Vitalsmiddle
- Proxy intercepts and security gates: rate limiters, WAF, mTLSmiddle
- Alternate paths: QUIC 0-RTT, WebSocket upgrade, connection migrationmiddle
- Observability: distributed traces, USE/RED, and samplingsenior
- Resilience: cascading retries, circuit breakers, and error budgetssenior
- What the three signals are: logs, metrics, and tracesjunior
- Metrics and cardinality: the cost model of a time-series databasemiddle
- Logs and volume: the cost model of structured loggingmiddle
- Traces and sampling: the cost model of distributed tracingmiddle
- Join keys and exemplars: making the three signals composemiddle
- Observability 2.0: wide events and the cost shiftsenior
- Failure modes and engineering practice: cardinality budgets, PII, and samplingsenior
- Why structured logs exist: the diary vs the spreadsheetjunior
- The production log schema: fields every line must carrymiddle
- Log levels and alert routingmiddle
- Sampling strategies and log costmiddle
- PII redaction and log injectionsenior
- Trace context propagation in logssenior
- OTel Logs Data Model and audit logs as a subsystemsenior
- OTel signals, Semantic Conventions, and the OTLP wire formatmiddle
- Auto-instrumentation and manual spans: the 80/20 of OTelmiddle
- The OTel Collector: receivers, processors, exporters, and deployment patternsmiddle
- Sampling strategies: head, tail, and parent-basedmiddle
- Vendor neutrality, eBPF instrumentation, the Operator, and browser/serverless OTelsenior
- Operating the OTel Collector: reliability, version skew, failure modes, and governancesenior
- RED and USE: two checklists, one triage disciplinejunior
- Instrumenting RED in Prometheus: counters, histograms, and cardinality disciplinemiddle
- USE on Linux: CPU, memory, disk, network, and PSImiddle
- Golden signals, dashboard layout, and service mesh auto-REDmiddle
- Cardinality as a cost driver: labels, PII, exemplars, and samplingmiddle
- Native histograms, SLO tie-in, and production failure patternsmiddle
- SLI, SLO, and the error budget: reliability by the numbersjunior
- Choosing SLIs and SLO targets: ratios, not feelingsmiddle
- Multi-window multi-burn-rate alerting: why AND beats ORmiddle
- Error budget policy, latency SLOs, and composite journeysmiddle
- Iceberg SLIs, composite SLO math, and SLA vs SLOsenior
- Production SLO failures, self-observability, security, and the big picturesenior
- Flame graphs: reading the picture that shows where time goesjunior
- Sampling vs instrumentation profiling: why 99 Hz wins in productionmiddle
- Profile types: CPU, memory, off-CPU, mutex — which one to reach formiddle
- Continuous profiling: always-on flame graphs with eBPF and trace-id correlationmiddle
- How flame graphs are built from samples, and the production workflows that use themmiddle
- Linux perf, eBPF internals, PGO, and the limits of samplingsenior
- Profiling in production: security, war stories, OTel profiles, and the infrastructure designsenior
- The debugging funnel: SLO → RED → trace → profilejunior
- OTel architecture: one SDK, four signals, one wire formatmiddle
- Cost discipline: keeping observability under 5% of infra spendmiddle
- The incident loop: from pager to postmortem to preventionmiddle
- Scale, security, and the ROI of observable systemssenior
- At-most-once, at-least-once, exactly-once: the three delivery contractsjunior
- The three failure legs — where duplicates and losses actually happenmiddle
- Consumer-side dedup: the cheapest path to exactly-once processingmiddle
- Kafka exactly-once semantics: idempotent producer and transactionsmiddle
- SQS visibility timeout, DLQ, and the outbox patternmiddle
- Exactly-once in production: impossibility proof, hybrid patterns, and real incidentssenior
- What OAuth is and why passwords are not the answerjunior
- Authorization code flow with PKCEmiddle
- ID token validation and JWKS cache managementmiddle
- Refresh token rotation and scope-based least privilegemiddle
- Sender-constrained tokens: DPoP and mTLSsenior
- OAuth in production: audience attacks, observability, and real failuressenior