SlideShare a Scribd company logo
Asynchronous I/O in NodeJS -  Standard and challenge of web programming? Pham Cong Dinh @ SkunkWorks @pcdinh BarCamp Saigon 2011 Follow us on Twitter: @teamskunkworks
Notice It is not a comprehensive study
Things can be changed
No standard at the moment
Unix only
Proven control flow models Single-threaded process model Prefork MPM Apache HTTPd Multi-threaded process model Worker MPM Apache HTTPd
JVM
Emerging control flow models  Coroutines Coroutines are computer program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations. Fiber A lightweight thread of execution. Like threads, fibers share address space. However, fibers use co-operative multitasking while threads use pre-emptive multitasking.  Events: non-blocking I/O
Events / Non-blocking I/O  From http://bethesignal.org/
Request handling:  Process / Threads / Events Process:  A single process is forked per request. That process is blocked until response can be produced
Threads:  A process contains multiple threads. A single thread is assigned to handle an incoming request. Thread-per-request model
Events:  A process consists of the processing of a series of events. At any instant in time, a single event/request is being processed. The process is not blocked on I/O request.
Request handling:  Process / Threads / Events Threads shares ●  D efault share memor y  ● F ile descriptors ●  Filesystem context  ● Signals and S ignal handling
Request handling:  Process / Threads / Events Thread creation is expensive - From iobound.com
Request handling:  Process / Threads / Events Context switching is expensive
Request handling:  Process / Threads / Events Blocking model: Process and Threads
Request handling:  Process / Threads / Events Non-blocking model: Events
Request handling:  Event-driven IO loop issue poll vs. epoll epoll: O(1) or O(n=active)
Request handling:  Event-driven callback issues Non-blocking IO Loop vs. Blocking callback Event dispatching is not blocked Callback can be blocked Mixing asynchronous code and synchronous code can be bad
Events in NodeJS libev   for event loops
libeio  for asynchonous file I/O
c-ares  for asynchronous DNS requests and name resolution.
evcom  (by Ryan Dahl) is a stream socket library on top of libev.
Asynchronous programming model in NodeJS First citizen: High order function/callback
Most “objects” in NodeJS are Event Emitters (http server/client, etc.)
Most low level “functions” take callbacks. (posix API, DNS lookups, etc.) Blocking code var a = db.query('SELECT A'); console.log('result a:', a); Non-blocking code using callback db.query('SELECT A',  function(result)  { console.log('result a:', result); });

More Related Content

PDF
NodeJS: the good parts? A skeptic’s view (devnexus2014)
Chris Richardson
 
PPT
Nodejs Event Driven Concurrency for Web Applications
Ganesh Iyer
 
PPTX
Node.js Workshop - Sela SDP 2015
Nir Noy
 
PDF
Server Side Event Driven Programming
Kamal Hussain
 
PDF
NodeJS: an Introduction
Roberto Casadei
 
KEY
A million connections and beyond - Node.js at scale
Tom Croucher
 
PDF
Node.js Explained
Jeff Kunkle
 
PDF
NodeJS
LinkMe Srl
 
NodeJS: the good parts? A skeptic’s view (devnexus2014)
Chris Richardson
 
Nodejs Event Driven Concurrency for Web Applications
Ganesh Iyer
 
Node.js Workshop - Sela SDP 2015
Nir Noy
 
Server Side Event Driven Programming
Kamal Hussain
 
NodeJS: an Introduction
Roberto Casadei
 
A million connections and beyond - Node.js at scale
Tom Croucher
 
Node.js Explained
Jeff Kunkle
 
NodeJS
LinkMe Srl
 

What's hot (20)

PDF
NodeJS for Beginner
Apaichon Punopas
 
PPTX
NodeJS guide for beginners
Enoch Joshua
 
KEY
Writing robust Node.js applications
Tom Croucher
 
PPTX
Introduction Node.js
Erik van Appeldoorn
 
KEY
NodeJS
.toster
 
PDF
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
PDF
Philly Tech Week Introduction to NodeJS
Ross Kukulinski
 
KEY
node.js: Javascript's in your backend
David Padbury
 
PDF
Understanding the Single Thread Event Loop
TorontoNodeJS
 
PDF
Nodejs Explained with Examples
Gabriele Lana
 
PDF
Node Architecture and Getting Started with Express
jguerrero999
 
PPTX
Node.js: A Guided Tour
cacois
 
PPTX
introduction to node.js
orkaplan
 
PPT
Node js presentation
martincabrera
 
PPTX
Introduction to node.js
Dinesh U
 
PPT
RESTful API In Node Js using Express
Jeetendra singh
 
