brandonmtaylor.dev
Subject
Software
Date
Read
9 min

Single requests vs batch: start with one, prove you need more

Why I start every API with single requests, how to prove with latency and metrics that you need batching, and the rules a batch API should follow when you do: a result for every item, a cap on input, and a place to pick back up.

Contents
  1. Why single requests first
  2. Prove it with data first
  3. When you batch, do it the AWS way
  4. The takeaway
  5. Test yourself
  6. Further reading

When an API needs to handle many items, there are two shapes it can take. Single requests: one item per call, so a hundred items means a hundred calls. Batch requests: many items per call, so a hundred items might be one or ten.

I always start with single requests, and most of the time that’s where it stays. Batching sounds like the efficient choice, so people reach for it early, before anything shows they need it. What they get is code that’s harder to read, harder to test and harder to debug, solving a performance problem nobody measured.

Start with single requests. Move to batch only once the data proves you need it. And when you do, build it the way AWS builds its batch APIs.

Why single requests first

A single request is the simplest thing that works:

  • One item, one result. It succeeds or it fails, with a status code and an error that’s about that item.
  • Retries are simple. Retry the one call. No working out which part of a batch went through.
  • It’s easy to read and test. The handler does one thing. There’s no loop, no partial failure and no mapping between inputs and outputs.
  • It’s easy to trace. One request ID, one log line, one trace for one item.

A batch API gives all of that up. Every call can partly succeed, so every caller has to check each item’s result. Inputs have to be matched to outputs. There are limits to enforce and oversize requests to reject. None of that is hard on its own, but all of it is code that exists only because of batching, and it’s wasted if single requests were fast enough.

Prove it with data first

“Batching would be faster” is a guess until you measure it. Put metrics on the single-request path and let them tell you:

  • Latency per request, at the median and the p99. If a single call is already fast, batching saves little.
  • Calls per user action. One screen that makes 300 calls to load is a real signal. One that makes 3 isn’t.
  • Where the time goes. A trace (AWS X-Ray, or any tracing tool) shows whether the time is in the work itself or in per-call overhead: connecting, authenticating, cold starts. Batching only cuts the overhead. If the work dominates, batching just moves it.
  • Limits you’re actually hitting. Throttling errors, rate limits, or a per-request cost that shows up on the bill.

Before batching, try the cheaper fixes the data might point to: make the single calls in parallel instead of one after another, reuse connections (keep-alive) so you aren’t paying for a new one each time, or cache what doesn’t change. Each of those keeps the simple API.

Sometimes the SDK can batch for you, too. The AWS SDK for Java has an automatic batching client for SQS: your code still sends one message at a time, and the SDK groups them into batch calls behind the scenes. You get the fewer requests without writing any batch handling.

Know what batching costs before you commit to it. It can make each item slower. Items wait for a batch to fill or for a timer to fire: the Java SQS batching client, for example, waits up to 200 ms by default before sending a partial batch. That’s fine for background work and wrong for something a user is waiting on.

Then, and only then, batch. And when you do, the metrics you already have become the before picture that shows whether it worked.

When you batch, do it the AWS way

AWS has a lot of batch APIs, and they mostly follow the same rules. They’re good rules to copy:

API Max items per call How you match results to inputs
SQS SendMessageBatch 10 An Id you set on each entry
SNS PublishBatch 10 An Id you set on each entry
EventBridge PutEvents 10 Same position as in the request
Kinesis PutRecords 500 Same position as in the request
DynamoDB BatchWriteItem 25 Failed items returned as UnprocessedItems
Diagram. A request of up to 100 items, each with an id, goes to a batch API that checks limits, then each item. The response is HTTP 200 with a result per id: a ok, b invalid, c ok, d ok, plus lastProcessedId d, where to pick back up. One bad item gets its own error, and the call still returns 200.

1. Return a result for every item, not an error for the call

When one item in an AWS batch fails, the call doesn’t fail. It returns HTTP 200, with a result for each item: success for the ones that worked, and an error code and message for the ones that didn’t. EventBridge PutEvents returns a FailedEntryCount and an entry for every event. DynamoDB BatchWriteItem returns the writes it couldn’t do as UnprocessedItems, in the same shape as the request, so you can send them straight back.

The whole call errors only when the request itself is wrong: bad auth, a malformed body, or too many items. One bad item never turns into an error for the other ninety-nine. (DynamoDB’s BatchGetItem does fail the whole call if every item fails, which is reasonable: at that point, the problem isn’t any one item.)

The catch is on the caller’s side: a 200 doesn’t mean everything worked. Code that checks only the status code will quietly drop every failed item. Always check the per-item results, and retry only the failures, with backoff. Some SDKs have higher-level clients that do this for you, like boto3’s batch_writer for DynamoDB.

2. Map every input to its output

