SlideShare a Scribd company logo
1 of 60
There’s no sleep()
    in Javascript

Introduction to node.js
      twitter.com/jacek_becela
           github.com/ncr
node.js
node.js
• Server-side Javascript runtime
 • Google V8
 • CommonJS modules
node.js
• Server-side Javascript runtime
 • Google V8
 • CommonJS modules
• API for highly concurrent programming
 • All I/O is non-blocking (asynchronous)
 • Achieved using Event Loop
Two approaches to I/O
// blocking I/O + threads
var urls = db.query("select * from urls"); // wait
urls.each(function (url) {
  var page = http.get(url); // wait
  save(page); // wait
});
 
// non-blocking I/O + event loop
db.query("select * from urls", function (urls) {
  urls.each(function (url) {
    http.get(url, function (page) {
      save(page);
    });
  });
});
I/O Costs




http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles




         http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles



         http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles
• RAM: 250 cycles


        http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles
• RAM: 250 cycles
• DISK: 41,000,000 cycles

        http://nodejs.org/jsconf.pdf
I/O Costs

• L1: 3 cycles
• L2: 14 cycles
• RAM: 250 cycles
• DISK: 41,000,000 cycles
• NETWORK: 240,000,000 cycles
       http://nodejs.org/jsconf.pdf
Apache vs. Nginx




http://blog.webfaction.com/a-little-holiday-present
Apache vs. Nginx




http://blog.webfaction.com/a-little-holiday-present
Why threads are bad
Why threads are bad
• Hard to program
Why threads are bad
• Hard to program
• Shared state and locks
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
• Fine-grained locks increase complexity
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
• Fine-grained locks increase complexity
• Race conditions
Why threads are bad
• Hard to program
• Shared state and locks
• Deadlocks
• Giant locks decrease concurrency
• Fine-grained locks increase complexity
• Race conditions
• Context switching costs
When threads are good
When threads are good

• Support Multi-core CPUs
When threads are good

• Support Multi-core CPUs
• CPU-heavy work
When threads are good

• Support Multi-core CPUs
• CPU-heavy work
• Little or no shared state
When threads are good

• Support Multi-core CPUs
• CPU-heavy work
• Little or no shared state
• Threads count == CPU cores count
Event Loop
 user perspective
• You already use it everyday for I/O
• You register callbacks for events
• Your callback is eventually fired
      $("a").click(function () {
        console.log("clicked!");
      });
       
      $.ajax(..., function (...) {
        console.log("internets!");
      });
Event Loop
 life cycle
Event Loop
            life cycle
• Initialize empty event loop (just an array)
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
• End of source code reached
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
• End of source code reached
• Event loop starts iterating
Event Loop
            life cycle
• Initialize empty event loop (just an array)
• Read and “execute” code
 • Execute non-I/O code
 • Add every I/O call to the event loop
• End of source code reached
• Event loop starts iterating
• All this happens in a single thread
Event Loop
 life cycle
Event Loop
             life cycle
• Iterate over a list of events and callbacks
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
• Kernel notifies the Event Loop
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
• Kernel notifies the Event Loop
• Event Loop executes and removes a callback
Event Loop
             life cycle
• Iterate over a list of events and callbacks
• Perform I/O using non-blocking kernel
  facilities: epoll, kqueue, /dev/poll, select
• Event Loop goes to sleep
• Kernel notifies the Event Loop
• Event Loop executes and removes a callback
• Program exits when Event Loop is empty
Event Loop limitations
Event Loop limitations
• Callbacks have to return fast
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
 • Can do CPU-heavy stuff
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
 • Can do CPU-heavy stuff
 • No shared memory - no locks
Event Loop limitations
• Callbacks have to return fast
 • No CPU-heavy stuff
• What about multi-core CPUs
 • Web Workers using separate processes
 • Can do CPU-heavy stuff
 • No shared memory - no locks
 • Communication using message passing
Hello World
var sys = require('sys'),
   http = require('http');
http.createServer(function (req, res) {
  setTimeout(function () {
    res.sendHeader(200, {'Content-Type': 'text/plain'});
    res.write('Hello World');
    res.close();
  }, 2000);
}).listen(8000);
sys.puts('Server running at http://127.0.0.1:8000/');
sleep()
sleep()
• It is a blocking call per definition
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
• Except synchronous AJAX which is
  supposed to be used in “unload” event
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
• Except synchronous AJAX which is
  supposed to be used in “unload” event
• You can emulate sleep() using a “while”
  loop and checking wall clock but what’s the
  point...
