SlideShare uma empresa Scribd logo
1 de 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()

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

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()