SlideShare una empresa de Scribd logo
1 de 52
How NOT to write in
Node.js
Piotr Pelczar
me@athlan.pl

PHPers, 6 Feb 2014
About me

Piotr Pelczar
me@athlan.pl
About me

getfokus.com

useselly.com
How software lives in hardware?
• Operating systems are process based
• Each process has assigned
processor, registers, memory

http://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/4_Threads.html
How software lives in hardware?
• Process paralelism using
threads (thread pools)
• Switching processor over
processes/threads causes
context switching

http://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/4_Threads.html
How software lives in hardware?

1. Avoid context switching = wasting time
How software lives in hardware?
In trivial, sequential approach
• Each operation is executed
sequentially:

O(t) > O(t+1)
• if O(t) stucks, O(t+1) waits…
http://cs.brown.edu/courses/cs196-5/f12/handouts/async.pdf
How software lives in hardware?

This is cool, software flow is predictible
But not in high throughput I/O
http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
How software lives in hardware?
High throughput I/O doesn’t mean:
• Memory operations
• Fast single-thread computing
How software lives in hardware?
High throughput I/O means:
• HTTP requests
• Database connections
• Queue system dispatching
• HDD operations
Single-threaded, event loop model
Problem:
Imagine a man, who has a task:
1. Walk around
2. When bucket is full of water,
just pour another bucket
3. Go to next bucket
http://www.nightmare.com/medusa/async_sockets.html
Single-threaded, event loop model
What is nonblocking I/O?
Imagine a man, who has a task:
1. Walk around
2. When bucket is full of water,
just pour another bucket
3. Go to next bucket
http://www.nightmare.com/medusa/async_sockets.html
Single-threaded, event loop model
Problem:

Imagine a man, who has a task:
1. Walk around
2. When bucket is full of water,
just pour another bucket,
if not… continue
3. Go to next bucket
http://www.nightmare.com/medusa/async_sockets.html
Single-threaded, event loop model
How it is realised in low-level operating system?
• select()
• /dev/pool descriptors
• kqueue
• pool
• epool
Single-threaded, event loop model
How it is realised in low-level operating system?
#include <sys/types.h>
#include <sys/socket.h>

int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, const struct timeval *timeout);
Single-threaded, event loop model

2. Avoid I/O blocking
Node.js architecture

http://nodejs.org/logos/
Node.js architecture
JavaScript
C/C++

Node std library

node bindings (socket, http, …)

Google V8

Thread Pool
(libeio)

Event loop
(libev)
Node.js architecture
• Single-threaded
no context switching

• Event loop
no waits

• Javascript (Google V8)
• ECMA-262 support
Node.js architecture

http://www.tocadoelfo.com.br/2012/04/por-que-estou-aprendendo-nodejs.html
ECMA-262 support
var arr = []
for(var i = 0, j = arr.length; i < j; ++i) {
var row = arr[i] // ufff…
}
var arr = []
arr.forEach(function(row) {
})
„Parallelism”
is a myth
Node.js architecture
• Everything runs in parallel except your code
• When currently code is running,
(not waiting for I/O descriptors)
whole event loop is blocked
„Parallelism”
• Let’s compute Fibonacci
function fib(n) {
return (n < 2) ? 1 : (fib(n-2)+fib(n-1));
}

This will simply block main (single) thread.
„Parallelism”
• How about process.nextTick() ?
„Parallelism”
• … but next iteration over function is delayed into next
event loop iteration
• That means each descriptor is checked before
computation.
„Parallelism”

process.nextTick()
to speed up computations is a myth
Node.js is not good solution to make
single-process computations
„Parallelism”
You can still fork another process

• threads_a_gogo

pool = require('threads_a_gogo').createPool(5)
pool.any.eval('myFunction( ... )')

• Fork process

var fork = require('child_process').fork;
var child = fork(__filename, [ 'arg1' ]);
Callback hell
is a myth
we can deal with it
Callback hell
• Language construction – callback function
• When operation is ready, call function passed as an
argument
someOperation(arg1, arg2, function() {
console.log('cool!');
})
Callback hell
• When many operations are ready…
var amqp = require('amqp');
var connection = amqp.createConnection();
connection.on('ready', function() {
connection.exchange("ex1", function(exchange) {
connection.queue('queue1', function(q) {
q.bind(exchange, 'r1');
q.subscribe(function(json, headers, info, m) {
console.log("msg: " + JSON.stringify(json));
});
});
});
});

This is callback hell
Callback hell
Deal with callback hell in many ways:
• Define callbacks as local variables
• Use async module
• Use PROMISE design pattern
Callback hell
Define callbacks as local variables, like this:
var whenSthElseDone = function() {
// done...
}
var whenSthDone = function() {
operation(whenSthElseDone)
}
operation(whenSthDone)
Callback hell
Use async module:
async.series([
function(callback) {

],
function() {

operation1(callback)
},

})

function(callback) {
operationBloking()

return callback()
}

// all done...
Callback hell
PROMISE design pattern:
var Promise = require('promise');

var promise = new Promise(function (resolve, reject) {
operation1(function (err, res) {
if (err) reject(err);
else resolve(res);

});
});
Callback hell
PROMISE design pattern:
promise.then(function(res) {
// done...

})
Events (event bus)
Triggering event does’t block whole event loop is a myth
Events
var eventbus = require('events').EventEmitter