sleep()
• It is a blocking call per definition
• Browser JS has no blocking functions
• Except synchronous AJAX which is
  supposed to be used in “unload” event
• You can emulate sleep() using a “while”
  loop and checking wall clock but what’s the
  point...
• The real reason: JavaScript exceution and
  Event Loop live in a single thread
Where to go next
• github.com/ry/node
• groups.google.com/group/nodejs
• howtonode.org
• dailyjs.org
• search twitter for node.js
• github.com/ncr/flickr_spy
Demo

More Related Content

What's hot

Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Angular App Presentation
Angular App PresentationAngular App Presentation
Angular App PresentationElizabeth Long
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introductionJonathan Holloway
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Angular 10 course_content
Angular 10 course_contentAngular 10 course_content
Angular 10 course_contentNAVEENSAGGAM1
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses étatsJosé Paumard
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Kanika Gera
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdfBareen Shaikh
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 

What's hot (20)

Présentation Angular 2
Présentation Angular 2 Présentation Angular 2
Présentation Angular 2
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Angular App Presentation
Angular App PresentationAngular App Presentation
Angular App Presentation
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Angular material
Angular materialAngular material
Angular material
 
Single Page Applications
Single Page ApplicationsSingle Page Applications
Single Page Applications
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Angular 10 course_content
Angular 10 course_contentAngular 10 course_content
Angular 10 course_content
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
L'API Collector dans tous ses états
L'API Collector dans tous ses étatsL'API Collector dans tous ses états
L'API Collector dans tous ses états
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
Rest web services
Rest web servicesRest web services
Rest web services
 
Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Angular
AngularAngular
Angular
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 

Similar to 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.jsGary Yeh
 
"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)Tech in Asia ID
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningMichel Schildmeijer
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await ExplainedJeremy Likness
 
Web a Quebec - JS Debugging
Web a Quebec - JS DebuggingWeb a Quebec - JS Debugging
Web a Quebec - JS DebuggingRami Sayar
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...Hackito Ergo Sum
 
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?Christian Joudrey
 
Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012mumrah
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentationasync_io
 
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleClojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleJulian Gamble
 
Kernelci.org needs you!
Kernelci.org needs you!Kernelci.org needs you!
Kernelci.org needs you!Mark Brown
 

Similar to Introduction to node.js (20)

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
 
"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)
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
SDN TEST Suite
SDN TEST SuiteSDN TEST Suite
SDN TEST Suite
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
C# Async/Await Explained
C# Async/Await ExplainedC# Async/Await Explained
C# Async/Await Explained
 
Web a Quebec - JS Debugging
Web a Quebec - JS DebuggingWeb a Quebec - JS Debugging
Web a Quebec - JS Debugging
 
What is Node.js
What is Node.jsWhat is Node.js
What is Node.js
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
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?
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
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?
 
Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012Introduction to ZooKeeper - TriHUG May 22, 2012
Introduction to ZooKeeper - TriHUG May 22, 2012
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Dcjq node.js presentation
Dcjq node.js presentationDcjq node.js presentation
Dcjq node.js presentation
 
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian GambleClojure Conj 2014 - Paradigms of core.async - Julian Gamble
Clojure Conj 2014 - Paradigms of core.async - Julian Gamble
 
Node.js
Node.jsNode.js
Node.js
 
Kernelci.org needs you!
Kernelci.org needs you!Kernelci.org needs you!
Kernelci.org needs you!
 

Recently uploaded

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
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
 
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
 
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 educationjfdjdjcjdnsjd
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 

