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

● Default share memory   ● File descriptors
● Filesystem context     ● Signals and Signal 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);
});
Asynchronous programming model in NodeJS

●   Callbacks is hard
        ●   Divides things into stages and handle each stage in a
              a callback
        ●   Do things in a specific order.
        ●   You must keep track of what is done at a point of time
        ●   Hard to handle failures
        ●   Nested callbacks can be hard to read
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 Foundn");
            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();
                  });
              }
        });
}
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?
Asynchronous programming model in NodeJS
          Flow Control Libraries
●   Steps https://github.com/creationix/step
●   Flow-JS https://github.com/willconant/flow-js
●   Node-Promise https://github.com/kriszyp/node-promise
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);
   }
);
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', 'bobvance@potato.egg', function() {
        dbSet('user:' + userId + ':firstName', 'Bob', function() {
            dbSet('user:' + userId + ':lastName', 'Vance', function() {
                okWeAreDone();
            });
        });
    });
});                 flow.exec(
                        function() {
                            dbGet('userIdOf:bobvance', this);

                        },function(userId) {
                            dbSet('user:' + userId + ':email', 'bobvance@potato.egg', this.MULTI());
                            dbSet('user:' + userId + ':firstName', 'Bob', this.MULTI());
                            dbSet('user:' + userId + ':lastName', 'Vance', this.MULTI());

                        },function() {
                            okWeAreDone()
                        }
                   );
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!.
●   http://tamejs.org/
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);
      });
    });
  });
}
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);
}
Asynchronous programming model in NodeJS
            JavaScript's yield
●   V8/NodeJS has not supported yield, so generator yet
The end
●   Q&A

More Related Content

What's hot

Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tourcacois
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsGanesh Iyer
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js ExplainedJeff Kunkle
 
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 backendDavid Padbury
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 

What's hot (20)

Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
node.js dao
node.js daonode.js dao
node.js dao
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
Node.js - A Quick Tour
Node.js - A Quick TourNode.js - A Quick Tour
Node.js - A Quick Tour
 
Nodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web ApplicationsNodejs Event Driven Concurrency for Web Applications
Nodejs Event Driven Concurrency for Web Applications
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Node.js Explained
Node.js ExplainedNode.js Explained
Node.js Explained
 
NodeJS
NodeJSNodeJS
NodeJS
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
 
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
 
Node.js
Node.jsNode.js
Node.js
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
NodeJS: an Introduction
NodeJS: an IntroductionNodeJS: an Introduction
NodeJS: an Introduction
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 

Viewers also liked

Real Life WebSocket Case Studies and Demos
Real Life WebSocket Case Studies and DemosReal Life WebSocket Case Studies and Demos
Real Life WebSocket Case Studies and DemosPeter Moskovits
 
Building Living Web Applications with HTML5 WebSockets
Building Living Web Applications with HTML5 WebSocketsBuilding Living Web Applications with HTML5 WebSockets
Building Living Web Applications with HTML5 WebSocketsPeter Moskovits
 
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015Rich Cullen
 
Node.js and websockets intro
Node.js and websockets introNode.js and websockets intro
Node.js and websockets introkompozer
 
Websockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalableWebsockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalableGareth Marland
 
Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossugclkao
 

Viewers also liked (6)

Real Life WebSocket Case Studies and Demos
Real Life WebSocket Case Studies and DemosReal Life WebSocket Case Studies and Demos
Real Life WebSocket Case Studies and Demos
 
Building Living Web Applications with HTML5 WebSockets
Building Living Web Applications with HTML5 WebSocketsBuilding Living Web Applications with HTML5 WebSockets
Building Living Web Applications with HTML5 WebSockets
 
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
 
Node.js and websockets intro
Node.js and websockets introNode.js and websockets intro
Node.js and websockets intro
 
Websockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalableWebsockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalable
 
Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossug
 

Similar to Node js

Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
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.jsasync_io
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
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.0Binary Studio
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA PresentationRob Tweed
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
 
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.jssoft-shake.ch
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 

