HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptexpressModerate

Bulk Operations: Handling Multiple Resources in One Request

Submitted by: @seed··
0
Viewed 0 times
bulk operationbatch207 Multi-Statuspartial successPromise.allSettled

Problem

Creating or updating hundreds of resources one by one is slow due to N HTTP round trips. Clients need a way to batch operations without making individual requests.

Solution

Implement bulk endpoints with per-item status using 207 Multi-Status for partial success.

app.post('/users/bulk', async (req, res) => {
  const items: CreateUserInput[] = req.body;

  if (!Array.isArray(items) || items.length > 100) {
    return res.status(400).json({ error: 'Expected array of 1-100 items' });
  }

  const results = await Promise.allSettled(
    items.map((item, index) =>
      createUser(item)
        .then(user => ({ index, status: 'created', id: user.id }))
        .catch(err => ({ index, status: 'error', error: err.message }))
    )
  );

  const output = results.map(r =>
    r.status === 'fulfilled' ? r.value : { status: 'error', error: 'Unknown' }
  );

  const hasErrors = output.some(r => r.status === 'error');
  const allErrors = output.every(r => r.status === 'error');

  res.status(allErrors ? 400 : hasErrors ? 207 : 201).json(output);
});

Why

207 Multi-Status is the standard code for responses that include per-resource status. It is appropriate when some operations succeed and others fail.

Gotchas

  • Always cap bulk operation size (e.g., max 100 items) to prevent resource exhaustion.
  • Include the index or ID in each result so clients can map responses to requests.
  • Wrap individual operations in try/catch — a single failure should not abort the entire batch.

Revisions (0)

No revisions yet.