SlideShare una empresa de Scribd logo
1 de 50
This is a 15 minute presentation I did
at work recently about threads,
polling and node.js.

It rests heavily on the shoulders of
giants, especially Ryan Dahls original
node.js talk at jsconf.eu.
non-blocking I/O,
event loops,
javascript and
node.js.
Threads suck
Why do we
use threads?
Policy p = cmServer.getPolicy(...);

System.out.println(p.getContentId().toString());
Policy p = cmServer.getPolicy(...);

System.out.println(p.getContentId().toString());
Policy p = cmServer.getPolicy(...);
Blocking implies multiple execution stacks. Where else to go?

System.out.println(p.getContentId().toString());
How to deal with blocking?
Processes
    No shared memory
    Heavy

OS Threads
    Can share memory
    Relatively cheap
Green threads / Co-routines
Are threads cheaper
than processes?
HTTP request latency; glibc 2.3.2 on Linux 2.6
                     HTTP-anropslatens; glibc 2.3.2 på Linux 2.6




                                                   1 thread per call




                                                                 1 process per call




http://bulk.fefe.de/scalable-networking.pdf



                                              Open connections
HTTP request latency; glibc 2.3.2 on Linux 2.6




                    1 thread per call




                                  1 process per call




 Which is the reason why we use thread pools!




               Open connections
Are threads
cheap at all?
nginx vs apache
       http://blog.webfaction.com/a-little-holiday-present
nginx vs apache
           http://blog.webfaction.com/a-little-holiday-present




  ∆ = Apaches context switching
lmbench
         ./lat_ctx -N 10 -s 4096 0 1 .. 20

80

74

68

62

56

50
     2     3   4   5   6   7   8   9   10 11 12 13 14 15 16 17 18 19 20
lmbench
         ./lat_ctx -N 10 -s 4096 0 1 .. 20

80

74

68

62

56

50
     2     3   4   5   6   7   8   9   10 11 12 13 14 15 16 17 18 19 20


          On a MBP, OS X 10.6 Context switch around 65 µs
65 µs x 2 x 4000 = 520 ms
How about memory?
> ulimit -a | grep stack
stack size     (kbytes, -s) 8192
...but at least 512+1 kb
For OS X, source: ADC
nginx vs apache
       http://blog.webfaction.com/a-little-holiday-present
nginx vs apache
              http://blog.webfaction.com/a-little-holiday-present




Difference: Threads and processes cost.
What about ngnix?
The cost of I/O

L1-cache             3 cycles
L2-cache            14 cycles
RAM                250 cycles
Disk        41 000 000 cycles
Network    240 000 000 cycles
The weight of I/O
The weight of I/O

L1-cache   A big squirrel
The weight of I/O

L1-cache   A big squirrel
L2-cache   A medium-sized cat
The weight of I/O

L1-cache   A big squirrel
L2-cache   A medium-sized cat
RAM        Mattias, basically
The weight of I/O

L1-cache   A big squirrel
L2-cache   A medium-sized cat
RAM        Mattias, basically
Disk       Like a 100 blue whales
The weight of I/O

L1-cache   A big squirrel
L2-cache   A medium-sized cat
RAM        Mattias, basically
Disk       Like a 100 blue whales
Network    Belarus yearly
           wheat import
Servers pretty I/O-intensive
             =
   Squirrelʼs burried in
   whales fat and wheat
Policy p = cmServer.getPolicy(...);

System.out.println(p.getContentId().toString());
cmServer.getPolicy(function (Policy p) {
  System.out.println(
     p.getContentId().toString()
  );
});
cmServer.getPolicy(function (Policy p) {
  System.out.println(
           Sleeps until p’s available
     p.getContentId().toString()
  );
});
cmServer.getPolicy(function (Policy p) {
  System.out.println(
            Sover tills dess p finns
     p.getContentId().toString()
  );
});
// And down here we can do other stuff
Non-blocking I/O...

All code is run in a single thread
Functions listen on events,
act and sleep
...is pretty demanding


All I/O has to be non-blocking
Callbacks are pretty ugly without HOF
V8 + node.js
“a purely evented,
 non-blocking
 infrastructure to script
 highly concurrent
 programs.”
V8 Chromes JS engine
JS Built to be event driven
node.js Queues built on /dev/epoll
        amongst other things
var http = require('http');

http.createServer(function (req, res) {
  setTimeout(function () {
    res.sendHeader(200, {'Content-Type': 'text/plain'});
    res.sendBody('Hello World');
    res.finish();
  }, 2000);
}).listen(8080);
% node hello.js
% ab -n 1000 -c 200 http://127.0.0.1:8080/

...