PDF
Building servers with Node.js
ConFoo
 
PDF
Nodejs vatsal shah
Vatsal N Shah
 
PDF
Getting started with developing Nodejs
Phil Hawksworth
 
NodeJS for Beginner
Apaichon Punopas
 
NodeJS guide for beginners
Enoch Joshua
 
Writing robust Node.js applications
Tom Croucher
 
Introduction Node.js
Erik van Appeldoorn
 
NodeJS
.toster
 
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Philly Tech Week Introduction to NodeJS
Ross Kukulinski
 
node.js: Javascript's in your backend
David Padbury
 
Understanding the Single Thread Event Loop
TorontoNodeJS
 
Nodejs Explained with Examples
Gabriele Lana
 
Node Architecture and Getting Started with Express
jguerrero999
 
Node.js: A Guided Tour
cacois
 
introduction to node.js
orkaplan
 
Node js presentation
martincabrera
 
Introduction to node.js
Dinesh U
 
RESTful API In Node Js using Express
Jeetendra singh
 
Building servers with Node.js
ConFoo
 
Nodejs vatsal shah
Vatsal N Shah
 
Getting started with developing Nodejs
Phil Hawksworth
 
Ad

Viewers also liked (20)

PPTX
Building Web Apps & APIs With Node JS
Lohith Goudagere Nagaraj
 
PDF
NodeJS: the good parts? A skeptic’s view (oredev, oredev2013)
Chris Richardson
 
PDF
Testing NodeJS Security
Jose Manuel Ortega Candel
 
PPTX
All about NodeJS
Hsu Ping Feng
 
PPTX
Introduction to Node.js
Vikash Singh
 
ODP
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
PDF
NodeJS for Novices - 28/Oct/13 - Winnipeg, MB
David Wesst
 
PDF
(C)NodeJS
Jackson Tian
 
PDF
Node js (runtime environment + js library) platform
Sreenivas Kappala
 
PDF
Microservices and Seneca at RomaJS group
Luca Lanziani
 
PDF
The Seneca Pattern at EngineYard Distill 2013 Conference
Richard Rodger
 
PPTX
Node Interactive : 7 years, 7 design patterns, will node continue to outshine
Shubhra Kar
 
KEY
Introducing the Seneca MVP framework for Node.js
Richard Rodger
 
PPTX
Writing Test Cases with PHPUnit
Shouvik Chatterjee
 
PDF
NodeJS Microservices, Built it Now, Scale it Later!
Lalit Shandilya
 
PDF
Richard rodger technical debt - web summit 2013
Richard Rodger
 
PDF
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
Nurul Ferdous
 
PDF
Nodejs in Production
William Bruno Moraes
 
PPT
How to scale and deploy NodeJS app
Yacobus Reinhart
 
PDF
NodeJS security - still unsafe at most speeds - v1.0
Dinis Cruz
 
Building Web Apps & APIs With Node JS
Lohith Goudagere Nagaraj
 
NodeJS: the good parts? A skeptic’s view (oredev, oredev2013)
Chris Richardson
 
Testing NodeJS Security
Jose Manuel Ortega Candel
 
All about NodeJS
Hsu Ping Feng
 
Introduction to Node.js
Vikash Singh
 
Introduce about Nodejs - duyetdev.com
Van-Duyet Le
 
NodeJS for Novices - 28/Oct/13 - Winnipeg, MB
David Wesst
 
(C)NodeJS
Jackson Tian
 
Node js (runtime environment + js library) platform
Sreenivas Kappala
 
Microservices and Seneca at RomaJS group
Luca Lanziani
 
The Seneca Pattern at EngineYard Distill 2013 Conference
Richard Rodger
 
Node Interactive : 7 years, 7 design patterns, will node continue to outshine
Shubhra Kar
 
Introducing the Seneca MVP framework for Node.js
Richard Rodger
 
Writing Test Cases with PHPUnit
Shouvik Chatterjee
 
NodeJS Microservices, Built it Now, Scale it Later!
Lalit Shandilya
 
Richard rodger technical debt - web summit 2013
Richard Rodger
 
JavaScript as a Server side language (NodeJS): JSConf 2011, Dhaka
Nurul Ferdous
 
Nodejs in Production
William Bruno Moraes
 
How to scale and deploy NodeJS app
Yacobus Reinhart
 
NodeJS security - still unsafe at most speeds - v1.0
Dinis Cruz
 
Ad

Similar to Asynchronous I/O in NodeJS - new standard or challenges? (20)

ODP
Node js
hazzaz
 
PPTX
NodeJS
Alok Guha
 
