SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Concurrency in NodeJS

       PeterGriess, Yahoo! Inc.
pg@std.in | @pgriess| http://blog.std.in
NodeJS Concurrency Model
•   Single process
•   Single thread
•   Non-preemptive
•   Conncurrency provided by multiple processes
The Bad
• 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
The Good
•   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
child_process
• Node has an API for creating child
  processes, child_process.spawn()
• It has problems
  – Very UNIX; not friendly to JavaScript developers
  – IPC is DIY (transport? data format?)
Web Workers
• A rich but (mostly) easy-to-use JavaScript API
  – Spawn new workers
  – Send and receive messages to/from workers
  – Worker lifecycle management (creation,
    termination, etc)
• A Worker executes a JavaScript file/URL
• 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?
  – http://blog.std.in/2010/07/08/nodejs-webworker-
    design/
Ping/pong example: parent.js
var Worker = require(‘webworker/webworker’).Worker;

varw = new Worker(‘/Users/griessp/child.js’);

w.onmessage = function(e) {
console.log(e.data);
};

w.onerror = function(e) {
console.log(‘Error: ‘ + e.message);
w.terminate();
};

w.postMessage({ping : ‘pong’});
Ping/pong example: child.js
onmessage = function(e) {
console.log(e.data);
postMessage([e.data.ping, {Hello : ‘world’}]);

setTimeout(function() {
         throw new Error(‘Ohnoes!’);
    }, 1000);
};

onclose = function() {
console.log(‘Child: Shutting down.’);
};
Ping/pong example: output
% node ./parent.js
{ ping: 'pong' }
[ 'pong', { Hello: 'world' } ]
Parent error: Oh noes!
Child: Shutting down.
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!
node-webworkers: Extensions
• Gracefully shut down workers with onclose()
• Watch for worker termination with onexit()
• Send file descriptors with postMessage()

Weitere ähnliche Inhalte

Was ist angesagt?

Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
Tom Croucher
 

Was ist angesagt? (20)

Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Introduction to node.js by jiban
Introduction to node.js by jibanIntroduction to node.js by jiban
Introduction to node.js by jiban
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Node.js tutoria for beginner
Node.js tutoria for beginnerNode.js tutoria for beginner
Node.js tutoria for beginner
 
Nodejs intro
Nodejs introNodejs intro
Nodejs intro
 
Create Rest API in Nodejs
Create Rest API in Nodejs Create Rest API in Nodejs
Create Rest API in Nodejs
 
Node ppt
Node pptNode ppt
Node ppt
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystem
 
Node.js for beginner
Node.js for beginnerNode.js for beginner
Node.js for beginner
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDB
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
node.js dao
node.js daonode.js dao
node.js dao
 
Understanding the Single Thread Event Loop
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event Loop
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 

Ähnlich wie NodeJS Concurrency

T4T Training day - NodeJS
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJS
Tim Sommer
 
What I learned from FluentConf and then some
What I learned from FluentConf and then someWhat I learned from FluentConf and then some
What I learned from FluentConf and then some
Ohad Kravchick
 

Ähnlich wie NodeJS Concurrency (20)

"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Scalable server component using NodeJS & ExpressJS
Scalable server component using NodeJS & ExpressJSScalable server component using NodeJS & ExpressJS
Scalable server component using NodeJS & ExpressJS
 
Node azure
Node azureNode azure
Node azure
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 
What we do with Go
What we do with GoWhat we do with Go
What we do with Go
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 
Node.js on Azure
Node.js on AzureNode.js on Azure
Node.js on Azure
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
T4T Training day - NodeJS
T4T Training day - NodeJST4T Training day - NodeJS
T4T Training day - NodeJS
 
AngularJS - Architecture decisions in a large project 
AngularJS - Architecture decisionsin a large project AngularJS - Architecture decisionsin a large project 
AngularJS - Architecture decisions in a large project 
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
01 java intro
01 java intro01 java intro
01 java intro
 
What I learned from FluentConf and then some
What I learned from FluentConf and then someWhat I learned from FluentConf and then some
What I learned from FluentConf and then some
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Breaking the eggshell: From .NET to Node.js
Breaking the eggshell: From .NET to Node.jsBreaking the eggshell: From .NET to Node.js
Breaking the eggshell: From .NET to Node.js
 
Evolution of a cloud start up: From C# to Node.js
Evolution of a cloud start up: From C# to Node.jsEvolution of a cloud start up: From C# to Node.js
Evolution of a cloud start up: From C# to Node.js
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

NodeJS Concurrency

  • 1. Concurrency in NodeJS PeterGriess, Yahoo! Inc. pg@std.in | @pgriess| http://blog.std.in
  • 2. NodeJS Concurrency Model • Single process • Single thread • Non-preemptive • Conncurrency provided by multiple processes
  • 3. The Bad • 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
  • 4. The Good • 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
  • 5. child_process • Node has an API for creating child processes, child_process.spawn() • It has problems – Very UNIX; not friendly to JavaScript developers – IPC is DIY (transport? data format?)
  • 6. Web Workers • A rich but (mostly) easy-to-use JavaScript API – Spawn new workers – Send and receive messages to/from workers – Worker lifecycle management (creation, termination, etc) • A Worker executes a JavaScript file/URL • Separate process and execution context • A W3C standard, part of the “HTML5” bucket; designed for browsers
  • 7. Shameless plug: node-webworker • A Web Workers implementation for NodeJS • npm install webworker • Interested about the design? – http://blog.std.in/2010/07/08/nodejs-webworker- design/
  • 8. Ping/pong example: parent.js var Worker = require(‘webworker/webworker’).Worker; varw = new Worker(‘/Users/griessp/child.js’); w.onmessage = function(e) { console.log(e.data); }; w.onerror = function(e) { console.log(‘Error: ‘ + e.message); w.terminate(); }; w.postMessage({ping : ‘pong’});
  • 9. Ping/pong example: child.js onmessage = function(e) { console.log(e.data); postMessage([e.data.ping, {Hello : ‘world’}]); setTimeout(function() { throw new Error(‘Ohnoes!’); }, 1000); }; onclose = function() { console.log(‘Child: Shutting down.’); };
  • 10. Ping/pong example: output % node ./parent.js { ping: 'pong' } [ 'pong', { Hello: 'world' } ] Parent error: Oh noes! Child: Shutting down.
  • 11. 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!
  • 12. node-webworkers: Extensions • Gracefully shut down workers with onclose() • Watch for worker termination with onexit() • Send file descriptors with postMessage()