Batch small operations
Thousands of tiny calls (N+1 queries, one Redis GET per id) dominate latency.
Say it like this
Hydrating a feed is 20 post lookups and 20 author lookups, so I collect the ids and issue one MGET per store instead of forty round trips; latency drops from forty network hops to two.
Basic solution
Collect ids and issue one bulk request: MGET, IN (...) queries, batched RPCs.
Two round trips instead of forty
The feed service gathers all post ids first, fetches them in one MGET, gathers the distinct author ids from the result, and fetches those in a second MGET. The feed service fills any cache misses with one IN query to the database.
How it works
- Before fetching anything, the caller collects every key it needs: first all the post ids for the page, then, once the posts are in hand, all the distinct author ids from those posts.
- It issues one bulk request per store: MGET with all the keys for Redis, SELECT ... WHERE id IN (...) for SQL, a batched RPC for another service. One request carries the whole list.
- The store answers all the keys in one round trip. The caller maps each result back to the key it asked for (not to the position in the list) and fills in any misses from the next layer down.
- For code that cannot easily gather its keys up front, such as GraphQL resolvers, a loader (the DataLoader pattern) collects the individual get calls made during one event-loop tick and flushes them together as a single batch.
- Batches are capped in size: a page of 20 is one call, but a backfill of 100K ids becomes 1,000 calls of 100 so no single request is enormous.
What batching removes
- The per-call overhead: the network round trip, acquiring a connection, parsing the request, and the database planning each query. The work on the data itself is unchanged; you are paying the fixed cost once instead of forty times.
Worked example
Feed hydration on the news feed
- A page is 20 post ids. Each post needs its body and its author profile: 40 lookups.
- One call per key: 40 × 0.5 ms Redis round trip = 20 ms serial, or 1–2 ms in parallel but 40 connections in flight per page. At 10K pages/s that is 400K Redis ops/s and 400K connection acquisitions.
- Batched: MGET of 20 post ids (one round trip, ~0.7 ms) then MGET of up to 20 distinct author ids (~0.6 ms). Two round trips, ~1.5 ms, 20K Redis ops/s at the same page rate.
- Database fallback for misses: one SELECT ... WHERE id IN (list) instead of N point queries; the planner does one index scan with 20 keys.
- Rate limiter counting: gateways accumulate counts locally for 100 ms and send one INCRBY per key instead of one per request, cutting Redis calls 10–100×.
Variants and when each wins
Explicit bulk APIs
- MGET, IN lists, batch endpoints, where the caller gathers its keys first and sends them in one request. It wins on efficiency whenever the code can know its keys ahead of time.
Request-scoped loader (DataLoader)
- Individual get calls made within one event-loop tick are coalesced into one batch, with a per-request cache so the same key is fetched once. It wins in resolver-style code, where each field asks for its own data and restructuring is impractical.
Pipelining
- The client sends many commands back to back without waiting for each reply, and the store answers them in order. It wins when the commands cannot be merged into one, such as a mix of GET and SET; it removes the round-trip waits but not the per-command work.
Time-window batching for writes
- Writes are buffered for a few milliseconds or until N arrive, then flushed as one bulk write. It wins for counters and logs where a few milliseconds of delay are fine; the buffer is lost if the process crashes before the flush.
Use explicit bulk reads wherever the keys are known, a loader in GraphQL-style resolvers, and windowed batching only for writes that tolerate a few milliseconds of delay.
Failure modes
One slow key stalls the batch
- The p99 of the batched call is far worse than that of any single key. It happens because the batch cannot return until its slowest member does, and a bigger batch is more likely to include a slow member. Cap the batch size, set a deadline for the batch, and return partial results with the misses flagged rather than waiting.
Oversized request
- A 50K-key IN list times out or trips a parameter limit. It happens because the batch had no upper bound. Chunk to 100 to 1,000 keys per call and run the chunks concurrently under a concurrency limit.
Lost error granularity
- One bad key fails the whole batch. It happens because the bulk API is all-or-nothing and reports a single error for the request. Prefer APIs that return a per-item status, or fall back to individual calls for the chunk that failed.
Duplicate and misordered keys
- Results end up attached to the wrong rows. It happens because the code deduplicated the key list before sending and forgot to expand it again, or assumed the response order matched the request order. Map results by key, never by position.
Batch window adds latency to everything
- Every request is 10 ms slower. It happens because a time-window batcher was placed on a hot read path, so every read waits for the window to close. Use time windows only for writes; for reads use a loader that flushes at the end of the current tick.
Interviewer follow-ups
Answer out loud before you open each one.
What is the N+1 problem and how does batching fix it?
Fetching a list of N items and then one extra query per item for a related record gives N+1 round trips. Collect the N foreign keys and fetch the related records in one IN query or MGET, which turns N+1 into 2.
How big should a batch be?
Big enough to amortise the round trip, small enough that the slowest member and the payload size stay bounded; 100 to 1,000 keys is typical. Measure p99 against batch size and pick the knee.
Does batching help writes as well as reads?
Yes, and often more: one multi-row INSERT or INCRBY replaces hundreds of statements and transaction commits. The trade is a buffering window that delays each write slightly and can be lost on crash, so use it for counters and logs, not for payments.
How does pipelining differ from batching?
Batching merges many operations into one command the server executes together. Pipelining sends many separate commands without waiting for replies, removing the round-trip waits but not the per-command work. Redis supports both; MGET is a batch, a pipeline of GETs is pipelining.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Feed service | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon ElastiCache | Post cache, User cache | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon Aurora | Posts DB | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |