Home / Articles

Million-row Excel imports in Node without a memory spike

A practical Node design for million-row Excel imports: stream each row, report every bad line, stage before a single commit, and keep memory flat when the database slows down.

Publisher: REACTAPP.TOP15 min read3478 words

This article is published in English.

Sources: Beyond File Uploads: Building Scalable Data Import Pipelines in Node.js

A product that takes spreadsheet uploads has to do more than store a file. The interesting problems show up once the workbook is large.

You have to:

  • open an Excel file
  • parse the rows into records
  • check every record against the business rules
  • keep passing rows apart from failing ones
  • accept the whole import or refuse it, according to the policy you were given
  • save the failures in a form the uploader can read
  • scan the file for viruses and other malicious content
  • write the accepted data into the database
  • survive dropped connections, retries, and failures you did not schedule

The file you must support holds 1 million records.

At that size, a careless design will exhaust memory, flood the database, or commit part of the import and then die. Those three outcomes are the problem to design against.

One workable answer is a background pipeline built around Node streams, pipeline(), transforms, and backpressure, with the architectural choices written down the way a design note would write them: scope, goals, numbers, the pipeline, the failures, and the options you turned down. The samples all run.

What is in scope

People upload an Excel file. A row is stored only once the business rules accept it.

The ceiling is a million rows. You accept the import or you refuse it, you name each failed row and the reason, and a half-applied import must not remain in the database.

It begins when the upload shows up and finishes when the records are committed. The UI is out of scope. So are the business rules themselves.

Goals, and what you are not doing

Goals:

  • Heap that stays about flat no matter how large the workbook is
  • A check on every row, and a report of every failure, rather than a stop at the first error
  • Commits that are all or nothing: the live tables receive the full import, or they receive none of it
  • A resume after a crash that does not insert the same record a second time
  • A malware scan that finishes before any parser opens the file
  • A status the uploader can poll while the job is still running

Not in scope:

  • Finishing the import before you answer the upload request
  • Repairing invalid cells on the user's behalf
  • Outrunning what the database can safely absorb
  • Workbooks that contain more than one sheet

How large the file gets

The first design question is how big the input becomes.

The simplest plan loads the whole workbook into an array. Here is the heap cost of 1 million rows, before any row is checked:

// naive.mjs — run with: node naive.mjs
const rows = [];
for (let i = 1; i <= 1_000_000; i++) {
  rows.push({ row: i, email: `user${i}@example.com`, amount: i % 500 });
}
const mb = Math.round(process.memoryUsage().heapUsed / 1024 / 1024);
console.log(`${rows.length} rows, ${mb} MB of heap`);1000000 rows, 133 MB of heap

Three short fields on each row already occupy 133 MB.

Sheets you actually receive are wider. The same row count, with 10 text columns:

// wide.mjs — run with: node wide.mjs
const rows = [];
for (let i = 1; i <= 1_000_000; i++) {
  const row = { row: i };
  for (let c = 1; c <= 10; c++) row[`col${c}`] = `value-${c}-${i}`;
  rows.push(row);
}
const mb = Math.round(process.memoryUsage().heapUsed / 1024 / 1024);
console.log(`${rows.length} rows x 10 columns, ${mb} MB of heap`);1000000 rows x 10 columns, 723 MB of heap

Three numbers come out of that, and they shape everything after:

  • Memory. Ten columns put one import at 723 MB before parser overhead. Three uploads at the same time pass 2 GB. Heap has to stop growing with the file.
  • Writes. A million inserts of a single row means a million trips to the database and back. Group 1000 rows into each statement and you send 1000 statements.
  • Time. Suppose one batch insert costs 50 ms. That figure is assumed, not measured. A thousand batches then spend 50 seconds on inserts alone. Parsing, the rule checks, and the malware scan sit on top of that, so this work cannot live inside an HTTP request.

Two processes