Similar to Node js (20)

NodeJS
NodeJSNodeJS
NodeJS
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
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
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Event driven programming -- Node.JS
Event driven programming -- Node.JSEvent driven programming -- Node.JS
Event driven programming -- Node.JS
 
Node intro
Node introNode intro
Node intro
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
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
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
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 Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 

More from hazzaz

Coffee1
Coffee1Coffee1
Coffee1hazzaz
 
Suy ngam
Suy ngamSuy ngam
Suy ngamhazzaz
 
Tu dong dat hang tu he thong ban le lon nhat trung quoc
Tu dong dat hang tu he thong ban le lon nhat trung quocTu dong dat hang tu he thong ban le lon nhat trung quoc
Tu dong dat hang tu he thong ban le lon nhat trung quochazzaz
 
how startups can benefit from launch community
how startups can benefit from launch communityhow startups can benefit from launch community
how startups can benefit from launch communityhazzaz
 
social network game
social network gamesocial network game
social network gamehazzaz
 
trung oss magento overview
trung oss magento overviewtrung oss magento overview
trung oss magento overviewhazzaz
 
su dung drupal xay dung mang xa hoi
su dung drupal xay dung mang xa hoisu dung drupal xay dung mang xa hoi
su dung drupal xay dung mang xa hoihazzaz
 
html5 css3 the future of web technology
html5 css3 the future of web technologyhtml5 css3 the future of web technology
html5 css3 the future of web technologyhazzaz
 
java script unit testing framework
java script unit testing frameworkjava script unit testing framework
java script unit testing frameworkhazzaz
 
build your own php extension
build your own php extensionbuild your own php extension
build your own php extensionhazzaz
 
kiem tien online
kiem tien onlinekiem tien online
kiem tien onlinehazzaz
 
web optimization
web optimizationweb optimization
web optimizationhazzaz
 
speed up ntvv2 by php ext module
speed up ntvv2 by php ext modulespeed up ntvv2 by php ext module
speed up ntvv2 by php ext modulehazzaz
 
zingmepracticeforbuildingscalablewebsitewithphp
zingmepracticeforbuildingscalablewebsitewithphpzingmepracticeforbuildingscalablewebsitewithphp
zingmepracticeforbuildingscalablewebsitewithphphazzaz
 
mysql optimization
mysql optimizationmysql optimization
mysql optimizationhazzaz
 
EAV in Magento
EAV in MagentoEAV in Magento
EAV in Magentohazzaz
 
css_trends
css_trendscss_trends
css_trendshazzaz
 
Phan mem tu do nguon mo
Phan mem tu do nguon moPhan mem tu do nguon mo
Phan mem tu do nguon mohazzaz
 

More from hazzaz (20)

Coffee1
Coffee1Coffee1
Coffee1
 
Suy ngam
Suy ngamSuy ngam
Suy ngam
 
Tu dong dat hang tu he thong ban le lon nhat trung quoc
Tu dong dat hang tu he thong ban le lon nhat trung quocTu dong dat hang tu he thong ban le lon nhat trung quoc
Tu dong dat hang tu he thong ban le lon nhat trung quoc
 
how startups can benefit from launch community
how startups can benefit from launch communityhow startups can benefit from launch community
how startups can benefit from launch community
 
social network game
social network gamesocial network game
social network game
 
trung oss magento overview
trung oss magento overviewtrung oss magento overview
trung oss magento overview
 
su dung drupal xay dung mang xa hoi
su dung drupal xay dung mang xa hoisu dung drupal xay dung mang xa hoi
su dung drupal xay dung mang xa hoi
 
html5 css3 the future of web technology
html5 css3 the future of web technologyhtml5 css3 the future of web technology
html5 css3 the future of web technology
 
java script unit testing framework
java script unit testing frameworkjava script unit testing framework
java script unit testing framework
 
