SlideShare a Scribd company logo
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

More Related Content

PPTX
Bucks County Tech Meetup: node.js introduction
PPTX
Scalable Web Apps
KEY
Introduction to node.js
PPTX
introduction to node.js
PPT
Node js presentation
PDF
Node.js - A Quick Tour
PPTX
JavaScript Engines and Event Loop
PDF
Nodejs Explained with Examples
Bucks County Tech Meetup: node.js introduction
Scalable Web Apps
Introduction to node.js
introduction to node.js
Node js presentation
Node.js - A Quick Tour
JavaScript Engines and Event Loop
Nodejs Explained with Examples

What's hot (20)

PPTX
Avoiding Callback Hell with Async.js
PPT
JavaScript Event Loop
PDF
Comet with node.js and V8
PDF
Introduction to Node.js: What, why and how?
PPTX
All you need to know about the JavaScript event loop
KEY
Node.js - Best practices
PDF
Celery introduction
PDF
Pragmatic Monolith-First, easy to decompose, clean architecture
PDF
Non-blocking I/O, Event loops and node.js
KEY
Writing robust Node.js applications
KEY
A million connections and beyond - Node.js at scale
PDF
PPTX
Vert.x v3 - high performance polyglot application toolkit
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
PPTX
Introduction Node.js
PDF
Javascript Promises/Q Library
PPTX
Intro to Node.js (v1)
PPTX
Binary Studio Academy: Concurrency in C# 5.0
PDF
Server Side Event Driven Programming
PDF
Treasure Data Summer Internship Final Report
Avoiding Callback Hell with Async.js
JavaScript Event Loop
Comet with node.js and V8
Introduction to Node.js: What, why and how?
All you need to know about the JavaScript event loop
Node.js - Best practices
Celery introduction
Pragmatic Monolith-First, easy to decompose, clean architecture
Non-blocking I/O, Event loops and node.js
Writing robust Node.js applications
A million connections and beyond - Node.js at scale
Vert.x v3 - high performance polyglot application toolkit
Matthew Eernisse, NodeJs, .toster {webdev}
Introduction Node.js
Javascript Promises/Q Library
Intro to Node.js (v1)
Binary Studio Academy: Concurrency in C# 5.0
Server Side Event Driven Programming
Treasure Data Summer Internship Final Report
Ad

Viewers also liked (16)

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

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

PDF
Introduction to Node.js
PPTX
Node.js: A Guided Tour
PDF
Frontend Track NodeJS
ODP
Nodejs
PDF
Event driven programming -- Node.JS
PPTX
High Performance NodeJS
PPTX
Node.js Workshop - Sela SDP 2015
PDF
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
KEY
node.js dao
PDF
Node js internal
PPTX
PDF
Basic Understanding and Implement of Node.js
PDF
Understanding the Single Thread Event Loop
PPTX
Introduction to Node.js
PDF
Node.js introduction
PPTX
Introduction to Node.js
ODP
Node js lecture
PDF
Node.js introduction
PDF
Node.js concurrency
PPT
Scalability using Node.js
Introduction to Node.js
Node.js: A Guided Tour
Frontend Track NodeJS
Nodejs
Event driven programming -- Node.JS
High Performance NodeJS
Node.js Workshop - Sela SDP 2015
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
node.js dao
Node js internal
Basic Understanding and Implement of Node.js
Understanding the Single Thread Event Loop
Introduction to Node.js
Node.js introduction
Introduction to Node.js
Node js lecture
Node.js introduction
Node.js concurrency
Scalability using Node.js

Recently uploaded (20)

PDF
Empathic Computing: Creating Shared Understanding
PPTX
Spectroscopy.pptx food analysis technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPT
Teaching material agriculture food technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Cloud computing and distributed systems.
PDF
KodekX | Application Modernization Development
PDF
cuic standard and advanced reporting.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Encapsulation theory and applications.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Electronic commerce courselecture one. Pdf
PPTX
MYSQL Presentation for SQL database connectivity
Empathic Computing: Creating Shared Understanding
Spectroscopy.pptx food analysis technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
Teaching material agriculture food technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Cloud computing and distributed systems.
KodekX | Application Modernization Development
cuic standard and advanced reporting.pdf
Encapsulation_ Review paper, used for researhc scholars
Diabetes mellitus diagnosis method based random forest with bat algorithm
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Review of recent advances in non-invasive hemoglobin estimation
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Encapsulation theory and applications.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Electronic commerce courselecture one. Pdf
MYSQL Presentation for SQL database connectivity

How NOT to write in Node.js