A small API takes the file. A worker does the costly steps later, so a million rows never occupy the request for the whole job.

  1. Upload API. Stream the body to storage, insert an imports row, enqueue work, answer 202 Accepted and the import id.
  2. File storage. Keeps the original workbook. Local disk here. In production, use object storage. S3 is the usual bucket.
  3. Job queue. Delivers each import to a worker. BullMQ, sitting on Redis, fits Node.
  4. Import worker. Malware check, parse, rules, batches, staging, then commit or refuse.
  5. Database. imports holds status and the checkpoint. staging holds rows not yet live. records is the live table.
  6. Error report. Each rejected row, plus the reason, so the uploader can correct the sheet.

Statuses run uploaded, then scanning, then importing, then completed. Malware in the scan sets rejected. Too many bad rows during import also sets rejected. Any status can become failed, and a retry continues from the saved checkpoint.

uploaded → scanning → importing → completed
                    ↘ rejected    ↘ rejected
                      (malware)     (too many invalid rows)
any state → failed (retried from the last checkpoint)

Two routes. POST /imports answers 202 with { id, status: "uploaded" }. GET /imports/:id answers 200 with { id, status, ... }.

POST /imports        → 202 { id, status: "uploaded" }
GET  /imports/:id    → 200 { id, status, ... }

Putting the file on disk

The handler places bytes on disk and does not buffer the body.

req is already readable. Pipe it into a file write stream.

// api.mjs — run with: node api.mjs
import { createServer } from 'node:http';
import { createWriteStream } from 'node:fs';
import { unlink } from 'node:fs/promises';
import { pipeline } from 'node:stream/promises';
import { randomUUID } from 'node:crypto';

const imports = new Map(); // stands in for the `imports` table

createServer(async (req, res) => {
  const json = (code, body) =>
    res.writeHead(code, { 'content-type': 'application/json' }).end(JSON.stringify(body));

  if (req.method === 'POST' && req.url === '/imports') {
    const id = randomUUID();
    try {
      await pipeline(req, createWriteStream(`${id}.xlsx`)); // straight to disk
    } catch {
      await unlink(`${id}.xlsx`).catch(() => {}); // client gave up mid-upload
      return json(400, { error: 'upload interrupted' });
    }
    imports.set(id, { id, status: 'uploaded' });
    // queue.add('import', { id }): a worker takes it from here
    return json(202, imports.get(id));
  }
  const job = req.method === 'GET' && imports.get(req.url.split('/imports/')[1]);
  return job ? json(200, job) : json(404, { error: 'not found' });
}).listen(3000, () => console.log('listening on :3000'));$ curl -X POST localhost:3000/imports --data-binary @records.xlsx
{"id":"d30d89c0-9adf-4be1-b207-29d5ac181b38","status":"uploaded"}
$ curl localhost:3000/imports/d30d89c0-9adf-4be1-b207-29d5ac181b38
{"id":"d30d89c0-9adf-4be1-b207-29d5ac181b38","status":"uploaded"}

The sample uses a raw body so the listing stays small. A browser form posts multipart/form-data, parsed by busboy as a stream. A presigned URL into the bucket skips this handler.

Rows as a stream

A stream feeds data through in chunks. A stage keeps only the chunk it is working on.

Node gives you three stage types:

  • Readable: where the rows originate
  • Transform: edits a row on the way through
  • Writable: where the rows land

pipeline() wires those stages together, propagates an error, and tears the chain down if one of them fails.

The worker reads the workbook a single row, then the next. Install with npm i exceljs, then use the streaming reader from the exceljs repo.

// excel.mjs — needs: npm i exceljs, and a records.xlsx with columns email, amount
import ExcelJS from 'exceljs';

async function* readExcel(path) {
  const workbook = new ExcelJS.stream.xlsx.WorkbookReader(path);
  for await (const sheet of workbook) {
    for await (const row of sheet) {
      if (row.number === 1) continue; // skip the header row
      const [, email, amount] = row.values; // values[0] is always empty
      yield { row: row.number, email, amount };
    }
    break; // first sheet only: 1 million rows fit on one sheet
  }
}

for await (const record of readExcel('records.xlsx')) console.log(record);

