Streaming and Validating Large NDJSON Pipelines
Stream multi-gigabyte NDJSON files line by line in constant memory, handle split chunk boundaries, isolate corrupt lines, and report row schemas.
On this page
Why Giant JSON Arrays Crash Data Pipelines
Exporting two million analytics events, LLM fine-tuning examples, or audit logs as a single [ ... ] JSON array creates an immediate memory wall. Calling await response.json() or JSON.parse(fs.readFileSync("events.json", "utf8")) loads the entire raw string into memory, allocates an object graph three to five times larger on the V8 or Python heap, and triggers sudden ERR_STRING_TOO_LONG or JavaScript heap out of memory crashes as soon as data grows past a few hundred megabytes.
Newline-Delimited JSON (NDJSON, also known as JSON Lines / .jsonl) solves both memory overhead and partial-failure resilience by storing one independent JSON object per line. Readers consume arbitrarily large streams in constant memory, HTTP APIs flush initial rows immediately as Server-Sent Events or chunked application/x-ndjson responses, and a single corrupted line never hides inside an opaque file-wide parse failure.
Before wiring an ingestion job, you can paste sample streams into the Interactive JSONL / NDJSON Inspector to detect line-numbered syntax errors, profile observed key frequencies across records, and export normalized previews locally.
Choosing NDJSON Over Alternative Streaming Formats
Engineers evaluating streaming formats often compare NDJSON against standard bracketed JSON arrays, CSV, and binary Parquet or Protobuf streams. CSV breaks cleanly whenever nested objects, optional arrays, or strings containing commas and quotes enter telemetry payloads, forcing brittle escaping rules across tools. Binary formats like Parquet excel at columnar analytics storage inside data lakes, yet lack human readability during curl or grep incident triage and require explicit schema compilation steps before downstream clients can inspect rows.
NDJSON hits a sweet spot for operational pipelines, webhook archives, and LLM evaluation datasets: every line stays self-contained UTF-8 JSON, grep and wc -l and split -l work effortlessly in shell pipelines, appending new records takes an atomic O(1) file append without rewriting closing brackets, and HTTP chunked responses flush individual rows as soon as database cursors yield them.
Handling Arbitrary Chunk Splits and Backpressure
Streaming NDJSON cleanly across network sockets or Node.js ReadableStreams requires careful state tracking around chunk boundaries. Underlying TCP packets, Web fetch buffers, and fs.createReadStream blocks slice arbitrarily at 16KB or 64KB boundaries—right in the middle of a JSON object or even mid-way through a 4-byte UTF-8 character.
The TypeScript async generator below handles three subtle transport mechanics simultaneously: TextDecoder in { stream: true } mode holds incomplete multi-byte UTF-8 bytes across reads, a carry string holds the partial tail line until \n arrives, and maxLineBytes prevents an un-delimited malicious payload from filling RAM indefinitely.
import { z } from "zod";
export interface NdjsonRecordResult<T> {
lineNumber: number;
ok: true;
data: T;
}
export interface NdjsonErrorResult {
lineNumber: number;
ok: false;
stage: "json" | "schema" | "size";
rawPreview: string;
reason: string;
}
export async function* streamValidatedNdjson<S extends z.ZodTypeAny>(
byteStream: ReadableStream<Uint8Array>,
schema: S,
options: { maxLineChars?: number } = {},
): AsyncGenerator<NdjsonRecordResult<z.infer<S>> | NdjsonErrorResult> {
const maxLineChars = options.maxLineChars ?? 1_048_576; // 1 MiB line cap
const reader = byteStream.getReader();
const decoder = new TextDecoder("utf-8", { fatal: false });
let carry = "";
let lineNumber = 0;
const parseLine = (rawLine: string): NdjsonRecordResult<z.infer<S>> | NdjsonErrorResult | null => {
const clean = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
if (clean.trim().length === 0) return null; // Skip blank trailing/empty lines
let parsed: unknown;
try {
parsed = JSON.parse(clean);
} catch (err) {
return {
lineNumber,
ok: false,
stage: "json",
rawPreview: clean.slice(0, 120),
reason: err instanceof Error ? err.message : "Invalid JSON",
};
}
const validated = schema.safeParse(parsed);
if (!validated.success) {
return {
lineNumber,
ok: false,
stage: "schema",
rawPreview: clean.slice(0, 120),
reason: validated.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "),
};
}
return { lineNumber, ok: true, data: validated.data };
};
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
carry += decoder.decode(value, { stream: true });
if (carry.length > maxLineChars && !carry.includes("\n")) {
throw new Error(`NDJSON line ${lineNumber + 1} exceeded ${maxLineChars} chars without newline`);
}
let nlIndex = carry.indexOf("\n");
while (nlIndex !== -1) {
lineNumber++;
const line = carry.slice(0, nlIndex);
carry = carry.slice(nlIndex + 1);
const result = parseLine(line);
if (result) yield result;
nlIndex = carry.indexOf("\n");
}
}
// Flush decoder remainder + final line lacking trailing \n
carry += decoder.decode();
if (carry.length > 0) {
lineNumber++;
const finalResult = parseLine(carry);
if (finalResult) yield finalResult;
}
} finally {
reader.releaseLock();
}
}
Pay close attention to the try ... finally { reader.releaseLock(); } guard and the for await (const item of streamValidatedNdjson(...)) consumption pattern. Because yield pauses inside the generator until the caller finishes awaiting a database batch insert or downstream HTTP call, natural TCP backpressure propagates automatically back to the upstream server or disk reader—keeping memory consumption completely flat whether the file holds 1,000 rows or 100,000,000 rows.
Writing NDJSON Safely and Flushing Downstream
Producing clean NDJSON requires equal discipline on the writer side, especially in Node.js streams where writing faster than disk or socket drain causes internal buffer bloat. Wait for the drain event whenever stream.write() returns false, and ensure JSON.stringify rejects non-serializable cyclic values cleanly:
import fs from "node:fs";
import { once } from "node:events";
export async function writeNdjsonBatch(
outPath: string,
records: AsyncIterable<Record<string, unknown>>,
): Promise<number> {
const out = fs.createWriteStream(outPath, { encoding: "utf8" });
let count = 0;
try {
for await (const record of records) {
const line = `${JSON.stringify(record)}\n`;
if (!out.write(line)) {
await once(out, "drain");
}
count++;
}
out.end();
await once(out, "finish");
return count;
} catch (err) {
out.destroy();
throw err;
}
}
Stream Pitfalls: UTF-8 BOM, CRLF, and Schema Drift
Keep an eye on four real-world edge cases when ingesting external NDJSON dumps:
- UTF-8 Byte Order Mark (
\uFEFF) on line 1: Files exported from Windows tools or Excel pipelines frequently prepend\uFEFFbefore the opening{on line 1, causingJSON.parse()to fail exclusively on record 1 withUnexpected token! Strip a leading\uFEFFonlineNumber === 1before parsing. - Windows
\r\n(CRLF) line endings: Splitting strictly on\nleaves a trailing\r(JSON.parsetolerates trailing\routside strings, though line length checks and raw error previews look messy unless stripped cleanly). - Pretty-printed multi-line JSON fed into an NDJSON reader: A standard formatted JSON object spanning 15 lines fails on every single line inside a line-oriented parser. Reject files starting with
[\nor{\n "immediately with a clear"Expected compact single-line NDJSON records"diagnostic rather than logging 10,000 false syntax errors. - Unchecked
carry.slice()quadratic GC churn on huge single lines: If an individual record measures 500KB and arrives in 512-byte chunks, repeated string concatenation creates churn; accumulate chunks in astring[]buffer and.join("")only when\nappears for ultra-dense workloads.
Verifying Boundary Resilience Before Shipping
Before deploying streaming ingestion workers, inspect representative logs and schema coverage in the Interactive JSONL / NDJSON Inspector, and verify five adversarial scenarios in your automated test suite alongside memory-capped soak runs:
- Feed a stream chunked at 3-byte increments across multi-byte emoji (
"🚀") and CJK characters to confirm zero\uFFFDcorruption occurs. - Verify an input file lacking a final trailing
\nstill yields its last record accurately duringdecoder.decode()flush. - Inject a broken JSON line at line 42 inside a 100-line stream and assert line 42 emits
ok: false, stage: "json"while lines 1–41 and 43–100 still validate cleanly. - Test a
2 MiBline with no\nagainstmaxLineCharsand confirm the stream aborts predictably instead of exhausting process memory. - Verify a slow consumer (
await delay(10)per batch) keeps peak RSS memory flat across 50,000 streamed records, and check that dead-letter error previews truncate oversized strings cleanly before writing to logs so a single corrupt row never floods observability storage.
FAQ
- What is the difference between NDJSON, JSONL, and standard JSON arrays?
- Standard JSON wraps items inside outer [ ... ] brackets, requiring parsers to wait for or buffer the full structure. NDJSON (Newline Delimited JSON) and JSONL (JSON Lines) place one self-contained JSON value per line separated by \n, enabling O(1)-memory streaming.
- Why must JSON strings inside NDJSON never contain raw unescaped newline characters?
- In NDJSON, literal 0x0A newline bytes act strictly as record boundaries. Any newline inside a string field must be escaped as \n (two ASCII characters) per RFC 8259, otherwise a single record splits across two broken lines.
- How should an ingestion worker react when line 48,219 out of 1,000,000 is malformed?
- Avoid aborting the entire batch or swallowing the error silently. Emit the raw failing line number and validation reason to a dead-letter channel or structured error summary while continuing downstream processing—unless the pipeline requires all-or-nothing transactionality.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.