← Back to Node.js, page 8

nodejs-0153 · Hard senior

How would you design a file processing pipeline (parse, transform, store) in Node.js with bounded concurrency per stage, ordered output and backpressure?

Chain async generator stages. Each stage keeps at most N items in flight, yields results in the original order, and pulls from the previous stage only when it has room, so a slow stage slows the source instead of growing a queue. Size each stage by its resource (CPU, network, disk), and at the system level add a durable queue, retries, idempotent writes and a dead letter store.

Full answer

Pipeline thinking

  • Break the work into stages with different limits. For example parse (CPU, small), resize (CPU heavy, 2 at a time), upload (network, 3 at a time).
  • Every stage needs a bound. Without it a fast source loads thousands of files into memory while the slow stage works.
  • Backpressure comes from the pull model. An async generator stage calls next() on its source only when it has capacity, so pressure flows back to the beginning.
  • Ordering: if the output must keep input order, wait for results in order while later items run in parallel. If order does not matter, take results as they finish (higher throughput).

Inside one process

  • A helper mapOrdered(source, fn, limit) keeps a small array of in-flight promises. It fills the array, awaits the first one, yields it, and refills.
  • Use worker threads for CPU stages and a limit near the core count.
  • Streams (Transform) work too. Object mode streams have highWaterMark in objects.

At system level (design interview)

  • A durable queue between stages (SQS, BullMQ, Kafka) so a crash does not lose work. Workers are separate processes that scale independently.
  • Store the state of every file (pending, processing, done, failed) in a database, with an idempotency key so retries do not duplicate results.
  • Retry with backoff, then a dead letter queue. Keep poison files from blocking the line.
  • Big files go to object storage first, and the queue carries only the key.
  • Metrics: queue length, age of the oldest item, time per stage, failure rate.
javascript
const { setTimeout: sleep } = require('node:timers/promises');

// Runs fn on up to `limit` items at once, but yields the results in input order.
async function* mapOrdered(source, fn, limit) {
  const iterator = source[Symbol.asyncIterator]();
  const inFlight = [];
  let finished = false;
  async function fill() {
    while (!finished && inFlight.length < limit) {
      const next = await iterator.next();
      if (next.done) { finished = true; break; }
      const promise = fn(next.value);
      promise.catch(() => {});               // the error is reported when the result is awaited
      inFlight.push(promise);
    }
  }
  await fill();
  while (inFlight.length) {
    yield await inFlight.shift();
    await fill();
  }
}

const stats = {};
function stage(name, limit, delayFor) {
  stats[name] = { running: 0, max: 0, limit };
  return (source) => mapOrdered(source, async (file) => {
    const s = stats[name];
    s.max = Math.max(s.max, ++s.running);
    await sleep(delayFor(file.id));               // pretend work
    s.running--;
    return { ...file, [name]: true };
  }, limit);
}

let produced = 0, consumed = 0, maxAhead = 0;
async function* files() {
  for (let id = 1; id <= 12; id++) {
    produced++;
    maxAhead = Math.max(maxAhead, produced - consumed);
    yield { id };
  }
}

async function main() {
  const parse = stage('parse', 4, (id) => 5 + (id % 3) * 4);
  const resize = stage('resize', 2, (id) => 30 - (id % 4) * 6);    // the slow stage
  const store = stage('store', 3, (id) => 5 + (id % 2) * 8);

  const order = [];
  for await (const file of store(resize(parse(files())))) { consumed++; order.push(file.id); }

  console.log('output order:', order.join(','));
  console.log('in input order:', order.every((id, i) => id === i + 1));
  for (const [name, s] of Object.entries(stats)) console.log(name.padEnd(7), 'limit', s.limit, '| never above the limit:', s.max <= s.limit, '| reached it:', s.max === s.limit);
  console.log('source was read at most', maxAhead, 'items ahead of the final consumer (12 files in total)');
}
main();

Twelve files pass through three stages with limits 4, 2 and 3. The output stays in order, no stage goes above its limit, and the source never runs far ahead of the slowest stage. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): output order: 1,2,3,4,5,6,7,8,9,10,11,12 in input order: true parse limit 4 | never above the limit: true | reached it: true resize limit 2 | never above the limit: true | reached it: true store limit 3 | never above the limit: true | reached it: true source was read at most 7 items ahead of the final consumer (12 files in total)

Key points

  • Each stage needs its own concurrency bound.
  • Pulling from the source only when there is room gives backpressure.
  • Keeping order means awaiting results in order while work runs in parallel.
  • Use workers for CPU stages.
  • A durable queue and idempotent writes make it survive crashes.

Common mistakes

  • No limit on a stage, so memory grows with the input.
  • Using Promise.all on the whole input list.
  • Losing order when the output must match the input.
  • Retrying inside the stage without an idempotent write.
  • Running CPU-heavy stages on the main thread.

Follow-ups

  • How would you handle one file that always fails?
  • How do you choose the limit for each stage?
  • How would the design change if the files are 10 GB each?

Tips

  • Draw the stages with their limits.
  • Say 'pull model gives backpressure'.
  • Finish with the durable queue and idempotency.