SlideShare a Scribd company logo
1 of 55
Deep Dive into
Event Loop
Shubham Chaurasia (schaurasia@)
AGENDA
● What is the event loop?
● Is Node.js single or multi-threaded? (or when?)
● Why Node.js scale well?
● Traditional Web Applications
● What is Node.js?
● Node.js Architecture
● Node.js Runtime
● Event Loop
● What is Libuv?
● Libuv Architecture
● When to use Node.js?
● Companies Using Node in Production
● Conclusion
TRADITIONAL WEB
APPLICATIONs
TRADITIONAL WEB APPLICATIONS
● Thread-based networking ( concurrency model, in which OS threads are employed)
● Drops connections when threads limit is reached.
● Threads limit is reached because threads are waiting/blocked for I/O.
● Thread context switching is not free.
● High Memory consumption per request (Thread takes more memory than just creating a new
tcp connection).
● Difficult to Manage concurrency.
● Dead lock
TRADITIONAL WEB APPLICATIONS
Concurrency x reqs/sec
APACHE vs NGINX
Concurrency x memory
APACHE vs NGINX
What’s the difference?
Apache uses one thread per connection.
NGINX doesn’t use threads. It uses an event loop.
APACHE vs NGINX
How Node.js Solves It?
● Node.js offloads the I/O call to libuv/linux Kernel
● Can handle more connections (High Throughput)
● Single Threaded (No Context switching overhead)
● CPU can be used well (As context switching is less)
● Low Memory consumption
● Easy to Manage concurrency
● No Threads, No Dead lock.
● Easy to Write code without worrying about thread locks and being thread safe.
● Node.js allows developers to write JavaScript for both the server and client side.
NODE.JS SOLUTION
Blocking vs Non-Blocking
BLOCKING vs NON-BLOCKING
What is Node.js?
● Asynchronous event-driven JavaScript runtime.
● Server-side Javascript.
● Built on Google’s V8 engine.
● Purely evented, non-blocking I/O. Influenced by system like EventMachine or Twisted.
● 8k lines of C/C++, 2k lines of Javascript (maybe some more PRs got merged)
● Designed to build scalable network applications.
● Designed because I/O needs to be done differently.
● It has an Event Loop for orchestration and a Worker Pool for expensive tasks.
NODE.JS
● No function should directly perform I/O. To receive info from disk, network, or another
process there must be a callback. (Thinking about async / await)
● Have Built in support for the most important protocols. TCP, DNS, HTTP
● Have support for many HTTP features.
○ Chunked requests and responses.
○ Keep-alive etc.
● Be platform independent.
● As Node is designed without threads, doesn't mean you cannot take advantage of
multiple cores in your environment.
○ child_process.fork()
○ cluster module
NODE.JS DESIGN GOALS
Is Node Really Single Threaded?
Node.js Architecture
NODE.JS HIGH LEVEL ARCHITECTURE
NODE.JS HIGH LEVEL ARCHITECTURE
Node Runtime
NODE.JS RUNTIME
Node Event Loop
NODE EVENT LOOP
NODE EVENT LOOP
NODE EVENT LOOP
NODE EVENT LOOP
NODE EVENT LOOP
NODE EVENT LOOP
What is Libuv?
● Libuv is a multi-platform support library with a focus on asynchronous I/O
and more.
● Small (relatively) C library : ~ 30K LOC (without tests)
● Designed for Node.js and C programs that miss the joy of javascript callback hell.
● Used by many other projects. https://github.com/libuv/libuv/wiki/Projects-that-use-libuv.
● Libuv is the heart of Node.js architecture.
● It abstract internal I/O complexities and provide a generalized interface to upper layers of
Node, so that Node can perform platform independent asynchronous I/O without
worrying about what platform it is run on.
LIBUV
● Full-featured Event Loop backed by epoll, kqueue, IOCP, event ports
● Asynchronous TCP and UDP sockets
● Asynchronous DNS resolution (dns.lookup)
● Asynchronous file and file system operations (fs.readFile, fs.readFileSync)
● High resolution clock and Timer (setTimeout, setInterval)
● Child processes (child_process.fork, process.nextTick)
● Thread pool and Threading utilities
● Signal handling
● Coolest Logo ever :)
LIBUV FEATURES
Libuv Architecture
The event loop: uv_loop_t (Single Threaded)
LIBUV ARCHITECTURE
● Libuv event loop is single threaded.
● Libuv only use threads for file i/o and getaddrinfo(dns lookup).
● http://blog.libtorrent.org/2012/10/asynchronous-disk-io/
● Default thread pool size is 4 (runtime env var: UV_THREADPOOL_SIZE)
● NOT FOR NETWORK I/O
● NOT FOR NETWORK I/O
● NOT FOR NETWORK I/O
LIBUV THREADS
Node uses the thread Pool to handle "expensive" tasks. This includes I/O for
which an operating system does not provide a non-blocking version, as well as
particularly CPU-intensive tasks.
1. I/O-intensive
1. DNS: dns.lookup(), dns.lookupService().
2. File System: All file system APIs except fs.FSWatcher() and those that are explicitly
synchronous use libuv's threadpool.
2. CPU-intensive
1. Crypto: crypto.pbkdf2(), crypto.scrypt(), crypto.randomBytes(), crypto.randomFill(),
crypto.generateKeyPair().
2. Zlib: All zlib APIs except those that are explicitly synchronous use libuv's threadpool.
NODE.JS THREAD POOL
NODE EVENT LOOP
Libuv Event Loop
LIBUV EVENT LOOP
Is Node Really Single Threaded?
● Node.js internally uses a library called Libuv. Which basically does most of the magic for
node.
● Libuv is multithreaded and uses preallocated set of threads called Thread Pool. The
default size of thread pool is 4.
● All javascript, V8 and event loop executes on the same thread called main thread.
● Node.js Event loop is part of Libuv library and does not resides inside node.js code base.
IS NODE REALLY SINGLE THREADED?
When to use Node?
For keeping your Node server speedy: Node is fast when the work associated with each
client at any given time is "small".
This applies to callbacks on the Event Loop and tasks on the Worker Pool.
WHEN TO USE NODE?
Companies Using Node In
Production
Companies Using Node
Credits
● https://nodejs.org/en/docs/
● https://github.com/nodejs/node
● http://docs.libuv.org/en/v1.x/index.html
● https://github.com/libuv/libuv
CREDITS
Conclusion
Thank You!