myFunction() {
operation1(function() {
eventbus.emit('myFunctionIsDone', {
result: 1234

})
}
}
Events
var eventbus = require('events').EventEmitter

eventbus.on('myFunctionIsDone', function(data) {
console.log('cool! ')
})

Trigger waits until all listeners are done. So do not
make long-running operations in event subscribers.
Scaling EventEmitter
Triggering events in event bus via EventEmitter does not scale!
Scaling EventEmitter
• Triggering events in event bus via EventEmitter
does not scale!
• Events are visible locally in main thread
Scaling EventEmitter

We need to use external queue system
to touch distributed nodes
(3rd party for our application written in Node.js)
Scaling EventEmitter
RabbitMQ is cool because:
• based on AMQP protocol
(so integrates 3rd party software – an abstraction)
• Queue async system
• Publish-subscribe async model
• Request-Response model
Scaling EventEmitter
Emit:
1. Trigger event in your application via EventEmitter
2. Catch it locally
3. Re-trigger via RabbitMQ
Scaling EventEmitter
Receive:
1. Subscribe on RabbitMQ exchange
2. Trigger local event in application
Scaling EventEmitter

This is only to separate responsibilities
and good design of application
Not only Node.js
Node.js is not a religion! It is only an implementation of async programming model
Not only Node.js
Node.js is not a religion. Last time - hype.
It only utilizes event-loop model, known from a long time…
• GUI frameworks
• Tornado – Python
• Linkedin parseq – Java
• Async and Await – C#
• Cramp – Ruby
• reactphp – PHP, ehhh… WAT?!
Event loop, single-threaded
model is not solution for all
your problems…
Especially for long-running computings in single thread.
It’s good for high throughput I/O.
Thank you.
Q&A?

Piotr Pelczar
me@athlan.pl

Más contenido relacionado

La actualidad más candente

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
Tom Croucher
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 

La actualidad más candente (20)

Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Node.js - Best practices
Node.js  - Best practicesNode.js  - Best practices
Node.js - Best practices
 
Celery introduction
Celery introductionCelery introduction
Celery introduction
 
Pragmatic Monolith-First, easy to decompose, clean architecture
Pragmatic Monolith-First, easy to decompose, clean architecturePragmatic Monolith-First, easy to decompose, clean architecture
Pragmatic Monolith-First, easy to decompose, clean architecture
 
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
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Node ppt
Node pptNode ppt
Node ppt
 
Vert.x v3 - high performance polyglot application toolkit
Vert.x v3 - high performance  polyglot application toolkitVert.x v3 - high performance  polyglot application toolkit
Vert.x v3 - high performance polyglot application toolkit
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Treasure Data Summer Internship Final Report
Treasure Data Summer Internship Final ReportTreasure Data Summer Internship Final Report
Treasure Data Summer Internship Final Report
 

Destacado

Destacado (16)

Enterprise makeover. Be a good web citizen, deliver continuously and change y...
Enterprise makeover. Be a good web citizen, deliver continuously and change y...Enterprise makeover. Be a good web citizen, deliver continuously and change y...
Enterprise makeover. Be a good web citizen, deliver continuously and change y...
 
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
 
InterConnect2016: WebApp Architectures with Java and Node.js
InterConnect2016: WebApp Architectures with Java and Node.jsInterConnect2016: WebApp Architectures with Java and Node.js
InterConnect2016: WebApp Architectures with Java and Node.js
 
(node.js) Web Development - prościej
(node.js) Web Development - prościej(node.js) Web Development - prościej
(node.js) Web Development - prościej
 
Algoritmi, aggregatori, analytics: spunti e appunti da #ONA14
Algoritmi, aggregatori, analytics: spunti e appunti da #ONA14Algoritmi, aggregatori, analytics: spunti e appunti da #ONA14
Algoritmi, aggregatori, analytics: spunti e appunti da #ONA14
 
Managing and Versioning Machine Learning Models in Python
Managing and Versioning Machine Learning Models in PythonManaging and Versioning Machine Learning Models in Python
Managing and Versioning Machine Learning Models in Python
 
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
 
How to Write a Popular Python Library by Accident
How to Write a Popular Python Library by AccidentHow to Write a Popular Python Library by Accident
How to Write a Popular Python Library by Accident
 
CSS - OOCSS, SMACSS and more
CSS - OOCSS, SMACSS and moreCSS - OOCSS, SMACSS and more
CSS - OOCSS, SMACSS and more
 
Object Oriented CSS
Object Oriented CSSObject Oriented CSS
Object Oriented CSS
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
 
State of Tech in Texas
State of Tech in TexasState of Tech in Texas
State of Tech in Texas
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Connecting With the Disconnected
Connecting With the DisconnectedConnecting With the Disconnected
Connecting With the Disconnected
 
Can We Assess Creativity?
Can We Assess Creativity?Can We Assess Creativity?
Can We Assess Creativity?
 

Similar a How NOT to write in Node.js

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 
Node js
Node jsNode js
Node js
hazzaz
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
Prasoon Kumar
 

Similar a How NOT to write in Node.js (20)

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
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
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
Node.js
Node.jsNode.js
Node.js
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
The art of concurrent programming
The art of concurrent programmingThe art of concurrent programming
The art of concurrent programming
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
Node js
Node jsNode js
Node js
 
Node azure
Node azureNode azure
Node azure
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Node.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitterNode.js Event Loop & EventEmitter
Node.js Event Loop & EventEmitter
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Introdution to Node.js
Introdution to Node.jsIntrodution to Node.js
Introdution to Node.js
 
"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)
 
Node.js 101 with Rami Sayar
Node.js 101 with Rami SayarNode.js 101 with Rami Sayar
Node.js 101 with Rami Sayar
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
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...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

How NOT to write in Node.js