Time per request:      2010.070 [ms] (mean)
              min mean[+/-sd] median   max
Connect:        0    2  1.9      1       8
Processing: 2001 2006   2.8   2005    2013
Waiting:     2000 2003  2.0   2003    2009
Total:       2002 2008  3.5   2006    2015

Percentage of the requests served within a certain time (ms)
  50%   2006
  66%   2008
  75%   2012
  80%   2013
  90%   2013
  95%   2014
  98%   2014
  99%   2014
 100%   2015 (longest request)
var stat = require('posix').stat,
      puts = require('sys').puts;


var promise = stat('/etc/passwd');


promise.addCallback(function (s) {
      puts('modified: ' + s.mtime);
});
var web = require('./web');


web.server(function (route) {
    route.get("^/([a-z]+)$", function(parms, req, res) {
          res.sendHeader(200, {'Content-Type':'text/plain'});
          res.sendBody("Hello " + parms[0]);
          res.finish();
    });
}).listen(8080);
% node web.test.js
% ab -n 10000 -c 250 http://127.0.0.1:8080/marcus
...

Requests per second:    4851.93 [#/sec] (mean)
Time per request:       51.526 [ms] (mean)
Time per request:       0.206 [ms] (mean, across all c requests)

Connection Times (ms)
              min mean[+/-sd] median    max
Connect:        0   14 111.8     1      999
Processing:     4   35 15.8     31      103
Waiting:        4   35 15.8     30      103
Total:         14   49 112.5    32     1035

Percentage of the requests served within a certain time (ms)
  50%     32
  66%     34
  75%     35
  80%     36
  90%     57
  95%     92
  98%    102
  99%    986
 100%   1035 (longest request)
var web   = require('./web'),
    posix = require('posix');

web.server(function (route) {
    route.get("^/([a-z]+)$", function(parms, req, res) {
        posix.cat(parms[0]).addCallback(function(text) {
            res.sendHeader(200, {'Content-Type':'text/plain'});
            res.sendBody(text);
            res.finish();
        });
    });
}).listen(8080);
throughput
80

74

68

62

56

50
     1   5   13   25   50   100   250
HEALTH
Distributed ab

One configuration, multiple nodes
REST interface
Streams JSON over HTTP
Decent performance
demo!

Más contenido relacionado

La actualidad más candente

OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
ScyllaDB
 
Windows system - memory개념잡기
Windows system - memory개념잡기Windows system - memory개념잡기
Windows system - memory개념잡기
ChangKyu Song
 
윤석주, 신입 게임 프로그래머가 되는 법 - 넥슨 채용 프로세스 단계별 분석, NDC2019
윤석주, 신입 게임 프로그래머가 되는 법 - 넥슨 채용 프로세스 단계별 분석, NDC2019윤석주, 신입 게임 프로그래머가 되는 법 - 넥슨 채용 프로세스 단계별 분석, NDC2019
윤석주, 신입 게임 프로그래머가 되는 법 - 넥슨 채용 프로세스 단계별 분석, NDC2019
devCAT Studio, NEXON
 

La actualidad más candente (20)

Fast Userspace OVS with AF_XDP, OVS CONF 2018
Fast Userspace OVS with AF_XDP, OVS CONF 2018Fast Userspace OVS with AF_XDP, OVS CONF 2018
Fast Userspace OVS with AF_XDP, OVS CONF 2018
 
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
OSv Unikernel — Optimizing Guest OS to Run Stateless and Serverless Apps in t...
 
Programación Reactiva con Spring WebFlux
Programación Reactiva con Spring WebFluxProgramación Reactiva con Spring WebFlux
Programación Reactiva con Spring WebFlux
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Yapp methodology anjo-kolk
Yapp methodology anjo-kolkYapp methodology anjo-kolk
Yapp methodology anjo-kolk
 
Apache Spark Core
Apache Spark CoreApache Spark Core
Apache Spark Core
 
Ndc12 2
Ndc12 2Ndc12 2
Ndc12 2
 
NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기
NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기
NDC 2017 하재승 NEXON ZERO (넥슨 제로) 점검없이 실시간으로 코드 수정 및 게임 정보 수집하기
 
Windows system - memory개념잡기
Windows system - memory개념잡기Windows system - memory개념잡기
Windows system - memory개념잡기
 
Ndc14 분산 서버 구축의 ABC
Ndc14 분산 서버 구축의 ABCNdc14 분산 서버 구축의 ABC
Ndc14 분산 서버 구축의 ABC
 
Lock free queue
Lock free queueLock free queue
Lock free queue
 
BPF / XDP 8월 세미나 KossLab
BPF / XDP 8월 세미나 KossLabBPF / XDP 8월 세미나 KossLab
BPF / XDP 8월 세미나 KossLab
 
Introduction to Spark Internals
Introduction to Spark InternalsIntroduction to Spark Internals
Introduction to Spark Internals
 
Data Storage Tips for Optimal Spark Performance-(Vida Ha, Databricks)
Data Storage Tips for Optimal Spark Performance-(Vida Ha, Databricks)Data Storage Tips for Optimal Spark Performance-(Vida Ha, Databricks)
Data Storage Tips for Optimal Spark Performance-(Vida Ha, Databricks)
 
Optimisation de MySQL
Optimisation de MySQLOptimisation de MySQL
Optimisation de MySQL
 
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이  왜 이리 힘드나요?  (Lock-free에서 Transactional Memory까지)
Ndc2014 시즌 2 : 멀티쓰레드 프로그래밍이 왜 이리 힘드나요? (Lock-free에서 Transactional Memory까지)
 
[125]웹 성능 최적화에 필요한 브라우저의 모든 것
[125]웹 성능 최적화에 필요한 브라우저의 모든 것[125]웹 성능 최적화에 필요한 브라우저의 모든 것
[125]웹 성능 최적화에 필요한 브라우저의 모든 것
 
FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기
 
윤석주, 신입 게임 프로그래머가 되는 법 - 넥슨 채용 프로세스 단계별 분석, NDC2019
윤석주, 신입 게임 프로그래머가 되는 법 - 넥슨 채용 프로세스 단계별 분석, NDC2019윤석주, 신입 게임 프로그래머가 되는 법 - 넥슨 채용 프로세스 단계별 분석, NDC2019
윤석주, 신입 게임 프로그래머가 되는 법 - 넥슨 채용 프로세스 단계별 분석, NDC2019
 
​『함수형 반응형 프로그래밍』 맛보기
​『함수형 반응형 프로그래밍』 맛보기​『함수형 반응형 프로그래밍』 맛보기
​『함수형 반응형 프로그래밍』 맛보기
 

Similar a Non-blocking I/O, Event loops and node.js

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Tom Croucher
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.io
Rick Copeland
 

Similar a Non-blocking I/O, Event loops and node.js (20)

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
 
Full Stack Load Testing
Full Stack Load Testing Full Stack Load Testing
Full Stack Load Testing
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
Node.js - As a networking tool
Node.js - As a networking toolNode.js - As a networking tool
Node.js - As a networking tool
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.io
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Caching and tuning fun for high scalability
Caching and tuning fun for high scalabilityCaching and tuning fun for high scalability
Caching and tuning fun for high scalability
 
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
 
Fisl - Deployment
Fisl - DeploymentFisl - Deployment
Fisl - Deployment
 
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
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
Tweaking performance on high-load projects
Tweaking performance on high-load projectsTweaking performance on high-load projects
Tweaking performance on high-load projects
 
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.
 
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloudfog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloud
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
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
panagenda
 

Último (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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...
 
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
 
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
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
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
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Non-blocking I/O, Event loops and node.js

  • 1. This is a 15 minute presentation I did at work recently about threads, polling and node.js. It rests heavily on the shoulders of giants, especially Ryan Dahls original node.js talk at jsconf.eu.
  • 4. Why do we use threads?
  • 5. Policy p = cmServer.getPolicy(...); System.out.println(p.getContentId().toString());
  • 6. Policy p = cmServer.getPolicy(...); System.out.println(p.getContentId().toString());
  • 7. Policy p = cmServer.getPolicy(...); Blocking implies multiple execution stacks. Where else to go? System.out.println(p.getContentId().toString());
  • 8. How to deal with blocking? Processes No shared memory Heavy OS Threads Can share memory Relatively cheap Green threads / Co-routines
  • 10. HTTP request latency; glibc 2.3.2 on Linux 2.6 HTTP-anropslatens; glibc 2.3.2 på Linux 2.6 1 thread per call 1 process per call http://bulk.fefe.de/scalable-networking.pdf Open connections
  • 11. HTTP request latency; glibc 2.3.2 on Linux 2.6 1 thread per call 1 process per call Which is the reason why we use thread pools! Open connections
  • 13. nginx vs apache http://blog.webfaction.com/a-little-holiday-present
  • 14. nginx vs apache http://blog.webfaction.com/a-little-holiday-present ∆ = Apaches context switching
  • 15. lmbench ./lat_ctx -N 10 -s 4096 0 1 .. 20 80 74 68 62 56 50 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
  • 16. lmbench ./lat_ctx -N 10 -s 4096 0 1 .. 20 80 74 68 62 56 50 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 On a MBP, OS X 10.6 Context switch around 65 µs
  • 17. 65 µs x 2 x 4000 = 520 ms
  • 19. > ulimit -a | grep stack stack size (kbytes, -s) 8192
  • 20. ...but at least 512+1 kb For OS X, source: ADC
  • 21. nginx vs apache http://blog.webfaction.com/a-little-holiday-present
  • 22. nginx vs apache http://blog.webfaction.com/a-little-holiday-present Difference: Threads and processes cost.
  • 24. The cost of I/O L1-cache 3 cycles L2-cache 14 cycles RAM 250 cycles Disk 41 000 000 cycles Network 240 000 000 cycles
  • 26. The weight of I/O L1-cache A big squirrel
  • 27. The weight of I/O L1-cache A big squirrel L2-cache A medium-sized cat
  • 28. The weight of I/O L1-cache A big squirrel L2-cache A medium-sized cat RAM Mattias, basically
  • 29. The weight of I/O L1-cache A big squirrel L2-cache A medium-sized cat RAM Mattias, basically Disk Like a 100 blue whales
  • 30. The weight of I/O L1-cache A big squirrel L2-cache A medium-sized cat RAM Mattias, basically Disk Like a 100 blue whales Network Belarus yearly wheat import
  • 31. Servers pretty I/O-intensive = Squirrelʼs burried in whales fat and wheat
  • 32. Policy p = cmServer.getPolicy(...); System.out.println(p.getContentId().toString());
  • 33. cmServer.getPolicy(function (Policy p) { System.out.println( p.getContentId().toString() ); });
  • 34. cmServer.getPolicy(function (Policy p) { System.out.println( Sleeps until p’s available p.getContentId().toString() ); });
  • 35. cmServer.getPolicy(function (Policy p) { System.out.println( Sover tills dess p finns p.getContentId().toString() ); }); // And down here we can do other stuff
  • 36. Non-blocking I/O... All code is run in a single thread Functions listen on events, act and sleep
  • 37. ...is pretty demanding All I/O has to be non-blocking Callbacks are pretty ugly without HOF
  • 39. “a purely evented, non-blocking infrastructure to script highly concurrent programs.”
  • 40. V8 Chromes JS engine JS Built to be event driven node.js Queues built on /dev/epoll amongst other things
  • 41. var http = require('http'); http.createServer(function (req, res) { setTimeout(function () { res.sendHeader(200, {'Content-Type': 'text/plain'}); res.sendBody('Hello World'); res.finish(); }, 2000); }).listen(8080);
  • 42. % node hello.js % ab -n 1000 -c 200 http://127.0.0.1:8080/ ... Time per request: 2010.070 [ms] (mean) min mean[+/-sd] median max Connect: 0 2 1.9 1 8 Processing: 2001 2006 2.8 2005 2013 Waiting: 2000 2003 2.0 2003 2009 Total: 2002 2008 3.5 2006 2015 Percentage of the requests served within a certain time (ms) 50% 2006 66% 2008 75% 2012 80% 2013 90% 2013 95% 2014 98% 2014 99% 2014 100% 2015 (longest request)
  • 43. var stat = require('posix').stat, puts = require('sys').puts; var promise = stat('/etc/passwd'); promise.addCallback(function (s) { puts('modified: ' + s.mtime); });
  • 44. var web = require('./web'); web.server(function (route) { route.get("^/([a-z]+)$", function(parms, req, res) { res.sendHeader(200, {'Content-Type':'text/plain'}); res.sendBody("Hello " + parms[0]); res.finish(); }); }).listen(8080);
  • 45. % node web.test.js % ab -n 10000 -c 250 http://127.0.0.1:8080/marcus ... Requests per second: 4851.93 [#/sec] (mean) Time per request: 51.526 [ms] (mean) Time per request: 0.206 [ms] (mean, across all c requests) Connection Times (ms) min mean[+/-sd] median max Connect: 0 14 111.8 1 999 Processing: 4 35 15.8 31 103 Waiting: 4 35 15.8 30 103 Total: 14 49 112.5 32 1035 Percentage of the requests served within a certain time (ms) 50% 32 66% 34 75% 35 80% 36 90% 57 95% 92 98% 102 99% 986 100% 1035 (longest request)
  • 46. var web = require('./web'), posix = require('posix'); web.server(function (route) { route.get("^/([a-z]+)$", function(parms, req, res) { posix.cat(parms[0]).addCallback(function(text) { res.sendHeader(200, {'Content-Type':'text/plain'}); res.sendBody(text); res.finish(); }); }); }).listen(8080);
  • 47. throughput 80 74 68 62 56 50 1 5 13 25 50 100 250
  • 49. Distributed ab One configuration, multiple nodes REST interface Streams JSON over HTTP Decent performance
  • 50. demo!