How does Hystrix for NodeJS work despite being single threaded? - node.js

hystrixjs is an implementation of Hystrix for NodeJS.
But I'm not able to understand how it works in a single threaded js. How does it handle timing out the task?
The documentation talks about that a bit
Since this library targets nodejs application, it is by far not as
complex as the java implementation (remember... just one thread... no
concurrency, at least most of the time...). So how does it accomplish
the goals outlined above:
wraps all promise-based calls to external systems (or "dependencies") in a "Command"
Does that mean all the library is just run the promise and letting node handle the multi threading part(like network calls being handled by OS threads)?

Related

Does microservices with node.js prevent the main thread from blocking

I have just started to understand how node.js event loop and microservices works and I was wondering if microservices can prevent the main thread of node.js application from blocking. What I mean is that we can run synchronous code on a different microservice which can send the response back when done and we can scale only that instance of microservice.
Is my understanding correct or please let me know if I got something wrong?
I think you're mixing up two concepts.
Microservices are relatively small, loosely-coupled services written in whatever language. For example if I work at BigEcommerceCompany I might have a variety of microservices written in a variety of technologies to manage, such as an auth service, cart service, payments service, reviews service, etc., and they might all be in the same language or all be in different languages.
Node's event loop is single threaded, but also has a worker pool that can be used for work without blocking the event loop, and Node can also be clustered with the build in cluster module (or various wrappers) across available CPUs. An example of a blocking function call in Node would be child_process.spawnSync; an example of a non-blocking call would be child_process.spawn. It's common when writing Node code to use a lot of Promises or callbacks to avoid blocking the event loop as much as possible.
The two concepts aren't really related except in that by writing small microservices it may be easier to find, isolate, and fix problems with Node performance.

Node.js Express server: running res.render() / ejs.render() using Node.js threadpool