More Related Content

Similar to Deep Dive into Node.js Event Loop.pdf

Similar to Deep Dive into Node.js Event Loop.pdf (20)

Node Architecture.pptx
Node Architecture.pptxNode Architecture.pptx
Node Architecture.pptx
 
Monkey Server
Monkey ServerMonkey Server
Monkey Server
 
node.js
node.jsnode.js
node.js
 
Netty training
Netty trainingNetty training
Netty training
 
Let's Containerize New York with Docker!
Let's Containerize New York with Docker!Let's Containerize New York with Docker!
Let's Containerize New York with Docker!
 
026 Neo4j Data Loading (ETL_ELT) Best Practices - NODES2022 AMERICAS Advanced...
026 Neo4j Data Loading (ETL_ELT) Best Practices - NODES2022 AMERICAS Advanced...026 Neo4j Data Loading (ETL_ELT) Best Practices - NODES2022 AMERICAS Advanced...
026 Neo4j Data Loading (ETL_ELT) Best Practices - NODES2022 AMERICAS Advanced...
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
Netty training
Netty trainingNetty training
Netty training
 
Free the Functions with Fn project!
Free the Functions with Fn project!Free the Functions with Fn project!
Free the Functions with Fn project!
 
02 Node introduction
02 Node introduction02 Node introduction
02 Node introduction
 
Построение простого REST сервера на Node.js | Odessa Frontend Code challenge
Построение простого REST сервера на Node.js | Odessa Frontend Code challengeПостроение простого REST сервера на Node.js | Odessa Frontend Code challenge
Построение простого REST сервера на Node.js | Odessa Frontend Code challenge
 