Only the first sheet is read. The limit is intentional: one worksheet per file. A worksheet tops out at 1048576 rows, which covers a million records.

Tests pushed the same limit. exceljs 4.4.0 mishandled small two-sheet workbooks that exceljs itself had written. Roughly one attempt in seven threw. The rest dropped sheet two and raised no error. The outcome followed how those internal parts were ordered. Files Excel had saved were never included, so one sheet stays out of that mess. Row numbers reset when a new sheet starts, and the staging key contains that number, so a second sheet would clash. A single sheet removes the crash, the missing sheet, and the clash.

Checking rows without dropping them

Validation is a Transform. A bad row is not discarded. Errors ride along on the record. Without that, a report of every failure is impossible.

A generator replaces the workbook so the sample needs no xlsx file:

// stream.mjs — run with: node stream.mjs
import { Readable, Transform, Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';

function* fakeRows(total) {
  for (let i = 1; i <= total; i++) {
    const email = i % 1000 === 0 ? 'not-an-email' : `user${i}@example.com`;
    yield { row: i, email, amount: i % 500 };
  }
}

const validate = new Transform({
  objectMode: true,
  transform(record, _enc, done) {
    const errors = [];
    if (!/^\S+@\S+\.\S+$/.test(record.email)) errors.push('invalid email');
    if (record.amount < 0) errors.push('negative amount');
    done(null, { record, errors });
  },
});

let valid = 0, invalid = 0;
const count = new Writable({
  objectMode: true,
  write({ errors }, _enc, done) {
    errors.length ? invalid++ : valid++;
    done();
  },
});

await pipeline(Readable.from(fakeRows(1_000_000)), validate, count);
const mb = Math.round(process.memoryUsage().heapUsed / 1024 / 1024);
console.log({ valid, invalid, heapMB: mb });{ valid: 999000, invalid: 1000, heapMB: 19 }

Same three fields as the in-memory array. A million of them use 19 MB, not the 133 MB the array needed. The printout is 999000 valid and 1000 invalid, because each 1000th address is not-an-email and the transform labels it invalid email. An amount below zero would be labeled negative amount. The row still continues.

Failures on disk, one line each

Invalid rows go out as NDJSON, a single JSON object on its own line. The file may grow without a bound, and none of that text has to sit in the heap.

When the file buffer fills, write() returns false. Wait for 'drain' before you accept another row.

// report.mjs — run with: node report.mjs (writes errors.ndjson)
import { createWriteStream } from 'node:fs';
import { Writable } from 'node:stream';

const report = createWriteStream('errors.ndjson');

const errorReport = new Writable({
  objectMode: true,
  write({ record, errors }, _enc, done) {
    if (!errors.length) return done(); // valid rows go elsewhere
    const line = JSON.stringify({ row: record.row, errors }) + '\n';
    if (report.write(line)) done();
    else report.once('drain', done); // the file is busy: wait
  },
  final(done) { report.end(done); },
});

errorReport.write({ record: { row: 1000 }, errors: ['invalid email'] });
errorReport.end();

What lands in errors.ndjson:

{"row":1000,"errors":["invalid email"]}

Skip that 'drain' wait and the report is what fills memory.

When the database is the slow stage

Producing rows is quick. Persisting them is not.

Leave the reader running while inserts lag, and unread rows stack up in RAM.

The name for that pause is backpressure. The slow stage asks everything ahead of it to stop. Each stream keeps a short buffer called highWaterMark. Object mode defaults that buffer to 16 objects. A full buffer stops the previous stage until room returns.

You get this from pipeline() only when done() runs after that chunk's work is actually finished.

One Transform gathers 1000 rows, then emits them. The writer below delays on purpose so it can play the database. It consumes 200000 rows and waits 5 ms on every batch, standing in for an insert of many values.

// backpressure.mjs — run with: node backpressure.mjs
import { Readable, Transform, Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { setTimeout as sleep } from 'node:timers/promises';

let read = 0, saved = 0, maxInFlight = 0;

function* rows(total) {
  for (let i = 1; i <= total; i++) { read++; yield { row: i }; }
}

const batch = (size) => {
  let buf = [];
  return new Transform({
    objectMode: true,
    transform(row, _enc, done) {
      buf.push(row);
      if (buf.length === size) { this.push(buf); buf = []; }
      done();
    },
    flush(done) { if (buf.length) this.push(buf); done(); },
  });
};

const slowDb = new Writable({
  objectMode: true,
  async write(rows, _enc, done) {
    await sleep(5); // pretend this is INSERT ... VALUES (...1000 rows)
    saved += rows.length;
    maxInFlight = Math.max(maxInFlight, read - saved);
    done();
  },
});

await pipeline(Readable.from(rows(200_000)), batch(1000), slowDb);
console.log({ read, saved, maxInFlight });{ read: 200000, saved: 200000, maxInFlight: 31016 }

maxInFlight records the highest number of rows read and not yet stored. That run shows 31016. Repeating it on a million rows shows 31016 again. The reader blocked on the writer. Buffer sizes set the memory ceiling. File length does not.

Stage, then commit once

Accepting the whole file or refusing it forces a bigger change than any other requirement.

Finding one fatal row at index 999999 is useless if earlier rows already sit in the live tables.

The worker therefore skips the live table until the end. Pending rows go to staging, with a key of (import_id, row_no). Every batch also updates a checkpoint. Live rows change once, inside a single transaction, after the file has a verdict. Until then, good rows sit in staging and bad rows are only in the report.

SQLite shipped with Node keeps the sample portable. DatabaseSync needs Node 22.5 or newer. ON CONFLICT DO NOTHING is in the inserts, and that same SQL runs on Postgres.

// staging.mjs — run with: node staging.mjs (Node 22.5+, built-in SQLite)
import { DatabaseSync } from 'node:sqlite';

const db = new DatabaseSync(':memory:');
db.exec(`
  CREATE TABLE records (email TEXT, amount INTEGER);
  CREATE TABLE imports (id TEXT PRIMARY KEY, status TEXT, last_batch INTEGER DEFAULT -1);
  CREATE TABLE staging (import_id TEXT, row_no INTEGER, email TEXT, amount INTEGER,
                        PRIMARY KEY (import_id, row_no));
`);
const stage = db.prepare('INSERT INTO staging VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING');
const checkpoint = db.prepare('UPDATE imports SET last_batch = ? WHERE id = ?');

function saveBatch(importId, batchNo, rows) {
  db.exec('BEGIN'); // rows and checkpoint land together, or not at all
  for (const r of rows) stage.run(importId, r.row, r.email, r.amount);
  checkpoint.run(batchNo, importId);
  db.exec('COMMIT');
}

function commitImport(importId) {
  db.exec('BEGIN'); // the only moment the real table changes
  db.prepare('INSERT INTO records SELECT email, amount FROM staging WHERE import_id = ?').run(importId);
  db.prepare('DELETE FROM staging WHERE import_id = ?').run(importId);
  db.prepare("UPDATE imports SET status = 'completed' WHERE id = ?").run(importId);
  db.exec('COMMIT');
}

To refuse an import, remove its staging rows, mark it rejected, and return the error file.

The case to watch is a crash in the middle, then another attempt.

// ...continues staging.mjs: a crash, then a retry
const SIZE = 1000;
const rows = Array.from({ length: 10_000 }, (_, i) =>
  ({ row: i + 1, email: `user${i + 1}@example.com`, amount: i % 500 })); // stands in for the stream
const count = (t) => db.prepare(`SELECT COUNT(*) AS n FROM ${t}`).get().n;

function runImport(importId, crashAt = Infinity) {
  const { last_batch } = db.prepare('SELECT last_batch FROM imports WHERE id = ?').get(importId);
  for (let b = last_batch + 1; b * SIZE < rows.length; b++) {
    if (b === crashAt) throw new Error(`worker crashed before batch ${b}`);
    saveBatch(importId, b, rows.slice(b * SIZE, (b + 1) * SIZE));
  }
  commitImport(importId);
}

db.prepare("INSERT INTO imports (id, status) VALUES ('imp-1', 'importing')").run();
try { runImport('imp-1', 4); } catch (err) { console.log(err.message); }
console.log('after crash:', { records: count('records'), staged: count('staging') });

saveBatch('imp-1', 3, rows.slice(3000, 4000)); // replaying a batch is harmless
runImport('imp-1'); // the retry picks up at batch 4
console.log('after retry:', { records: count('records'), staged: count('staging') });worker crashed before batch 4
after crash: { records: 0, staged: 4000 }
after retry: { records: 10000, staged: 0 }

After the crash the live table still has nothing from this import: 0 records and 4000 staged. That is four batches of 1000, halted before batch 4. The next attempt jumps over those four. Writing batch 3 a second time adds no rows. You end at 10000 records, with staging cleared.

The file is untrusted

Treat every uploaded spreadsheet as hostile input.

  • Parse only after a scan. Before opening the workbook, the worker passes the stored bytes to ClamAV, or to another scanner. Malware means status rejected. The parser is never called.
  • Stop oversized uploads early. Refuse anything above a fixed limit in the API, or the body will fill the disk.
  • Ignore the filename. Workbooks that end in .xlsx are ZIP archives. Expect those bytes to begin with PK, the ZIP magic. A matching name says nothing about the content.
  • Do not let cells become SQL. Rules decide which values pass. Values that are stored go in as bound parameters, matching staging.mjs.

A result for each failure

Pick the outcome before the failure shows up.

  • Upload dropped halfway. The pipeline() call fails. Delete the incomplete file. Do not enqueue a job.
  • Malware found. Set rejected and skip parsing.
  • Invalid rows over the threshold. Remove that import from staging, set rejected, and give the error file back.
  • Inserts get slow. Hold the reader to the writer's speed so the heap does not climb.
  • Process dies, or a deploy restarts it. The queue runs the job again from last_batch. A batch already stored changes nothing, because the staging primary key blocks the duplicate.
  • Database unreachable. Fail the job. A later attempt continues at the checkpoint already saved.

Options that lost

  • Materialize the workbook in an array. Dropped. RAM tracks file size, and ten columns on a million rows already means 723 MB.
  • One INSERT per row. Dropped. You would pay for a million separate round trips.
  • Keep one transaction open on the live table for the whole file. Dropped. It stays open the entire time, and dying at row 999999 rolls everything back to the start.
  • Write live rows immediately and delete them on reject. Dropped. While the import is unfinished, someone else can read rows that may disappear.
  • Finish inside the request handler. Dropped. The HTTP call times out, and a deploy aborts any import still running.
  • Dump CSV and load it with Postgres COPY. Parked for later, not dropped forever. Nothing loads rows faster, yet a clear error for each bad row becomes awkward to produce. Pick it up again if writes dominate the clock.

What the runs printed

Figures from a single machine running Node 26. Heap readings wander by a few MB each time you repeat a run.

  • Three columns, whole array: a million rows occupy 133 MB of heap
  • Ten columns, whole array: 723 MB
  • A million rows streamed through validation: 19 MB, on generated rows, with Excel parsing left out
  • Slow writer, rows held but not saved: the peak was 31016, identical at 200000 rows and at a million
  • Kill and resume: nothing from this import in the live table after the kill, 10000 after the resume, and no row twice

How much you hold at once

Receiving the upload is the simple half.

What you still have to build is the pipeline:

  • read row by row instead of materializing the sheet
  • allow a slow writer to stall the reader
  • group the inserts
  • mark bad rows and leave them in the stream rather than dropping them
  • keep rows in staging, save a checkpoint per batch, then accept or refuse the whole set together
  • run the scanner before the parser, and keep the work off the request

Those choices all answer the same question.

How much data is in memory at the peak?

When the peak tracks the workbook, some future upload will be large enough to break the process.

When the peak is just the stream buffers, file size is no longer what takes the process down.