We have an app that uses server-side rendering for SEO purposes using EJS templating.
I am well-versed with Node.js and know that it's probably possible to tap into the Node.js threadpool for asynchronous I/O for whatever purpose you want, whether it's a good idea or a bad idea. Currently I am wondering if it is possible to run ejs.render() or res.render() with a thread in the threadpool instead of the main thread in Node.js?
We are doing a lot of heavy computational lifting in the render functions and we definitely want that off the main thread, otherwise we will be paying $$$ for more servers.
Is it just the rendering that is concerning you? There are other template engines which should produce better results; being that template rendering should be an idempotent operation, you could additionally distribute across a cluster.
V8 will compile your code to assembly and, if your not hitting any deoptimizations or getting stalled by the garbage collector, I believe you should be in the neighborhood of your network I/O limits. I would definitely recommend you try other template engines, adding a caching HTTP reverse proxy at the front and running some benchmarks first.
EJS is known to be synchronous, and that's not going to change, so basically it's an inefficient rendering engine for Node.js since it blocks the JS thread whenever it renders a view, which degrades your overall throughput, especially if your rendering is CPU heavy.
You should definitely think about some other options. E.g. https://github.com/ericf/express-handlebars
If you really have CPU-heavy computation in your webserver, then Node.js is definitely not the right tool for the job anyway. There are much better servers to handle multi-threading and parallel processing. You could just setup Node to be a controller and forward your CPU-heavy requests to a backend service/server that can do the heavy-lifting.
It would be helpful to see what kind of computation you are doing during render to provide a better answer.
Tapping into the thread-pool (which is handled by libuv) would probably be a bad idea, but it is possible of course.. you just need some C++ skills and the uv_queue_work() method of the libuv library to schedule stuff on a worker thread.
I have experimented with building a scripting engine that is run in a forked process (Read on node's child process module here). I find that to be an attractive proposition for implementing rendering engines. Yes there are issues of passing parameters (post/get query strings, session status, etc) but they are easy to deal with, especially if you use the fork option (as opposed to exec or spawn). There are standard messaging methods to communicate between the child and parent.
The only overhead is the generation of the additional instance of node (the rendering engine itself). If you are doing extensive computation in the scripting engine then this constant, the one-time per rendering request overhead of forking a new process will be minor compared to the time taken to render.
If EJS rendering blocks the main node thread, then that alone is sufficient reason NOT to use it if you are doing any significant computation during rendering.

Node's coexistance with Boost.Asio

There's a node already doing some repetitive works(like setInterval) and network event handling.
I've built another network library in C++ using Boost.Asio and want to use it from node I explained above(with node-ffi and it works well).
Here's the problem. Node has its own event dispatcher and Boost.Asio too. So, after I've invoked the above C++ library from node, because it blocked, no other node code could not be reached and didn't work anymore.
Can I make them to coexist peacefully...?
Asio's io_service::poll_one() works find in some way but there's a better solution.
node-ffi's Async Library Call is perfect for this situation. It says...
node-ffi supports the ability to execute library calls in a different
thread using the libuv library. To use the async support, you invoke
the .async() function on any returned FFI'd function.

Vertx , Node or Play for calling multiple webservice asynchrously

I am developing a project and In this project I need calling multiple concurent web services ( least 5 webservice) asynchrously.
For that , whcih framework can be used Vertx , node , or Play
thanks
In play there is too much working out of the box. Node js will be nice if you can lose some time for writing your own tools.
All of these frameworks can be used.
Disclaimer: I work on the Play framework.
Given Play's Scala heritage, even if you're using Java, we provide Promises so that you can reason the flow of making async calls without suffering from what is known as "callback-hell". You may want to consider using promises for Node also... I believe they are available. I think Vert.x may offer something there too. I'm unsure but I don't believe Node and vert.x provide promises out of the box.
You may find this page useful: http://www.playframework.com/documentation/2.2.x/ScalaWS
Play documentation is not so good. If you are thinking to implement in scala play can be good option, but for java you may not find it so great as few things are not supported in Java (Eg to write a body parser of your own you need to use scala)
Nodejs can be a good choice however, in nodejs utilizing all the cpu cores is hard. There is a framework jxcore which claims to have a solution for this, but, I have not used it.
Vert.X IMO can be a good framework, it makes good use of all cpu cores, provides N event loops. Optionally, you can use worker thread pool if you really need to do cpu intensive operation and be responsive.
You can use vertx with RxJava module ( https://github.com/vert-x/mod-rxvertx ). You can combine your async results in anyway you want. rxvertx module supports wrappers for EventBus, HttpServer, HttpClient, NetServer, NetClient and Timer.

Instances where Node.js operations need to be synchronous

JavaScript is single-threaded (besides web workers and spawning multiple processes), and it's best not to wait for long-running operations as it blocks the thread. But still, when taking a peek into several modules in Github, they actually use these syncrhonous operations, most of the time in file operations.
Am I staring at bad code/practice? Or is there some real need for synchronous operations in JavaScript that I am not aware of?
Can you post an example? You are most likely looking at:
a call that is actually asynchronous such as fs.read. Note that all synchronous calls in the node core API end with the word "Sync" like fs.readSync.
synchronous code such as require('somemodule') that runs before the application begins accepting network requests
And yes, if you are seeing code doing something like fs.readSync while responding to an HTTP request, that is bad code/practice and that application will lock up while that synchronous operation happens.
Node.js it's not single-threaded, uses a pool of threads but they are exposed as a single thread to the javascript layer, otherwise would be impossible to write asynchronous code. Any I/O call blocks the current thread.
Threads are used internally to fake the asynchronous nature of all the
system calls. libuv also uses threads to allow you, the application,
to perform a task asynchronously that is actually blocking, by
spawning a thread and collecting the result when it is done.
http://nikhilm.github.com/uvbook/threads.html
Node.js has decided to include synchronous functions to maintain a similitude with other common languages, but they shouldn't be used, never, never, never!
Node.js in its nature is asynchronous, it's pure javascript. Javascript is synonym of closure, of callback. If you want to write synchronous code with Node.js perhaps you should try another scripting language like python.
There's an excellent module called async that eases the pain of nested callbacks. Then, why should I use synchronous code? Silly. If I use synchronous code I lose all the benefits that Node provides to me. The only exception are CLI apps, but again, I'll prefer to write all the code asynchronously. It's not really hard.
At some level, a synchronous operation has to occur. Node.js puts those in threads so that the whole server isn't blocked.

Resources