Ansible and CloudStack
Ansible and CloudStackAnsible and CloudStack
Ansible and CloudStack
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
OpenStack Cinder Best Practices - Meet Up
OpenStack Cinder Best Practices - Meet UpOpenStack Cinder Best Practices - Meet Up
OpenStack Cinder Best Practices - Meet Up
 
Node.js an Exectutive View
Node.js an Exectutive ViewNode.js an Exectutive View
Node.js an Exectutive View
 
Understand How Node.js and Core Features Works
Understand How Node.js and Core Features WorksUnderstand How Node.js and Core Features Works
Understand How Node.js and Core Features Works
 
HandlerSocket - A NoSQL plugin for MySQL
HandlerSocket - A NoSQL plugin for MySQLHandlerSocket - A NoSQL plugin for MySQL
HandlerSocket - A NoSQL plugin for MySQL
 
Blackray @ SAPO CodeBits 2009
Blackray @ SAPO CodeBits 2009Blackray @ SAPO CodeBits 2009
Blackray @ SAPO CodeBits 2009
 
18_Node.js.ppt
18_Node.js.ppt18_Node.js.ppt
18_Node.js.ppt
 
Thread
ThreadThread
Thread
 

Recently uploaded

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Recently uploaded (20)

WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
WSO2Con2024 - Simplified Integration: Unveiling the Latest Features in WSO2 L...
 
WSO2CON 2024 - Lessons from the Field: Legacy Platforms – It's Time to Let Go...
WSO2CON 2024 - Lessons from the Field: Legacy Platforms – It's Time to Let Go...WSO2CON 2024 - Lessons from the Field: Legacy Platforms – It's Time to Let Go...
WSO2CON 2024 - Lessons from the Field: Legacy Platforms – It's Time to Let Go...
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration Tooling
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Driving Innovation: Scania's API Revolution with WSO2
Driving Innovation: Scania's API Revolution with WSO2Driving Innovation: Scania's API Revolution with WSO2
Driving Innovation: Scania's API Revolution with WSO2
 
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of TransformationWSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
WSO2CON 2024 - Designing Event-Driven Enterprises: Stories of Transformation
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & Innovation
WSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & InnovationWSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & Innovation
WSO2CON 2024 - OSU & WSO2: A Decade Journey in Integration & Innovation
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Era
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 