PPT
JS everywhere 2011
Oleg Podsechin
 
PPT
Node.js: CAMTA Presentation
Rob Tweed
 
PPTX
Introduction to Node.JS
Collaboration Technologies
 
PPT
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rick Copeland
 
PPT
Server side JavaScript: going all the way
Oleg Podsechin
 
PPTX
Node.js Patterns for Discerning Developers
cacois
 
PDF
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 
PDF
Top 30 Node.js interview questions
techievarsity
 
KEY
Practical Use of MongoDB for Node.js
async_io
 
PDF
Node intro
cloudhead
 
PPTX
Copper: A high performance workflow engine
dmoebius
 
PDF
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
PPT
nodejs_at_a_glance.ppt
WalaSidhom1
 
PDF
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp
 
PDF
Beginning MEAN Stack
Rob Davarnia
 
PPT
Node js beginner
Sureshreddy Nalimela
 
PPT
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
PPT
Laurens Van Den Oever Xopus Presentation
Ajax Experience 2009
 
Node js
hazzaz
 
NodeJS
Alok Guha
 
JS everywhere 2011
Oleg Podsechin
 
Node.js: CAMTA Presentation
Rob Tweed
 
Introduction to Node.JS
Collaboration Technologies
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rick Copeland
 
Server side JavaScript: going all the way
Oleg Podsechin
 
Node.js Patterns for Discerning Developers
cacois
 
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 
Top 30 Node.js interview questions
techievarsity
 
Practical Use of MongoDB for Node.js
async_io
 
Node intro
cloudhead
 
Copper: A high performance workflow engine
dmoebius
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
nodejs_at_a_glance.ppt
WalaSidhom1
 
WebCamp 2016: PHP.Алексей Петров.PHP at Scale: System Architect Toolbox
WebCamp
 
Beginning MEAN Stack
Rob Davarnia
 
Node js beginner
Sureshreddy Nalimela
 
nodejs_at_a_glance, understanding java script
mohammedarshadhussai4
 
Laurens Van Den Oever Xopus Presentation
Ajax Experience 2009
 

Recently uploaded (20)

PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PPTX
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Software Development Methodologies in 2025
KodekX
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 

