458 points · by emschwartz · 1y ago · 168 comments
Sooner or later is seems like everyone gets the idea of reducing event loop stalls in their NodeJS code by trying to offload it to another thread, only to discover they’ve tripled the CPU load in the main thread.
I’ve seen people stringify arrays one entry at a time. Sounds like maybe they are doing that internally now.
If anything I would encourage the V8 team to go farther with this. Can you avoid bailing out for subsets of data? What about the CString issue? Does this bring faststr back from the dead?
As someone who has come from a JVM/go background, I was kinda shocked how amateur hour it felt tbh.
That's what I experienced too. But I think the deeper problem is Node's cooperative multitasking model. A preemptive multitasking (like Go) wouldn't block the whole event-loop (other concurrent tasks) during serializing a large response (often the case with GraphQL, but possible with any other API too). Yeah, it does kinda feel like amateur hour.
NodeJS is intended for IO-heavy workloads. Specifically, it's intended for workloads that don't benefit from parallel processing in the CPU.
This is because Javascript is strictly a single-threaded language; IE, it doesn't support shared access to memory from multiple threads. (And this is because Javascript was written for controlling a UI, and historically UI is all handled on a single thread.)
If you need true multithreading, there are plenty of languages that support it. Either you picked the wrong language, or you might want to consider creating a library in another language and calling into it from NodeJS.
Just so. It is, or at least can be, the plurality of the sequential part of any Amdahl's Law calculation for Nodejs.
I'm curious if any of the 'side effect free' commentary in this post is about moving parts of the JSON calculation off of the event loop. That would certainly be very interesting if true.
However for concurrency reasons I suspect it could never be fully off. The best you could likely do is have multiple threads converting the object while the event loop remains blocked. Not entirely unlike concurrent marking in the JVM.
That feels the wrong way to go. I would encourage the people that have this problem to look elsewhere. Node/V8 isn't well suited to backend or the heavier computational problems. Javascript is shaped by web usage, and it will stay like that for some time. You can't expect the V8 team to bail them out.
The Typescript team switched to Go, because it's similar enough to TS/JS to do part of the translation automatically. I'm no AI enthousiast, but they are quite good at doing idiomatic translations too.
Node was literally designed to be good for one thing - backend web service development.
It is exceptionally good at it. The runtime overhead is tiny compared to the JVM, the async model is simple as hell to wrap your head around and has a fraction of the complexity of what other languages are doing in this space, and Node running on a potato of a CPU can handle thousands of requests per second w/o breaking a sweat using the most naively written code.
Also the compactness of the language is incredible, you can get a full ExpressJS service up and running, including auth, in less than a dozen lines of code. The amount of magic that happens is almost zero, especially compared to other languages and frameworks. I know some people like their magic BS (and some of the stuff FastAPI does is nifty), but Express is "what you see is what you get" by default.
> The Typescript team switched to Go, because it's similar enough to TS/JS to do part of the translation automatically.
The TS team switched to go because JS is horrible at anything that isn't strings or doubles. The lack of an int type hinders the language, so runtimes do a lot of work to try and determine when a number can be treated like an int.
JS's type system is both absurdly flexible and also limiting. Because JS basically allows you to do anything with types, Typescript ends up being one of the most powerful type systems that has seen mass adoption. (Yes other languages have more powerful type systems, but none of them have the wide spread adoption TS does).
If I need to model a problem domain, TS is an excellent tool for doing so. If I need to respond to thousands of small requests, Node is an excellent tool for doing so. If I need to do some actual computation on those incoming requests, eh, maybe pick another tech stack.
But for the majority of service endpoints that consist of "get message from user, query DB, reformat DB response, send to user"? Node is incredible at solving that problem.
I don't think it was, at least not originally, But even if it was, that doesn't mean it actually is good, and certainly not for all cases.
> Node running on a potato of a CPU can handle thousands of requests per second w/o breaking a sweat using the most naively written code.
The parent comment is specifically about this. It breaks down at a certain point.
> you can get a full ExpressJS service up and running, including auth, in less than a dozen lines of code
Ease of use is nice for a start, but usually becomes technical debt. E.g., you can write a pretty small search algorithm, but it will perform terribly. Not a problem at the start. You can set up a service with a just a little bit of code in any major language using some framework. Heck, there are code free servers. But you will have to add more and more work-arounds as the application grows. There's no free lunch.
> The TS team switched to go because JS is horrible at anything that isn't strings or doubles.
They switched because V8 is too slow and uses quite a bit of memory. At least, that's what they wrote. But that was not what I wanted to address. I was trying to say that if you have to switch, Go is a decent option, because it's so close to JS/TS.
> But for the majority of service endpoints ...
Because they are simple, as you say. But when you run into problems, asking the V8 team to bail you out with a few more hacks doesn't seem right.
Most tasks take more memory in the middle that at the beginning and end. And if you're sharing memory between processes that can only communicate by setting bytes, then the memory at the beginning and end represents the communication overhead. The latency.
But this is also why things like p-limit work - they pause an array of arbitrary tasks during the induction phase, before the data expands into a complex state that has to be retained in memory concurrent with all of its peers. By partially linearizing you put a clamp on peak memory usage that Promise.all(arr.map(...)) does not, not just the thundering herd fix.
> JSON encoding is a huge impediment to communication
I wonder how much computational overhead JSON'ing adds to communications at a global scale, in contrast to just sending the bytes directly in a fixed format or something far more efficient to parse like ASN.1.
The number of times I've gone in looking for 10%, backed out a bit and rearranged the code first to find 25%, better maintainability, and space for a feature that marketing has been bitching about for three years and development keeps insisting we cannot do in any reasonable amount of time? Probably averages out to at least three times per employer, which is a good number of miracles to perform.
One thing that improves performance for the JVM that'd be nice to see in node realm is that JSON serialization libraries can stream out the serialization. One of the major costs of JSON is the memory footprint. Strings take up a LOT more space in memory than a regular object does.
Since the JVM typically only uses JSON as a communication protocol, streaming it out makes a lot of sense. The IO (usually) takes long enough to give a CPU reprieve while simultaneously saving memory.
Why not use structuredClone to communicate with the worker? So long as your object upholds all the rules you can pass it into postMessage directly.
TypedArray is a toy. Very few domains actually work well with this sort of data. Statistics, yes. Games? Do all the time, but also games: are full of glitches used by speed runners, due to games playing fast and loose to maintain an illusion they are doing much more per second than they should be able to.
DataView is a bit better. I am endlessly amazed at how many times I managed to read people talk about TypedArrays and SharedByteArrays before I discovered that DataView exists and has existed basically forever. Somebody should have mentioned it a lot, lot sooner.
Or I guess you can do it without the WebAssembly step.
[1] https://github.com/jk-jeon/dragonbox?tab=readme-ov-file#perf...
The difference between which values are precisely representable in binary and which are precisely representable in decimal means small errors can creep in.
https://randomascii.wordpress.com/2012/02/11/they-sure-look-...
The point is that it takes application of algorithms that need to be provably correctly implemented on both ends of any JSON serialization/deserialization. And if one implantation can roundtrip its own floating point values, that's great - but JSON is an interop format, so does it roundtrip if you send it to another system and back?
It's just an unnecessary layer of complexity that binary floating point serializers do not have to worry about.
[1] https://source.chromium.org/chromium/_/chromium/v8/v8/+/5cbc...
[2] https://github.com/facebook/folly/commit/2f0cabfb48b8a8df84f...
It's a real example of "you can solve just about anything with a billion dollars" though :)
I'd prefer JavaScript kept evolving (think "strict", but "stricter", "stricter still", ...) to a simpler and easier to compile/JIT language.
It'd need a ton of buy-in from the whole community and all VM implementors to have a chance at pencilling out in any reasonable time span. Not saying I'm against it, just noting.
This is / was ASM.js, a limited subset of JS without all the dynamic behaviour which allowed the interpreter to skip a lot of checks and assumptions. This was deprecated in favor of WASM - basically communicating that if you need the strictness or performance, use a different language.
As for JS strictness, eslint / biome with all the rules engaged will also make it strict.
Although java also has the advantage of not having to be ~ real time (i.e. has a compiler)
Nail on the head; a lot of JS overhead is due to its dynamic nature. asm.js disallowed some of this dynamic behaviour (like changing the shape of objects, iirc), meaning they could skip a lot of these checks.
Hombre, you’re about the best there is.
Do we get this even if you call `JSON.stringify(data, null, 0)`? Or do the arguments literally have to be undefined?
https://microsoftedge.github.io/Demos/json-dummy-data/512KB.... Chrome 138.0.7204.184
Any idea why?
The default object property iteration rules in JS define that numeric properties are traversed first in their numeric order, and only then others in the order they were added to the object. Since the numbers need to be in their numeric, not lexical, order, the engine would also need to parse them to ints before sorting.
> JSON.stringify({b: null, 10: null, 1: null, a: null})
'{"1":null,"10":null,"b":null,"a":null}'Imagine how far we could have come if we started from a reasonable basis.
It's how we used to make websites before SPA, and it's refreshing to see that it still makes a noticeable difference even on today's powerful CPUs and high speed networks.
There's probably a lesson in there somewhere.
JSON is a great minimalist format which is both human and machine readable. I never quite understood the popularity of ProtoBuf; the binary format is a major sacrifice to readability. I get that some people appreciate the type validation but it adds a lot of complexity and friction to the transport protocol layer.
It's hard enough to not break logical compatibility, so I appreciate not having to think too hard about wire compat. You can of course solve the same thing with JSON, but, well, YOU have to solve it.
(Also worth noting, there are a lot of things I don't like about the grpc ecosystem so I don't actually use it that much. But this is one of the pieces I really like a lot).
It does seem like some technologies get credit for solving problems that they created.
It is readable but it's not a good/fast format. IEEE754<->string is just expensive even w/ all the shortcuts and improvements. byte[]s have no good way to be presented either.
I don't disagree that people go for ProtoBuf a bit too eagerly though.
Once you factor in prefetching, branch prediction, etc., a highly optimized JSON serializer should be effectively free for most real world workloads.
The part where json sucks is IO overhead when modifying blobs. It doesn't matter how fast your serializer is if you have to push 100 megabytes to block storage every time a user changes a boolean preference.
There's structuredClone (https://developer.mozilla.org/en-US/docs/Web/API/Window/stru... https://caniuse.com/?search=structuredClone) with baseline support (93% of users), but it doesn't work if fields contain DOM objects or functions meaning you might have to iterate over and preprocess objects before cloning so more error-prone, manual and again inefficient?
Svelte has `$state.snapshot()` for this reason I believe.
> On Nov 16, 2008, at 11:57 PM, Peter Michaux wrote:
> > The name "JSON.stringify" seems a little too "Web 2.0" cool to me.
> Hardly. It's hacker dictionary material, old sk00l.
> > Is there any reason a more usual and serious sounding option like "serialize" was not used?
> Ugh, Web 1.0 my-first-Java-serializable-implementation anti-nostalgia vapors.
[0]: https://web.archive.org/web/20100718152229/https://mail.mozi...
Serialize, Marshal, toString: timeless. Stringify: Trendy, gone with the winds...
I think it's less about side effects being common when serializing, just that their fast path avoids anything that could have side effects (like toJSON).
The article touches briefly on this.
That said, I see that they called it out as you say, now. When I first read it, I thought they watched for side effects.
I'm assuming they have an allow list on all standard types. The date types, in particular, often have a toJson that seems like it should still be used? (Or am I wrong on that, too? :D )
People have exploited this sort of side effect to get bug bounties before via type confusion attacks, iirc.
That getter looks inoffensive and will, depending on your requirements, work just fine. But it has side effects because the string interpolation allocates and could trigger a garbage collection.
Note that if you're using modern JS 'class' blocks a 'get x ()' will be ignored by JSON.stringify, so if you're aiming to reproduce this you have to use old-school Object.defineProperty instead.
So array list instead of array?