build your own php extension
build your own php extensionbuild your own php extension
build your own php extension
 
kiem tien online
kiem tien onlinekiem tien online
kiem tien online
 
web optimization
web optimizationweb optimization
web optimization
 
speed up ntvv2 by php ext module
speed up ntvv2 by php ext modulespeed up ntvv2 by php ext module
speed up ntvv2 by php ext module
 
zingmepracticeforbuildingscalablewebsitewithphp
zingmepracticeforbuildingscalablewebsitewithphpzingmepracticeforbuildingscalablewebsitewithphp
zingmepracticeforbuildingscalablewebsitewithphp
 
mysql optimization
mysql optimizationmysql optimization
mysql optimization
 
EAV in Magento
EAV in MagentoEAV in Magento
EAV in Magento
 
Albus
AlbusAlbus
Albus
 
css_trends
css_trendscss_trends
css_trends
 
Cloud
CloudCloud
Cloud
 
Phan mem tu do nguon mo
Phan mem tu do nguon moPhan mem tu do nguon mo
Phan mem tu do nguon mo
 

Recently uploaded

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 TerraformAndrey Devyatkin
 
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 WorkerThousandEyes
 
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 RobisonAnna Loughnan Colquhoun
 
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 DevelopmentsTrustArc
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
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, ...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
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.pdfsudhanshuwaghmare1
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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, Adobeapidays
 

Recently uploaded (20)

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
 
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
 
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
 
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
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 

Node js

  • 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 ● Things can be changed ● No standard at the moment ● Unix only
  • 3. Proven control flow models ● Single-threaded process model ● Prefork MPM Apache HTTPd ● Multi-threaded process model ● Worker MPM Apache HTTPd ● JVM
  • 4. 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
  • 5. Events / Non-blocking I/O From http://bethesignal.org/
  • 6. 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.
  • 7. Request handling: Process / Threads / Events Threads shares ● Default share memory ● File descriptors ● Filesystem context ● Signals and Signal handling
  • 8. Request handling: Process / Threads / Events Thread creation is expensive - From iobound.com
  • 9. Request handling: Process / Threads / Events Context switching is expensive
  • 10. Request handling: Process / Threads / Events Blocking model: Process and Threads
  • 11. Request handling: Process / Threads / Events Non-blocking model: Events
  • 12. Request handling: Event-driven IO loop issue poll vs. epoll epoll: O(1) or O(n=active)
  • 13. 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
  • 14. 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.
  • 15. 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); });
  • 16. Asynchronous programming model in NodeJS ● Callbacks is hard ● Divides things into stages and handle each stage in a a callback ● Do things in a specific order. ● You must keep track of what is done at a point of time ● Hard to handle failures ● Nested callbacks can be hard to read
  • 17. 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 Foundn"); 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(); }); } }); }
  • 18. 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?
  • 19. Asynchronous programming model in NodeJS Flow Control Libraries ● Steps https://github.com/creationix/step ● Flow-JS https://github.com/willconant/flow-js ● Node-Promise https://github.com/kriszyp/node-promise
  • 20. 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); } );
  • 21. 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', 'bobvance@potato.egg', function() { dbSet('user:' + userId + ':firstName', 'Bob', function() { dbSet('user:' + userId + ':lastName', 'Vance', function() { okWeAreDone(); }); }); }); }); flow.exec( function() { dbGet('userIdOf:bobvance', this); },function(userId) { dbSet('user:' + userId + ':email', 'bobvance@potato.egg', this.MULTI()); dbSet('user:' + userId + ':firstName', 'Bob', this.MULTI()); dbSet('user:' + userId + ':lastName', 'Vance', this.MULTI()); },function() { okWeAreDone() } );
  • 22. 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!. ● http://tamejs.org/
  • 23. 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); }); }); }); }
  • 24. 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); }
  • 25. Asynchronous programming model in NodeJS JavaScript's yield ● V8/NodeJS has not supported yield, so generator yet
  • 26. The end ● Q&A