
Ask HN: Websocket/Node on local loop, why so slow? - netgusto
https://gist.github.com/netgusto/0920eda110121eb7fdb382345c7db5d2
======
netgusto
What: Node server asking 100 clients to update once per second via websocket
on a localhost loop.

Context: Server maintaining state for remote clients, clients issuing
operations to alter state (some kind of remote game loop).

Mechanics:

1\. Server broadcasts update 2\. Every client (100 clients) queries state on
server via emit api 3\. Server handles api requests and answers clients with
api response (dummy data) 4\. Client processes state, generates a state update
operation, and emits update to the server (dummy operation) 5\. Server
aggregates operation to state (dummy operation)

Why so slow ? I was kind of expecting the connections to be handled in a
parallel fashion, but it seems they're in fact processed sequentially by node.
Could that be properly parallelized somehow ?

~~~
al2o3cr
The Node server is single-threaded and multiplexes requests when they yield
control (for instance, when they make an async database call). Depending on
how realistic your "dummy operations" are, that may not be happening at all.

If you want parallelism, you'll need to add it yourself:

[http://mobilenext.net/scaling-node-js-multi-core-
systems/](http://mobilenext.net/scaling-node-js-multi-core-systems/)

~~~
netgusto
> If you want parallelism, you'll need to add it yourself

I guess that's the way to go. The article you mentioned has an interesting
demo : [https://github.com/chaudhryjunaid/multicore-
demo/blob/master...](https://github.com/chaudhryjunaid/multicore-
demo/blob/master/bin/multicore.js)

Though I'll yet have to figure out how to share the server state between the
server workers then. Thanks for your answer.

~~~
netgusto
Maybe more appropriate even than the node "cluster" in this demo is
[https://github.com/xk/node-threads-a-gogo](https://github.com/xk/node-
threads-a-gogo)

> Why threads ?

> 4.- The threads of a process share exactly the same address space, that of
> the process they belong to. Every thread can access every memory address
> within the process' address space. This is a very appropriate setup when the
> threads are actually part of the same job and are actively and closely
> cooperating with each other. Passing a reference to a chunk of data via a
> pointer is many orders of magnitude faster than transferring a copy of the
> data via IPC.

------
brudgers
This might make the basis of an interesting question on
codereview.stackexchange.com. Assuming of course that it meets all that site's
requirements.

~~~
netgusto
Didn't knew this sub-SO :) thanks !

