9 ms·
JSON encoding is a huge impediment to interprocess communication in NodeJS. Sooner or later is seems like everyone gets the idea of reducing event loop stalls
by hinkley 1y ago
JSON encoding is a huge impediment to interprocess communication in NodeJS.
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?
- jcdavis 1y agoBased off of my first ever forays into node performance analysis last year, JSON.stringify was one of the biggest impediments to just about everything around performant node services. The fact that everyone uses stringify to for dict keys, the fact that apollo/express just serializes the entire response into a string instead of incrementally streaming it back (I think there are some possible workarounds for this, but they seemed very hacky) As someone who has come from a JVM/go background, I was kinda shocked how amateur hour it felt tbh.
- MehdiHK 1y ago> JSON.stringify was one of the biggest impediments to just about everything around performant node services 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.
- Rohansi 1y agoThat's not really a Node problem but a JavaScript problem. Nothing about it was built to support parallel execution like Go and other languages. That's why they use web workers, separate processes, etc. to make use of more than a single core. But then you'll probably be dependent on JSON serialization to send data between those event loops.
- miroljub 1y ago> That's not really a Node problem but a JavaScript problem. Nowadays Node is JavaScript. They are the guys driving JavaScript standards and new features for a decade or so. Nothing prevents them from incrementally starting to add proper parallelism, multithreading, ...
- promiseofbeans 1y agoI disagree - JavaScript is the most used programming language in the world, and were I a betting man I'd happily wager client JS is still a much bigger share of that than server. Yes, there have been a lot of advances in modern JS for things like atomics and other fun memory stuff, but that's just the natrual progression for a language as popular as JS. The 3 main JS engines are still developed primarily for web browsers, and web developers are the primary audience considered in ES language discussions (although I'll concede that in recent years server runtimes have been considered more and more)
- coldtea 1y ago>I disagree - JavaScript is the most used programming language in the world, and were I a betting man I'd happily wager client JS is still a much bigger share of that than server. Clients are 90% still v8, so hardly different than Node.
- jerf 1y ago"Nothing prevents them from incrementally starting to add proper parallelism, multithreading, ..." In principle perhaps not. In practice it is abundantly clear now from repeated experience that trying to retrofit such things on to a scripting language that has been single-threaded for decades is an extremely difficult and error-prone process that can easily take a decade to reach production quality, if indeed it ever does, and then take another decade or more to become something you can just expect to work, expect to find libraries that use properly, etc. I don't think it's intrinsic to scripting languages. I think someone could greenfield one and have no more problems with multithreading than any other language. It's trying to put it into something that has been single-threaded for a decade or two already that is very, very hard. And to be honest, given what we've seen from the other languages that have done this, I'd have a very, very, very serious discussion with the dev team as to whether it's actually worth it. Other scripting languages have put a lot of work into this and it is not my perception that the result has been worth the effort.
- gwbas1c 1y ago> 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.
- MehdiHK 1y ago> If you need true multithreading I didn't say multithreading anywhere. Mutitasking (concurrency) != Multithreading. You can do pre-emptive concurrency with a single thread in other runtimes, where each task gets a pre-defined amount of CPU time slice, that solves fair scheduling for both IO and CPU-bound workloads. Nobody is supposed to pick NodeJS for CPU-bound workload, but you cannot escape JSON parse/stringify event-loop blocking in practice (which is CPU-bound).
- hinkley 1y ago> Based off of my first ever forays into node performance analysis last year, JSON.stringify was one of the biggest impediments to just about everything around performant node services 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.
- dmit 1y agoNode is the biggest impediment to performant Node services. The entire value proposition is "What if you could hire people who write code in the most popular programming language in the world?" Well, guess what
- hinkley 1y agoNodejs will never be as bad as VB was.
- jk3000 1y agoMore or less accidentally I turned a simple Excel spreadsheet into a sizable data management system. Once you learn where the bottlenecks are, it is surprising how fast VB is nowadays.
- schrodinger 1y agoLow bar!
- germandiago 1y agoI know Javascript is fast but... I cannot go with such a messy ecosystem. I find Python highly preferrable for my backend code for more or less low and middle traffic stuff. I know Python is not that good deployment-wise, but the language is really understandable, I have tools for every use case, I can easily provide bindings from C++ code and it is a joy to work with. If on top of that, they keep increasing its performance, I think I will stick to it for lots of backend tasks (except for high performance, where I have lately been doing with C++ and Capnproto RPC for distributed stuff).
- m-schuetz 1y agoIt comes down to language preferences. I find Python to be the worst thing computer science has to offer. No nested scoping in functions, variables leak through branches and loops due to lack of scopes, no classic for loops, but worst of all, installing python packages and frameworks never ever goes smoothly. I would like to love Jupyter notebooks because Notebooks are great for prototyping, but Jupyter and Python plotting libs are so clunky and slow, I always have to fall back to Node or writing a web page with JS and svg for plotting and prototyping.
- deleted 1y ago[deleted]
- brundolf 1y agoYeah. I think I've only ever found one situation where offloading work to a worker saved more time than was lost through serializing/deserializing. Doing heavy work often means working with a huge set of data- which means the cost of passing that data via messages scales with the benefits of parallelizing the work.
- hinkley 1y agoI think the clues are all there in the MDN docs for web workers. Having a worker act as a forward proxy for services; you send it a URL, it decides if it needs to make a network request, it cooks down the response for you and sends you the condensed result. 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.
- dwattttt 1y agoNow to just write the processing code in something that compiles to WebAssembly, and you can start copying and sending ArrayBuffers to your workers! Or I guess you can do it without the WebAssembly step.
- hinkley 1y agoA JSON.toBuffer would be another good addition to V8. There are a couple code paths that look like they might do this, but from all accounts it goes Object->String->Buffer, and for speed you want to skip the intermediate.
- dwattttt 1y agoI was actually imagining skipping the Object step; if you go from wire -> buffer, and only ever work on it in buffer form (i.e. in WebAssembly, in a language more amenable to working on buffers/bytes), you skip needing the Object -> JSON step. Notwithstanding whatever you need to do in the wire -> buffer step.
- hinkley 1y agoWorking with bytes in JS is still gross and I wouldn’t wish it on my worst enemy. Like I said, if you had a way to automate it, it wouldn’t be so bad.
- nijave 1y agoSame problem in Python. It'd be nice to have good/efficient IPC primitives with higher level APIs on top for common patterns
- userbinator 1y agoYou mean: > 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.
- hinkley 1y agoNo. Because painful code never gets optimized as much as less painful code. People convince themselves to look elsewhere, and an incomplete picture leads to local optima.
- hinkley 1y agoBTW, I often shorthand this as, "I'm not so much better [at optimization] as I am more stubborn." 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.
- tgv 1y ago> If anything I would encourage the V8 team to go farther with this. 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.
- com2kid 1y ago> Node/V8 isn't well suited to backend 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.
- deadbabe 1y agoWhen it comes time to do serious work in Node, that's when you start using TypedArrays and SharedArrayBuffers and work with straight binary data. stringifying is mostly for toy apps and smaller projects.
- hinkley 1y agoIf I took all the coworkers I’ve had in 30 years of coding whom I could really trust with the sort of bit fiddling array buffers, I could populate maybe two companies and everyone else would be fucked. 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.
- deadbabe 1y agoDataView has a lot of overhead. Just do it raw.
- zamalek 1y ago> 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. 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.
- hinkley 1y agoStructured clone only gets you a new object in this heap, not a new object in an isolate. You’re still doing stringify/parse under the hood every time you sendMessage.
- zamalek 1y agopostMessage uses it transparently: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage https://developer.mozilla.org/en-US/docs/Web/API/Worker/post...
- hinkley 1y agoSo I wonder if any of these improvements could be applied to structuredClone. Benchmarks aren’t showing structuredClone favorably versus JSON round tripping. Likely because JSON-compatible data structures are less complex than clonable data. I suspect with this change JSON will now be faster than structuredClone.
- zamalek 1y ago> Benchmarks aren’t showing structuredClone favorably versus JSON round tripping. Which ones? Structured clone seems to be approximately the same as FF according to this (structuredClone is slightly faster on my machine, probably margin of error): https://measurethat.net/Benchmarks/Show/23052/0/structuredclone-vs-jsonparse-jsonstringify https://measurethat.net/Benchmarks/Show/23052/0/structuredcl... (Linux: FF 141, Chromium 138).
- cogman10 1y agoIt's a major problem for JVM performance as well. Json encoding is simply fundamentally an expensive thing to do. 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.