Asynchronous I/O in NodeJS - new standard or challenges?

  • 1. Asynchronous I/O in NodeJS - Standard and challenge of web programming? Pham Cong Dinh @ SkunkWorks @pcdinh BarCamp Saigon 2011 Follow us on Twitter: @teamskunkworks
  • 2. Notice It is not a comprehensive study
  • 3. Things can be changed
  • 4. No standard at the moment
  • 6. Proven control flow models Single-threaded process model Prefork MPM Apache HTTPd Multi-threaded process model Worker MPM Apache HTTPd
  • 7. JVM
  • 8. Emerging control flow models Coroutines Coroutines are computer program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations. Fiber A lightweight thread of execution. Like threads, fibers share address space. However, fibers use co-operative multitasking while threads use pre-emptive multitasking. Events: non-blocking I/O
  • 9. Events / Non-blocking I/O From http://bethesignal.org/
  • 10. Request handling: Process / Threads / Events Process: A single process is forked per request. That process is blocked until response can be produced
  • 11. Threads: A process contains multiple threads. A single thread is assigned to handle an incoming request. Thread-per-request model
  • 12. Events: A process consists of the processing of a series of events. At any instant in time, a single event/request is being processed. The process is not blocked on I/O request.
  • 13. Request handling: Process / Threads / Events Threads shares ● D efault share memor y ● F ile descriptors ● Filesystem context ● Signals and S ignal handling
  • 14. Request handling: Process / Threads / Events Thread creation is expensive - From iobound.com
  • 15. Request handling: Process / Threads / Events Context switching is expensive
  • 16. Request handling: Process / Threads / Events Blocking model: Process and Threads
  • 17. Request handling: Process / Threads / Events Non-blocking model: Events
  • 18. Request handling: Event-driven IO loop issue poll vs. epoll epoll: O(1) or O(n=active)
  • 19. Request handling: Event-driven callback issues Non-blocking IO Loop vs. Blocking callback Event dispatching is not blocked Callback can be blocked Mixing asynchronous code and synchronous code can be bad
  • 20. Events in NodeJS libev for event loops
  • 21. libeio for asynchonous file I/O
  • 22. c-ares for asynchronous DNS requests and name resolution.
  • 23. evcom (by Ryan Dahl) is a stream socket library on top of libev.
  • 24. Asynchronous programming model in NodeJS First citizen: High order function/callback
  • 25. Most “objects” in NodeJS are Event Emitters (http server/client, etc.)
  • 26. Most low level “functions” take callbacks. (posix API, DNS lookups, etc.) Blocking code var a = db.query('SELECT A'); console.log('result a:', a); Non-blocking code using callback db.query('SELECT A', function(result) { console.log('result a:', result); });
  • 27. Asynchronous programming model in NodeJS Callbacks is hard Divides things into stages and handle each stage in a a callback
  • 28. Do things in a specific order.
  • 29. You must keep track of what is done at a point of time
  • 30. Hard to handle failures
  • 31. Nested callbacks can be hard to read
  • 32. Asynchronous programming model in NodeJS Nested callbacks can be hard to read var transferFile = function (request, response) { var uri = url.parse(request.url).pathname; var filepath = path.join(process.cwd(), uri); // check whether the file is exist and get the result from callback path.exists(filepath, function (exists) { if (!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); } else { // read the file content and get the result from callback fs.readFile(filepath, "binary", function (error, data) { if (error) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(error + "\n"); } else { response.writeHead(200); response.write(data, "binary"); } response.end(); }); } }); }
  • 33. Asynchronous programming model in NodeJS Callback is hard to debug function f () { throw new Error(’foo’); } setTimeout(f, 10000*Math.random()); setTimeout(f, 10000*Math.random()); From which line does the error arise?
  • 34. Asynchronous programming model in NodeJS Flow Control Libraries Steps https://github.com/creationix/step
  • 37. Asynchronous programming model in NodeJS Flow Control Libraries: Steps Step's goal is to both remove boilerplate code and to improve readability of asynchronous code. The features are easy chaining of serial actions with optional parallel groups within each step. Step( function readSelf() { fs.readFile(__filename, this); }, function capitalize(err, text) { if (err) throw err; return text.toUpperCase(); }, function showIt(err, newText) { if (err) throw err; console.log(newText); } );
  • 38. Asynchronous programming model in NodeJS Flow Control Libraries: Flow-JS Flow-JS provides a Javascript construct that is something like a continuation or a fiber found in other languages. Practically speaking, it can be used to eliminate so-called "pyramids" from your multi-step asynchronous logic. dbGet('userIdOf:bobvance', function(userId) { dbSet('user:' + userId + ':email', '[email protected]', function() { dbSet('user:' + userId + ':firstName', 'Bob', function() { dbSet('user:' + userId + ':lastName', 'Vance', function() { okWeAreDone(); }); }); }); }); Asynchronous programming model in NodeJS Flow Control Libraries: Flow-JS flow.exec( function() { dbGet('userIdOf:bobvance', this); }, function(userId) { dbSet('user:' + userId + ':email', '[email protected]', this.MULTI()); dbSet('user:' + userId + ':firstName', 'Bob', this.MULTI()); dbSet('user:' + userId + ':lastName', 'Vance', this.MULTI()); }, function() { okWeAreDone() } );
  • 39. Asynchronous programming model in NodeJS JavaScript extension: TameJS Tame (or "TameJs") is an extension to JavaScript, written in JavaScript, that makes event programming easier to write, read, and edit when control-flow libraries are not good enough!.
  • 41. Asynchronous programming model in NodeJS JavaScript extension: TameJS Synchronous code handleVisit : function(angel, buffy) { var match_score = getScore(angel, buffy); var next_match = getNextMatch(angel); var visit_info = recordVisitAndGetInfo(angel, buffy); if (match_score > 0.9 && ! visit_info.last_visit) { sendVisitorEmail(angel, buffy); } doSomeFinalThings(match_score, next_match, visit_info); } Asynchrnous code handleVisit : function(angel, buffy) { getScore(angel, buffy, function(match_score) { getNextMatch(angel, function(next_match) { recordVisitAndGetInfo(angel, buffy, function(visit_info) { if (match_score > 0.9 && ! visit_info.last_visit) { sendVisitorEmail(angel, buffy); } doSomeFinalThings(match_score, next_match, visit_info); }); }); }); }
  • 42. Asynchronous programming model in NodeJS JavaScript extension: TameJS TameJS style handleVisit : function(angel, buffy) { // // let's fire all 3 at once // await { getScore (angel, buffy, defer (var score)); getNextMatch (angel, buffy, defer (var next)); recordVisitAndGetInfo (angel, buffy, defer (var vinfo)); } // // they've called back, and now we have our data // if (score > 0.9 && ! vinfo.last_visit) { sendVisitorEmail(angel, buffy); } doSomeFinalThings(score, next, vinfo); }
  • 43. Asynchronous programming model in NodeJS JavaScript's yield V8/NodeJS has not supported yield, so generator yet
  • 44. The end Q & A