Concurrency in NodeJS
PeterGriess, Yahoo! Inc.
firstname.lastname@example.org | @pgriess| http://blog.std.in
NodeJS Concurrency Model
• Single process
• Single thread
• Conncurrency provided by multiple processes
• Can’t utilize multiple cores by default
– Modern server-class hardware is at least 4x
• Easy to stall request processing
– Invoke a method that blocks (there are some)
– Run some CPU-intensive code
• No race conditions (almost)
• No locking strategies to get wrong
• Comparatively easy to reason about
• Processes are a powerful sandbox
• QoS: nice(2), ionice(1), etc.
• Permissions: chroot(2), setuid(2), etc.
• Fault isolation
• Node has an API for creating child
• It has problems
– IPC is DIY (transport? data format?)
– Spawn new workers
– Send and receive messages to/from workers
– Worker lifecycle management (creation,
• Separate process and execution context
• A W3C standard, part of the “HTML5” bucket;
designed for browsers
Shameless plug: node-webworker
• A Web Workers implementation for NodeJS
• npm install webworker
• Interested about the design?
Ping/pong example: hilights
• Easily spawn a new process!
• Pass complex messages!
• Exceptions bubble up to the parent!
• Graceful shutdown!
• This code will work in a browser with (almost)
no changes. Hooray standard APIs!
• Gracefully shut down workers with onclose()
• Watch for worker termination with onexit()
• Send file descriptors with postMessage()