Trending

World technology news

→
Two lanes of CSV validation and a report that follows input order.
Software Engineering · 2026
Software Engineering

Validate files with bounded concurrency in Node.js

Limit active CSV validations, preserve input order, and record an outcome for every file in a working Node.js example.

Developer's JournalPublished: Nov 30, 20266 min read
Reading progress0%
In this article
  1. Four files and two active validations
  2. Put the limit where work starts
  3. Record outcomes using the original index
  4. Check the report and the active count
  5. Combine a job limit with resource limits
  6. Choose when validated rows become durable

Four files and two active validations

A sales team receives four regional CSV exports at the end of the day. Support needs to check the header, row count, and required fields for each file. A mistake in one region should leave the other validation results available. A report in input order lets an operator work down the source list even when the files finish out of order. This sample keeps at most two validations active. The north file takes longer. The south file finishes quickly with a missing header. West and east use the available slot. Each input produces one report entry. The program simulates both timing and error conditions locally so the demonstration can be run without an external service or customer data.

Put the limit where work starts

Mapping an async callback over a list invokes every callback during the map call. Promise.allSettled can then collect each outcome in input order. It receives promises for work that the mapping step already started. The example uses two loops instead. Each loop claims the next file index, waits for its validation, and takes another index if one remains. The read and increment happen before either loop can yield at an await. Each index is therefore claimed once within the JavaScript event loop. The counter belongs to one call of the function. Three simultaneous requests can each have their own pair of validations. A shared resource can require a limit that spans requests, so decide where that queue belongs before relying on a request-local limit.

Service architectureConceptual sketch · summary of the article's technical flow

Record outcomes using the original index

Allocate the results array to the size of the input and store each entry by index. South finishes first and appears after north in the report. The outer Promise.all waits for the validation loops to complete. Inside each loop, a try block catches both a synchronous exception from the inspection callback and a promise rejection. A fulfilled entry carries a value. A rejected entry carries the reason. The example keeps the error object so its message can be asserted in a test. An API can expose a stable error code and a short explanation without copying an uploaded field or a local file path into its response. An empty list starts no validation loops and returns an empty array.

import assert from 'node:assert/strict';
import { setTimeout as delay } from 'node:timers/promises';

export async function inspectFiles(files, limit, inspect) {
  if (!Number.isInteger(limit) || limit < 1) {
    throw new RangeError('limit must be a positive integer');
  }

  const results = Array(files.length);
  let cursor = 0;

  async function inspectNext() {
    while (cursor < files.length) {
      const index = cursor++;
      const file = files[index];
      try {
        const value = await inspect(file);
        results[index] = { file, status: 'fulfilled', value };
      } catch (reason) {
        results[index] = { file, status: 'rejected', reason };
      }
    }
  }

  await Promise.all(Array.from({ length: Math.min(limit, files.length) }, inspectNext));
  return results;
}

const completion = [];
let active = 0;
let peak = 0;
const files = ['north.csv', 'south.csv', 'west.csv', 'east.csv'];
const results = await inspectFiles(files, 2, async file => {
  active += 1;
  peak = Math.max(peak, active);
  try {
    await delay(file === 'north.csv' ? 35 : 5);
    completion.push(file);
    if (file === 'south.csv') throw new Error('missing header');
    return { rows: 12 };
  } finally {
    active -= 1;
  }
});

assert.equal(peak, 2);
assert.equal(active, 0);
assert.equal(completion[0], 'south.csv');
assert.deepEqual(results.map(result => result.file), files);
assert.deepEqual(results.map(result => result.status), ['fulfilled', 'rejected', 'fulfilled', 'fulfilled']);
assert.equal(results[1].reason.message, 'missing header');
assert.deepEqual(await inspectFiles([], 2, () => assert.fail('unexpected job')), []);
await assert.rejects(inspectFiles(files, 0, () => {}), RangeError);
const [one] = await inspectFiles(['bad.csv'], 1, () => { throw new Error('synchronous error'); });
assert.equal(one.reason.message, 'synchronous error');
console.log({ peak, report: results.map(({ file, status }) => [file, status]) });

Check the report and the active count

Run the file with Node.js. The peak value is two. The report lists north as fulfilled, south as rejected, and west and east as fulfilled. The active counter decreases in a finally block so the failed validation also frees its count. The sample checks that the count returns to zero, that an empty input stays empty, and that a limit of zero is rejected. The 35 and 5 millisecond values teach ordering. To size a real import, measure peak active jobs with representative files and record the time waiting in the queue separately from time spent validating. Inspect the file sizes alongside the aggregate result and count failures by cause.

Combine a job limit with resource limits

Reading two complete files into memory can still be costly. Streaming records and setting an input size limit address different constraints. This sample has no per-file deadline. If an inspection never settles, its slot stays occupied. When the underlying operation supports an abort signal, propagate it through its I/O calls before treating a deadline as freeing the slot. A Promise.race can stop waiting while the underlying operation continues. Some upstream services also cap the number of starts per second. A concurrency limit of two allows many short jobs to start in quick succession. Measure the start rate and the number of active requests separately and set both according to the upstream contract.

Choose when validated rows become durable

The function reports inspection results and leaves database writes to its caller. If all four exports constitute one batch, begin the durable import once all validations pass. With independent regional imports, a caller can commit successful files individually and store a file identity and digest with each operation. That identity helps recognize a retry after an incomplete delivery. When a progress display needs intermediate results, its notifications can use the same file identifier as the final report. Test the system with one slow file and one invalid file, then verify that the other files complete. Compare runs with one and two active inspections and confirm that outcomes remain equivalent even when resource usage and completion order change.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.