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

More Related Content

PDF
Nodejs Explained with Examples
PDF
Angular and The Case for RxJS
PPTX
.Net Core
PDF
Nodejs presentation
PDF
Microservices Integration Patterns with Kafka
PDF
NodeJS for Beginner
PDF
An introduction to React.js
PPTX
Top 10 RxJs Operators in Angular
Nodejs Explained with Examples
Angular and The Case for RxJS
.Net Core
Nodejs presentation
Microservices Integration Patterns with Kafka
NodeJS for Beginner
An introduction to React.js
Top 10 RxJs Operators in Angular

What's hot (20)

PDF
React Js Simplified
PDF
Introduction to Node.js
PPTX
Node js introduction
PPTX
Reactjs
PDF
RxJS + Redux + React = Amazing
PPTX
Introduction Node.js
PPTX
Rxjs ngvikings
PDF
Event-sourced architectures with Akka
PPTX
ASP.NET Core MVC + Web API with Overview
PPTX
Node.js Express
PDF
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
PDF
Spring Framework - Core
PPTX
Express JS
PDF
Basics of React Hooks.pptx.pdf
PPTX
Basic Concept of Node.js & NPM
PDF
Introduction to WebSockets Presentation
PPTX
Creating custom Validators on Reactive Forms using Angular 6
PDF
Important React Hooks
PDF
Apache Pulsar Development 101 with Python
PPTX
Presentation on "An Introduction to ReactJS"
React Js Simplified
Introduction to Node.js
Node js introduction
Reactjs
RxJS + Redux + React = Amazing
Introduction Node.js
Rxjs ngvikings
Event-sourced architectures with Akka
ASP.NET Core MVC + Web API with Overview
Node.js Express
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Spring Framework - Core
Express JS
Basics of React Hooks.pptx.pdf
Basic Concept of Node.js & NPM
Introduction to WebSockets Presentation
Creating custom Validators on Reactive Forms using Angular 6
Important React Hooks
Apache Pulsar Development 101 with Python
Presentation on "An Introduction to ReactJS"
Ad

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

PPT
Server side JavaScript: going all the way
PPTX
Full Stack Load Testing
PDF
Original slides from Ryan Dahl's NodeJs intro talk
KEY
The HTML5 WebSocket API
KEY
Node.js - As a networking tool
PDF
Nodejs a-practical-introduction-oredev
KEY
Writing robust Node.js applications
PPT
JS everywhere 2011
PDF
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
PPT
Real-Time Python Web: Gevent and Socket.io
PPTX
introduction to node.js
ODP
Caching and tuning fun for high scalability
PDF
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
PDF
Fisl - Deployment
PDF
Future Decoded - Node.js per sviluppatori .NET
PPTX
Real World Lessons on the Pain Points of Node.JS Application
PDF
Presto anatomy
PDF
Tweaking performance on high-load projects
PDF
Node.js - async for the rest of us.
KEY
fog or: How I Learned to Stop Worrying and Love the Cloud
Server side JavaScript: going all the way
Full Stack Load Testing
Original slides from Ryan Dahl's NodeJs intro talk
The HTML5 WebSocket API
Node.js - As a networking tool
Nodejs a-practical-introduction-oredev
Writing robust Node.js applications
JS everywhere 2011
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Real-Time Python Web: Gevent and Socket.io
introduction to node.js
Caching and tuning fun for high scalability
Linux kernel TLS и HTTPS / Александр Крижановский (Tempesta Technologies)
Fisl - Deployment
Future Decoded - Node.js per sviluppatori .NET
Real World Lessons on the Pain Points of Node.JS Application
Presto anatomy
Tweaking performance on high-load projects
Node.js - async for the rest of us.
fog or: How I Learned to Stop Worrying and Love the Cloud
Ad

Recently uploaded (20)

PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
cuic standard and advanced reporting.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
Machine Learning_overview_presentation.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Getting Started with Data Integration: FME Form 101
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Big Data Technologies - Introduction.pptx
PPT
Teaching material agriculture food technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Electronic commerce courselecture one. Pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
cuic standard and advanced reporting.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A comparative analysis of optical character recognition models for extracting...
Machine Learning_overview_presentation.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Weekly Chronicles - August'25-Week II
Getting Started with Data Integration: FME Form 101
MIND Revenue Release Quarter 2 2025 Press Release
Per capita expenditure prediction using model stacking based on satellite ima...
Big Data Technologies - Introduction.pptx
Teaching material agriculture food technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Group 1 Presentation -Planning and Decision Making .pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Electronic commerce courselecture one. Pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
gpt5_lecture_notes_comprehensive_20250812015547.pdf

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!