The Crash That Shouldn’t Have Happened
It was 3 AM on a Friday when our monitoring system blew up.
"Process terminated: FATAL ERROR: Ineffective mark-compacts near heap limit"
Our high-traffic API—processing 10,000+ JSON requests per minute—had crashed. The culprit?
A deceptively innocent JSON.parse()
call.
Here’s why it happened—and how to bulletproof your app against JSON-related crashes.
1. The Hidden Dangers of JSON.parse()
🚨 Problem #1: Malformed JSON Crashes Your App
// 💥 CRASH! Unexpected token
JSON.parse('{"bad": json}'); // Throws SyntaxError
✅ Fix: Always wrap in try/catch
.
try {
JSON.parse(potentiallyDirtyData);
} catch (err) {
// Handle gracefully
}
🚨 Problem #2: Prototype Pollution Attacks
// Malicious payload modifies prototypes!
JSON.parse('{"__proto__":{"admin":true}}');
✅ Fix: Use JSON.parse
with a reviver function or libraries like pure-json-parse
.
🚨 Problem #3: Memory Bombs (Deeply Nested JSON)
// {a:{a:{a:{...}}}} - 50,000 levels deep
JSON.parse(evilPayload); // 💥 RangeError: Maximum call stack size exceeded
✅ Fix: Limit depth with a custom parser or fast-json-parse
.
2. Why JSON.stringify()
is Just as Dangerous
🚨 Problem #1: Circular References Crash Node
const obj = { a: 1 };
obj.self = obj; // Circular!
JSON.stringify(obj); // 💥 TypeError: Converting circular structure to JSON
✅ Fix: Use flatted
or json-stringify-safe
.
🚨 Problem #2: CPU Spikes from Large Objects
// 500MB object? Enjoy 100% CPU!
JSON.stringify(hugeDataset); // Blocks event loop
✅ Fix:
-
Stream JSON with
JSONStream
. - Batch-process large datasets.
🚨 Problem #3: Unexpected toJSON()
Behavior
class User {
toJSON() { return this.privateData; } // 😱 Leaks secrets!
}
✅ Fix: Explicitly control serialization.
3. Performance Optimizations
Method | Risk | Faster Alternative |
---|---|---|
JSON.parse() |
Malformed data | fast-json-parse |
JSON.stringify() |
CPU blocking | fast-json-stringify |
Large JSON | Memory spikes | Streams (JSONStream ) |
Real-world impact: Switching to fast-json-stringify
reduced JSON ops CPU usage by 65%.
Key Takeaways
✔ Always validate/sanitize JSON input
✔ Handle circular references safely
✔ Stream large JSON instead of blocking
✔ Use optimized libs for high-throughput apps
Have you been burned by JSON ops? Share your war story!
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.