Deep Dive into Node.js Event Loop.pdf

  • 1. Deep Dive into Event Loop Shubham Chaurasia (schaurasia@)
  • 2. AGENDA ● What is the event loop? ● Is Node.js single or multi-threaded? (or when?) ● Why Node.js scale well? ● Traditional Web Applications ● What is Node.js? ● Node.js Architecture ● Node.js Runtime ● Event Loop ● What is Libuv? ● Libuv Architecture ● When to use Node.js? ● Companies Using Node in Production ● Conclusion
  • 5. ● Thread-based networking ( concurrency model, in which OS threads are employed) ● Drops connections when threads limit is reached. ● Threads limit is reached because threads are waiting/blocked for I/O. ● Thread context switching is not free. ● High Memory consumption per request (Thread takes more memory than just creating a new tcp connection). ● Difficult to Manage concurrency. ● Dead lock TRADITIONAL WEB APPLICATIONS
  • 8. What’s the difference? Apache uses one thread per connection. NGINX doesn’t use threads. It uses an event loop. APACHE vs NGINX
  • 10.
  • 11. ● Node.js offloads the I/O call to libuv/linux Kernel ● Can handle more connections (High Throughput) ● Single Threaded (No Context switching overhead) ● CPU can be used well (As context switching is less) ● Low Memory consumption ● Easy to Manage concurrency ● No Threads, No Dead lock. ● Easy to Write code without worrying about thread locks and being thread safe. ● Node.js allows developers to write JavaScript for both the server and client side. NODE.JS SOLUTION
  • 15. ● Asynchronous event-driven JavaScript runtime. ● Server-side Javascript. ● Built on Google’s V8 engine. ● Purely evented, non-blocking I/O. Influenced by system like EventMachine or Twisted. ● 8k lines of C/C++, 2k lines of Javascript (maybe some more PRs got merged) ● Designed to build scalable network applications. ● Designed because I/O needs to be done differently. ● It has an Event Loop for orchestration and a Worker Pool for expensive tasks. NODE.JS
  • 16. ● No function should directly perform I/O. To receive info from disk, network, or another process there must be a callback. (Thinking about async / await) ● Have Built in support for the most important protocols. TCP, DNS, HTTP ● Have support for many HTTP features. ○ Chunked requests and responses. ○ Keep-alive etc. ● Be platform independent. ● As Node is designed without threads, doesn't mean you cannot take advantage of multiple cores in your environment. ○ child_process.fork() ○ cluster module NODE.JS DESIGN GOALS
  • 17. Is Node Really Single Threaded?
  • 19. NODE.JS HIGH LEVEL ARCHITECTURE
  • 20. NODE.JS HIGH LEVEL ARCHITECTURE
  • 23.
  • 32. ● Libuv is a multi-platform support library with a focus on asynchronous I/O and more. ● Small (relatively) C library : ~ 30K LOC (without tests) ● Designed for Node.js and C programs that miss the joy of javascript callback hell. ● Used by many other projects. https://github.com/libuv/libuv/wiki/Projects-that-use-libuv. ● Libuv is the heart of Node.js architecture. ● It abstract internal I/O complexities and provide a generalized interface to upper layers of Node, so that Node can perform platform independent asynchronous I/O without worrying about what platform it is run on. LIBUV
  • 33. ● Full-featured Event Loop backed by epoll, kqueue, IOCP, event ports ● Asynchronous TCP and UDP sockets ● Asynchronous DNS resolution (dns.lookup) ● Asynchronous file and file system operations (fs.readFile, fs.readFileSync) ● High resolution clock and Timer (setTimeout, setInterval) ● Child processes (child_process.fork, process.nextTick) ● Thread pool and Threading utilities ● Signal handling ● Coolest Logo ever :) LIBUV FEATURES
  • 35. The event loop: uv_loop_t (Single Threaded) LIBUV ARCHITECTURE
  • 36. ● Libuv event loop is single threaded. ● Libuv only use threads for file i/o and getaddrinfo(dns lookup). ● http://blog.libtorrent.org/2012/10/asynchronous-disk-io/ ● Default thread pool size is 4 (runtime env var: UV_THREADPOOL_SIZE) ● NOT FOR NETWORK I/O ● NOT FOR NETWORK I/O ● NOT FOR NETWORK I/O LIBUV THREADS
  • 37. Node uses the thread Pool to handle "expensive" tasks. This includes I/O for which an operating system does not provide a non-blocking version, as well as particularly CPU-intensive tasks. 1. I/O-intensive 1. DNS: dns.lookup(), dns.lookupService(). 2. File System: All file system APIs except fs.FSWatcher() and those that are explicitly synchronous use libuv's threadpool. 2. CPU-intensive 1. Crypto: crypto.pbkdf2(), crypto.scrypt(), crypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair(). 2. Zlib: All zlib APIs except those that are explicitly synchronous use libuv's threadpool. NODE.JS THREAD POOL
  • 38.
  • 39.
  • 40.
  • 41.
  • 45.
  • 46. Is Node Really Single Threaded?
  • 47. ● Node.js internally uses a library called Libuv. Which basically does most of the magic for node. ● Libuv is multithreaded and uses preallocated set of threads called Thread Pool. The default size of thread pool is 4. ● All javascript, V8 and event loop executes on the same thread called main thread. ● Node.js Event loop is part of Libuv library and does not resides inside node.js code base. IS NODE REALLY SINGLE THREADED?
  • 48. When to use Node?
  • 49. For keeping your Node server speedy: Node is fast when the work associated with each client at any given time is "small". This applies to callbacks on the Event Loop and tasks on the Worker Pool. WHEN TO USE NODE?
  • 50. Companies Using Node In Production
  • 53. ● https://nodejs.org/en/docs/ ● https://github.com/nodejs/node ● http://docs.libuv.org/en/v1.x/index.html ● https://github.com/libuv/libuv CREDITS