The caller has to know which result belongs to which item. There are two ways to do it:

  • An ID per item, chosen by the caller, echoed back in the result. This is what SQS and SNS do, and it’s the one I’d pick for my own APIs, because it doesn’t break if anyone reorders the results.
  • Position: result 3 belongs to item 3. EventBridge and Kinesis do this. It works, but it’s easy to get wrong if anything in between filters or sorts.

3. Cap the input

Every batch API needs a maximum, and every AWS one has one: 10, 25, 500. Most also cap the total size (EventBridge PutEvents must be under 1 MB, and BatchWriteItem 16 MB), because ten huge items can be worse than a thousand small ones. Without a cap, someone sends a million items in one request, and the call runs until it times out, holds memory the whole time, and fails with no useful result for any of them.

Pick limits on count and size that keep a full batch comfortably inside your timeout, document them, and reject anything over them with a 400 that says what the limit is.

4. Return where you stopped

If a call can stop partway (it hit a time budget, a size limit or throttling), tell the caller where. Return the last processed key or ID. Most users never look at it, but anyone who needs to can use it to pick back up where the call left off, or to page through results.

DynamoDB does this on reads: Query and Scan return a LastEvaluatedKey, and you pass it back as ExclusiveStartKey to get the next page. On writes, UnprocessedItems does the same job.

Three more things that are easy to miss

  • A batch isn’t a transaction. Some items succeed and some don’t, and the ones that succeeded stay done. If the items have to succeed or fail together, you need a transaction (in DynamoDB, TransactWriteItems), which is a different tool with different limits.
  • Decide what a duplicate in one batch means. If the same item appears twice in one request, is that two writes, one, or an error? DynamoDB’s BatchWriteItem rejects the whole request. Pick a rule and document it.
  • Measure per item, not per call. Once you batch, a call can succeed while half its items fail, so a dashboard of successful calls looks healthy while work is being lost. Count item successes and failures separately.

Put together, a batch endpoint looks like this:

const MAX_ITEMS = 100;

type Item = { id: string; payload: unknown };
type Result = { id: string; ok: true } | { id: string; ok: false; error: string };

export async function handleBatch(items: Item[], deadline: number) {
  if (items.length > MAX_ITEMS) {
    // The request itself is wrong: this is the one case that errors.
    return { status: 400, body: { error: `At most ${MAX_ITEMS} items per request.` } };
  }

  const results: Result[] = [];
  let lastProcessedId: string | undefined;
  for (const item of items) {
    // Out of time: stop here and say how far we got.
    if (Date.now() > deadline) break;
    try {
      await processItem(item);
      results.push({ id: item.id, ok: true });
    } catch (err) {
      // One bad item gets its own result; it doesn't fail the rest.
      results.push({ id: item.id, ok: false, error: (err as Error).message });
    }
    lastProcessedId = item.id;
  }

  return { status: 200, body: { results, lastProcessedId } };
}

Each result carries the caller’s id, failures are per item, the input is capped, and lastProcessedId says how far it got. If the deadline cuts the call short, the items after lastProcessedId have no result yet, and the caller sends them again in the next request.

Since a caller will retry failed items, and sometimes a whole batch after a timeout, each item’s processing should be safe to repeat. That’s idempotency, and the retries post covers how to retry the failures without making things worse.

The takeaway

  • Start with single requests. They’re simpler to read, test, retry and trace, and they’re often all you need.
  • Prove it before you batch. Measure latency, calls per action, where the time goes and the limits you hit. Try parallel calls, connection reuse and caching first.
  • Return a result for every item. Error only when the request itself is wrong, and have callers check per-item results, not just the status code.
  • Map inputs to outputs, with an ID per item.
  • Cap the input, by count and size, and reject oversize requests with a clear message.
  • Return where you stopped, so callers can resume or paginate.

Test yourself

1. A page makes 40 API calls to load, one after another, each taking about 50 ms. Should you build a batch endpoint?

Not yet. Try making the calls in parallel first. If they’re independent, the page would wait roughly as long as the slowest call instead of all 40 added together. Batch only if the parallel version still isn’t fast enough, or the calls hit rate limits.

2. You call a batch API with 25 items and get HTTP 200. Did all 25 succeed?

Not necessarily. Batch APIs return 200 when the call worked, even if some items failed. Check the per-item results (or UnprocessedItems, or FailedEntryCount) and retry only the failed items.

3. Why is an ID per item safer than matching results by position?

Position breaks as soon as anything between the server and the caller filters, sorts or retries part of the list. An ID travels with the item, so the match holds no matter what order the results come back in.

4. Your batch endpoint has no maximum. What happens when someone sends 100,000 items?

The call runs until it times out, holding memory the whole time, and the caller gets no result for any item, not even the ones that finished. A cap with a clear 400 turns that into an error the caller can fix by splitting the request.

Further reading