node.js - Can two http request come together? If it can, how nodeJS server handles it? -
yesterday giving presentation on nodejs. 1 asked me following question:
as know nodejs single threaded server, several request coming server , pushes request event loop. if 2 request coming server @ exact same time, how server handle situation?
i guessed thought , replied following:
i guess no 2 http request can come server @ exact same time, request come through single socket in queue. http request has following format:
timestamp of request contained in it's header , may pushed event loop depending upon timestamp in header.
but i'm not sure whether gave him right or wrong answer.
i guess no 2 http request can come server @ exact same time, request come through pipe in queue.
this part correct. incoming connections go event queue , 1 of them has placed in queue first.
what if 2 request coming 2 server @ exact same time, how server handle situation?
since server listening incoming tcp connections on single socket in single process, there cannot 2 incoming connections @ same time. 1 processed underlying operating system before other one. think of way. incoming connection set of packets on network connection. 1 of incoming connections have packets before other one.
even if had multiple network cards , multiple network links 2 incoming connections literally arrive @ server @ exact same moment, node.js queue guarded concurrency mutex , 1 of incoming connections grab mutex before other , put in event queue before other.
the 1 processed os first put node.js event queue before other one. when node.js available process next item in event queue, whichever incoming request first in event queue start processing first.
because node.js js execution single threaded, code processing request run synchronous code completion. if has async operation, start async operation , return. allow next item in event queue processed , code second request start running. run synchronous completion. first request, if has async operation, start async operation , return.
at point after both requests have started async operations , returned, event queue. when 1 of async operations finishes, post event event queue , when single thread of node.js free, again process next item in event queue. if both requests have lots of async operations, progress interleave , both "in-flight" @ same fire async operation , return until async operation completes processing picks again when node.js free process next event.
timestamp of request contained in it's header , may pushed event loop depending upon timestamp in header.
this part not right. incoming events of same type added queue arrive. first ones arrive go queue first - there's isn't step examines timestamp.
Comments
Post a Comment