Four uploads that took minutes: linear-time parsers
Short answer. A regex is quadratic on an upload when it can scan to the end of the file from every place it starts. <!--[\s\S]*?--> does that from every unterminated <!--, a tag pattern built on [^>]* does it from every < with no >, and \s*X$ does it from every space in a long run. The fix is the same each time: make every pattern stop at the next delimiter, or replace it with an indexOf walk. Then write a test that feeds the worst case and fails if it takes seconds instead of milliseconds.
This is the batch of four I fixed in KhataGO's back office in December: three parsers and one matcher, every one of them fed by a file a signed-in shop uploads.
What the review found
KhataGO takes three kinds of upload: a Tally XML export of outstanding bills, a CSV of dues, and the GSTR-2B the GST portal publishes for a business (plus the shop's own purchase register to compare it with). The import limit is 2 MB (MAX_IMPORT_BYTES in lib/import/index.ts) and the GSTR-2B upload limit is 4 MB (MAX_UPLOAD_BYTES).
A security review of those paths found that the size limit bounded the bytes and nothing bounded the work. The commit that fixed the parsers (9fb4125) puts it in one sentence: a few hundred KB pinned one CPU for 5–60 s, and a full 2 MB or 4 MB file for minutes. On a serverless function that is a timeout. On a shared instance, every other request waits behind it.
Nothing here needed a hostile regex expert. The inputs that trigger it are boring: one marker repeated, never closed.
1. Comments and CDATA in the Tally XML
The Tally importer is a lenient tokenizer, not a validating XML parser, because Tally writes control characters a strict parser refuses. Before tokenizing it stripped comments and unwrapped CDATA:
const body = text
.replace(/<!--[\s\S]*?-->/g, "")
.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, (_, c) => escape(c));
A lazy quantifier looks cheap: it stops at the first -->. But when there is no -->, it does not stop until the end of the input, and then the engine moves one character on and tries again. A file of 60,000 copies of <!-- starts that scan at every one of them. That is O(n) work from each of O(n) starts.
The fix drops the regex for an indexOf walk that keeps the old behaviour, including leaving an unterminated opener as written:
function replaceBetween(text: string, open: string, close: string,
replace: (inner: string) => string): string {
let out = "";
let from = 0;
for (;;) {
const start = text.indexOf(open, from);
if (start < 0) break;
const end = text.indexOf(close, start + open.length);
if (end < 0) break; // unterminated: stop looking, keep the rest as is
out += text.slice(from, start) + replace(text.slice(start + open.length, end));
from = end + close.length;
}
return out + text.slice(from);
}
The break on a missing close is what makes it linear. Once there is no --> after one opener, there is none after any later opener either, so there is nothing left to look for.
2. The tag tokenizer
The tokenizer itself was one global regex:
const TAG = /<(\/?)([A-Za-z_][\w.:-]*)[^>]*?(\/?)>/g;
It had two separate quadratic cases.
The first is <a <a <a … with no > anywhere. [^>]*? excludes > but not <, so from each < it reads on through every later tag to the end of the file before giving up. Same shape as the comments.
The second needs only one <: <a followed by 400,000 letters and no >. The name [\w.:-]* and the attributes [^>]*? can both match letters, so when the final > fails the engine backtracks the name one character shorter and lets the attributes try again, and again, once for every split point. That is quadratic from a single start.
The replacement fixes both:
// The name is taken whole (lookahead + backreference: no backtracking into it),
// and a tag ends before the next `<`.
const TAG = /<(\/?)(?=([A-Za-z_][\w.:-]*))\2([^<>]*)>/g;
JavaScript has no atomic groups, but a lookahead followed by a backreference to what it captured behaves like one. The lookahead matches the longest name, and \2 then consumes exactly that text. If the rest of the pattern fails, the engine cannot backtrack into a lookahead, so there is no other split of the name to try. And [^<>]* stops at the next <, so a failed tag costs only the text up to the next one. The self-closing check moved out of the regex into attributes.endsWith("/").
The header lookup (company name and report period, read before the import so the shop can see which file it is) had the first problem too: <SVTODATE[^>]*>, with 40,000 copies of <SVTODATE, scanned to the end from each one. The fix was one character class: [^<>]*.
3. A trim() per quote in the dues CSV
This one was not a regex. The CSV parser is a hand-written RFC 4180 state machine, and it decided whether a " opened a quoted cell like this:
if (ch === '"' && cell.trim() === "") {
quoted = true;
cell = "";
} else {
cell += ch;
}
A quote only opens a cell if nothing but whitespace came before it. Otherwise it is a literal character and gets appended. So a cell of a followed by 400,000 quotes appends each quote and calls trim() on the whole cell first, every time. The cell grows by one each step, so the trims add up to n²/2 characters read.
The fix keeps the answer to "is the cell still blank?" as the cell is built, instead of asking the cell again:
let blank = true;
const add = (s: string) => {
cell += s;
if (blank && s.trim() !== "") blank = false;
};
// …
if (ch === '"' && blank) { quoted = true; reset(); }
Each trim() now runs on one character. The rule I took from it is the same as for the regexes: any per-character step that reads the whole accumulated value is a loop inside a loop.
4. \s*(dr|cr)$ on a GSTR-2B amount
The GSTR-2B amount reader turns cells like ₹ 1,12,000.10 Dr into exact paise. One line stripped the debit/credit suffix:
.replace(/\s*(?:dr|cr)\.?$/i, "")
.replace(/[,\s]/g, "");
On 1, a run of spaces, then 2, the engine starts at the first space, lets \s* take the whole run, fails to find dr or cr, backs off one space at a time, fails each time, then starts again at the second space. A run of k spaces costs about k²/2 steps. The test comment records 80,000 spaces taking about 9 seconds.
The leading \s* did nothing useful: the very next line removes every space anyway. Deleting it was the whole fix:
// No leading `\s*`: every space goes on the next line anyway.
.replace(/(?:dr|cr)\.?$/i, "")
Two new rows in the existing table test pin the behaviour that could have changed: 500 Cr. (two spaces and a dot) and 500cr (no space) both still read as 50,000 paise.
5. The GSTR-2B matcher was n×m
The fourth problem was found in the same pass but is a different kind: an algorithm, not a pattern. Commit 89a475a.
The matcher compares the shop's purchase register with the GSTR-2B and sorts documents into buckets: matched, not in 2B, not in books, and so on. Its second pass suggests probable pairs, such as the same supplier with an invoice number one edit away and equal amounts. A probable pair is never accepted automatically; a person decides.
That pass scored every unmatched books document against every 2B document and kept every scored pair in one array, then sorted it. Both sides are uploads, and each may hold up to 20,000 documents (MAX_DOCS_PER_SIDE). One supplier on both sides with equal amounts and dates is up to 400 million pair objects. The commit message has the measurement: 2,000 documents a side, about 240 KB of JSON, already took 26 s and 310 MB. At the 20,000 cap it would run out of memory.
Two changes, both in lib/gst2b/match.ts:
- Compare only what can score.
probableScorereturns nothing for documents from different suppliers or of a different kind, so the pass now groups 2B documents by supplier GSTIN and kind and looks only inside the group. - Same greedy, no pairs array. The old order was "sort all pairs by score descending, then books order, then 2B order, take each pair whose two sides are still free". That is the same as: for each score from best to worst, walk the books in order and give each one its first free 2B document at that score. No pair is ever stored.
Grouping does not help when one supplier really is most of both files, so there is also a cap. The pass counts its comparisons before it starts and does nothing when they exceed MAX_PROBABLE_COMPARISONS (2,000,000). Trimmed:
const comparisons = probing.reduce((n, p) => n + p.pool.length, 0);
if (comparisons <= MAX_PROBABLE_COMPARISONS) {
for (const score of [3, 2, 1]) {
for (const { b, pool } of probing) {
if (pairedBooks.has(b)) continue;
const t = pool.find(t => !usedTwoB.has(t) && probableScore(doc(b), twoB[t], tol) === score);
if (t !== undefined) { pairedBooks.add(b); usedTwoB.add(t); push(/* PROBABLE */); }
}
}
}
Above the cap, those documents stay in the "in books, not in 2B" and "in 2B, not in books" buckets. I chose that degradation on purpose. A probable pair is a suggestion a person still has to confirm, so losing the suggestion costs some review time, while losing the whole response costs the shop the page. The cap and what happens above it are written down in the back office's own design notes next to the bucket table.
The tests that time each case
A performance fix without a test comes back the first time someone "simplifies" a regex. Each case above has a test that builds the worst-case input, checks it is under the real upload limit, and fails if parsing takes too long. From tests/lib/importParsers.test.ts:
describe("parsing an upload takes linear time", () => {
const LINEAR_MS = 2500;
const timed = async (text: string) => {
const bytes = new TextEncoder().encode(text);
expect(bytes.length).toBeLessThan(MAX_IMPORT_BYTES);
const started = performance.now();
await parseImportFile(bytes).catch(() => undefined);
return performance.now() - started;
};
it("Tally XML: unterminated comments", async () => {
expect(await timed(`<ENVELOPE>${"<!--".repeat(60_000)}`)).toBeLessThan(LINEAR_MS);
});
it("Tally XML: tags that never close", async () => {
expect(await timed(`<ENVELOPE>${"<a ".repeat(40_000)}`)).toBeLessThan(LINEAR_MS);
expect(await timed(`<ENVELOPE><a${"b".repeat(400_000)}`)).toBeLessThan(LINEAR_MS);
});
it("CSV: one cell of quotes", async () => {
expect(await timed(`a${'"'.repeat(400_000)}`)).toBeLessThan(LINEAR_MS);
});
// …unterminated CDATA, a header variable that never closes
});
The amount reader has the same kind of test with 200,000 spaces and a one-second bound. The matcher test runs 1,000 documents a side (all 1,000 come back as probable pairs, under five seconds), then a size just over the cap (zero probable pairs, every document in the two "not in" buckets, also under five seconds).
Three things make these tests worth having rather than flaky:
- The bound sits between the two complexities, far from both. The linear parse of these inputs takes milliseconds; the quadratic one took seconds to minutes. A bound of a couple of seconds tolerates a slow CI runner without letting the old code through.
- Each test fails when its own fix alone is reverted. I checked that per fix, not for the batch. A timing test that passes against the code it is meant to catch is decoration; I have written that test before, and the post about it is the reason I check now.
- A second test proves the output did not change. A new tokenizer test reads attributes, a self-closing tag, CDATA holding
&and<, and a comment that contains a tag. It passes on the old code too. That is the point: the speed changed, the answers did not. The matcher got the same treatment, an ordering test (best score first across the books) that passes before and after.
What to look for in your own parsers
For each pattern that runs over uploaded text, ask what it does when its closing delimiter never comes. If the answer is "reads to the end of the input", multiply by the number of places it can start. [\s\S]*?, .* and any negated class that does not exclude the opening character are the usual suspects.
Look for two quantifiers that can match the same characters next to each other, like a name followed by attributes that both accept letters. That is the single-start blow-up, and in JavaScript the lookahead-plus-backreference trick removes it.
Look for any step inside a per-character loop that reads the whole value built so far: trim(), includes(), split(), a regex over the buffer.
And when two uploads meet, count the pairs. A size limit on each file says nothing about the product of the two.
Exact paise and Indian number formatting in the same code path are their own post: formatting rupees in JavaScript.