Recently uploaded (20)

Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
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
 
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
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Introduction to node.js

  • 1. There’s no sleep() in Javascript Introduction to node.js twitter.com/jacek_becela github.com/ncr
  • 3. node.js • Server-side Javascript runtime • Google V8 • CommonJS modules
  • 4. node.js • Server-side Javascript runtime • Google V8 • CommonJS modules • API for highly concurrent programming • All I/O is non-blocking (asynchronous) • Achieved using Event Loop
  • 5. Two approaches to I/O // blocking I/O + threads var urls = db.query("select * from urls"); // wait urls.each(function (url) {   var page = http.get(url); // wait   save(page); // wait });   // non-blocking I/O + event loop db.query("select * from urls", function (urls) {   urls.each(function (url) {     http.get(url, function (page) {       save(page);     });   }); });
  • 7. I/O Costs • L1: 3 cycles http://nodejs.org/jsconf.pdf
  • 8. I/O Costs • L1: 3 cycles • L2: 14 cycles http://nodejs.org/jsconf.pdf
  • 9. I/O Costs • L1: 3 cycles • L2: 14 cycles • RAM: 250 cycles http://nodejs.org/jsconf.pdf
  • 10. I/O Costs • L1: 3 cycles • L2: 14 cycles • RAM: 250 cycles • DISK: 41,000,000 cycles http://nodejs.org/jsconf.pdf
  • 11. I/O Costs • L1: 3 cycles • L2: 14 cycles • RAM: 250 cycles • DISK: 41,000,000 cycles • NETWORK: 240,000,000 cycles http://nodejs.org/jsconf.pdf
  • 15. Why threads are bad • Hard to program
  • 16. Why threads are bad • Hard to program • Shared state and locks
  • 17. Why threads are bad • Hard to program • Shared state and locks • Deadlocks
  • 18. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency
  • 19. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency • Fine-grained locks increase complexity
  • 20. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency • Fine-grained locks increase complexity • Race conditions
  • 21. Why threads are bad • Hard to program • Shared state and locks • Deadlocks • Giant locks decrease concurrency • Fine-grained locks increase complexity • Race conditions • Context switching costs
  • 23. When threads are good • Support Multi-core CPUs
  • 24. When threads are good • Support Multi-core CPUs • CPU-heavy work
  • 25. When threads are good • Support Multi-core CPUs • CPU-heavy work • Little or no shared state
  • 26. When threads are good • Support Multi-core CPUs • CPU-heavy work • Little or no shared state • Threads count == CPU cores count
  • 27. Event Loop user perspective • You already use it everyday for I/O • You register callbacks for events • Your callback is eventually fired $("a").click(function () {   console.log("clicked!"); });   $.ajax(..., function (...) {   console.log("internets!"); });
  • 29. Event Loop life cycle • Initialize empty event loop (just an array)
  • 30. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code
  • 31. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code
  • 32. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop
  • 33. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop • End of source code reached
  • 34. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop • End of source code reached • Event loop starts iterating
  • 35. Event Loop life cycle • Initialize empty event loop (just an array) • Read and “execute” code • Execute non-I/O code • Add every I/O call to the event loop • End of source code reached • Event loop starts iterating • All this happens in a single thread
  • 37. Event Loop life cycle • Iterate over a list of events and callbacks
  • 38. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select
  • 39. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep
  • 40. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep • Kernel notifies the Event Loop
  • 41. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep • Kernel notifies the Event Loop • Event Loop executes and removes a callback
  • 42. Event Loop life cycle • Iterate over a list of events and callbacks • Perform I/O using non-blocking kernel facilities: epoll, kqueue, /dev/poll, select • Event Loop goes to sleep • Kernel notifies the Event Loop • Event Loop executes and removes a callback • Program exits when Event Loop is empty
  • 44. Event Loop limitations • Callbacks have to return fast
  • 45. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff
  • 46. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs
  • 47. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes
  • 48. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes • Can do CPU-heavy stuff
  • 49. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes • Can do CPU-heavy stuff • No shared memory - no locks
  • 50. Event Loop limitations • Callbacks have to return fast • No CPU-heavy stuff • What about multi-core CPUs • Web Workers using separate processes • Can do CPU-heavy stuff • No shared memory - no locks • Communication using message passing
  • 51. Hello World var sys = require('sys'),    http = require('http'); http.createServer(function (req, res) {   setTimeout(function () {     res.sendHeader(200, {'Content-Type': 'text/plain'});     res.write('Hello World');     res.close();   }, 2000); }).listen(8000); sys.puts('Server running at http://127.0.0.1:8000/');
  • 53. sleep() • It is a blocking call per definition
  • 54. sleep() • It is a blocking call per definition • Browser JS has no blocking functions
  • 55. sleep() • It is a blocking call per definition • Browser JS has no blocking functions • Except synchronous AJAX which is supposed to be used in “unload” event
  • 56. sleep() • It is a blocking call per definition • Browser JS has no blocking functions • Except synchronous AJAX which is supposed to be used in “unload” event • You can emulate sleep() using a “while” loop and checking wall clock but what’s the point...
  • 57. sleep() • It is a blocking call per definition • Browser JS has no blocking functions • Except synchronous AJAX which is supposed to be used in “unload” event • You can emulate sleep() using a “while” loop and checking wall clock but what’s the point... • The real reason: JavaScript exceution and Event Loop live in a single thread
  • 58. Where to go next • github.com/ry/node • groups.google.com/group/nodejs • howtonode.org • dailyjs.org • search twitter for node.js • github.com/ncr/flickr_spy
  • 59.
  • 60. Demo

Editor's Notes