SlideShare a Scribd company logo
Evented programming in node.js
and ruby
Overview
• Evented Programming
• Evented Web Backends
• Evented Ruby vs Evented Javascript
• Improving Rails Concurrency
Evented Programming
$(‘body’).click(function(){
$(this).css(‘color’, ‘red’);
});
Event Callback
Reactor Pattern
Reactor Pattern
• Events: keyboard, mouse, touch
• Reusable reactors: browser
Node.js
• Node.js is an event driven, non-blocking I/O
model that makes it lightweight efficient,
perfect for data intensive real time that run
across distributed devices.
Blocking I/O
If RAM was an F-18 Hornet with a max speed of
1,190 mph, disk access is a banana slug with a
top speed of 0.007 mph
Blocking I/O
F = Fast F18 Hornet
S = Slow Banana Slug
data = File.read(‘file.txt’)
FSSSSSSSSSSSSSSSSSF
CPU is idle
Blocking I/O
• Switches b/w busy processes
• OS and h/w caches hides complexity
Blocking I/O
Node.js switches b/w I/O within the same
process
Web Apps
• Blocking I/O decreases concurrency
• Database, file system – disk
• S3, external APIs – network
• ImageMagick – shelling out
Rails Concurrency
tweet = Tweet.new(params[‘tweet’]) # 1.
tweet.shorten_links! # 2. network
tweet.save # 3. disk
Rails Concurrency
Rails Concurrency
• Process Concurrency
• Lots of memory
Node Concurrency
tweet = new Tweet(); // 1.
tweet.shorten_links(function(tweet) { // 2. callback
tweet.save(function(){ // 3. callback
})
})
Node Concurrency
Node Concurrency
• Reactor switches b/w requests
• Fewer processes needed => Less memory
Latency
• Blocking I/O does not speed up
• Optimize response latency first
Code Smell
tweet = new Tweet(); // 1.
tweet.shorten_links(function(tweet) { // 2. callback
tweet.save(function(){ // 3. callback
})
})
• App code aware of blocking I/O
• Ugly syntax, nested contexts
Node use cases
• Chat Server
• Fast File Upload Client
• API’s
• Proxy server(In SOA)
• Data Streaming
• Any Real Time Data Apps
Who are using node
How event driven programming can be
done in ruby
Think ruby way
• Instead of waiting for something to happen
before executing code,
• Put that code in proc,
• Invoke the proc when something happens
Writing asyc code
• Synchronous ruby code uses return values
– ret = operation()
– do_something_with(ret)
• Evented async code uses blocks instead
– operation{ |ret| do_something_with(ret) }
• Different from how you usually use ruby
blocks. The is stored and invoked later(it’s
asynchronous)
Evented Ruby
• Ruby is capable of evented programming
• Multi-paradigm: procedural, evented, parallel
• Mix and match paradigms
Ruby Reactors
• Reactor is just a gem
• Eventmachine, cool.io, others
Basic concepts
• Threads
• Fibers
Threads
• Shared state and memory space
• Light weight
• Preemptive scheduling
Downsides
• Race conditions
• Deadlocks
• Hard to debug
• GIL
Fibers
• Cooperative scheduling
• Relatively lightweight
• Maintains state
Upsides
• No races
• No need of locks
• Parallelism
• Explicit yielding and resuming
Add Events
http = EM::HttpRequest.new(‘http://vinsol-meetup.com/’).get
http.callback {
# request finished
}
OK, so how do I use EM?
• gem install ‘eventmachine’
• require ‘eventmachine’
Deferring work
• The reactor itself is single threaded and the
EM methods which work with the reactor are
not thread-safe.
• This has two outcomes.
– code that takes a long time to run and moved to a
bg thread(db queries, http requests etc.)
– Once moved to bg thread, we have ability to tell
reactor to do work for us
• This is where EM#defer comes into play.
EM#defer(op, cb)
• We can schedule the execution of a block to
one of the threads in EventMachines thread
pool.
• EM#thread_pool_size = 20(default)
• EM#defer takes a second parameter, the
callback. This callback will be executed on the
main reactor thread and will be provided with
the return value of our deferred operation.
Code Smell
http = EM::HttpRequest.new(‘http://vinsol-com.com/’).get
http.callback {
# request finished
}
• App code aware of blocking I/O
• Code doesn’t look like ruby
Procedural Interface,
Evented Execution
Faraday.default_adapter = :em_synchrony
response = Faraday.get ‘http://vinsol-taf.com/’
• Hides system event callbacks in libraries
• Keeps app code clean
Procedural Interface,
Evented Execution
Procedural Interface,
Evented Execution
Code Smell?
One Requests per Fiber
• Wrap each req in its own fiber
• Web reqs are independent of each other
• Switch between requests instead of processes
Rack::FiberPool
Recap
• App server is reactor aware
• One fiber per request
• App code is unchanged
Mixing Paradigms
• Libraries may block the reactor
But that’s ok…
Starting Points
• Data stores
• http
• Kernel.system calls
Data Stores
• Redis
• Mysql
• Postgresql
• mongo
HTTP
• Faraday: use an event aware http adapter
System Calls
• EM.popen – non-blocking version
• EM.defer – run blocking call outside of reactor
thread
Final Result
Why Ruby
• Reuse existing code
• Performance won’t be worse
• Keep procedural syntax
• Multi-paradigm
Why Node
• Single paradigm consistency
• Community
Wrapping up
• Evented programming is hard in any language
• Evented programming for evented problems
• Evented programming doesn’t fix latency
• Avoid evented I/O interface in app code
Thanks!

More Related Content

PPTX
Asynchronous Python with Twisted
PDF
WTF is Twisted?
ZIP
How we use Twisted in Launchpad
PDF
High-Performance Networking Using eBPF, XDP, and io_uring
KEY
Twisted: a quick introduction
PDF
Whoops! I Rewrote It in Rust
PDF
An Introduction to Twisted
KEY
Zero mq logs
Asynchronous Python with Twisted
WTF is Twisted?
How we use Twisted in Launchpad
High-Performance Networking Using eBPF, XDP, and io_uring
Twisted: a quick introduction
Whoops! I Rewrote It in Rust
An Introduction to Twisted
Zero mq logs

What's hot (20)

KEY
Distributed app development with nodejs and zeromq
PPT
Ruby eventmachine pres at rubybdx
KEY
Concurrency in ruby
PDF
ZeroMQ with NodeJS
PDF
The art of concurrent programming
PPT
Leveraging zeromq for node.js
PDF
OSNoise Tracer: Who Is Stealing My CPU Time?
PDF
Optcarrot: A Pure-Ruby NES Emulator
PPT
Ruby vs Node ShiningRay Shanghai
PPT
ruby + websocket + haproxy
PDF
Rust Is Safe. But Is It Fast?
PPTX
Basics of Node.js
PDF
Extreme HTTP Performance Tuning: 1.2M API req/s on a 4 vCPU EC2 Instance
PDF
Twisted Introduction
PDF
Event Machine
PDF
Solving some of the scalability problems at booking.com
ODP
Developing high-performance network servers in Lisp
ODP
Grape golilath
PDF
RISC-V on Edge: Porting EVE and Alpine Linux to RISC-V
PDF
[En] IPVS for Docker Containers
Distributed app development with nodejs and zeromq
Ruby eventmachine pres at rubybdx
Concurrency in ruby
ZeroMQ with NodeJS
The art of concurrent programming
Leveraging zeromq for node.js
OSNoise Tracer: Who Is Stealing My CPU Time?
Optcarrot: A Pure-Ruby NES Emulator
Ruby vs Node ShiningRay Shanghai
ruby + websocket + haproxy
Rust Is Safe. But Is It Fast?
Basics of Node.js
Extreme HTTP Performance Tuning: 1.2M API req/s on a 4 vCPU EC2 Instance
Twisted Introduction
Event Machine
Solving some of the scalability problems at booking.com
Developing high-performance network servers in Lisp
Grape golilath
RISC-V on Edge: Porting EVE and Alpine Linux to RISC-V
[En] IPVS for Docker Containers
Ad

Similar to Evented Ruby VS Node.js (20)

PDF
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
PPT
JavaScript Event Loop
PPTX
introduction to node.js
KEY
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
PPTX
GeekCampSG - Nodejs , Websockets and Realtime Web
PDF
Basic Understanding and Implement of Node.js
PDF
Node js internal
PDF
FITC - Node.js 101
PPT
Large-scale projects development (scaling LAMP)
PDF
Highly concurrent yet natural programming
PDF
Nodejs - Should Ruby Developers Care?
PPTX
Why Play Framework is fast
PDF
Introduction to Node.js
PPTX
Node.js: The What, The How and The When
PPTX
Node.js
PPTX
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
PDF
Introduction to Node.js: What, why and how?
PDF
Nodejs a-practical-introduction-oredev
PDF
Ruby performance - The low hanging fruit
PDF
Bringing Concurrency to Ruby - RubyConf India 2014
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
JavaScript Event Loop
introduction to node.js
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
GeekCampSG - Nodejs , Websockets and Realtime Web
Basic Understanding and Implement of Node.js
Node js internal
FITC - Node.js 101
Large-scale projects development (scaling LAMP)
Highly concurrent yet natural programming
Nodejs - Should Ruby Developers Care?
Why Play Framework is fast
Introduction to Node.js
Node.js: The What, The How and The When
Node.js
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
Introduction to Node.js: What, why and how?
Nodejs a-practical-introduction-oredev
Ruby performance - The low hanging fruit
Bringing Concurrency to Ruby - RubyConf India 2014
Ad

Recently uploaded (20)

PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Electronic commerce courselecture one. Pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Cloud computing and distributed systems.
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
KodekX | Application Modernization Development
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
MYSQL Presentation for SQL database connectivity
Mobile App Security Testing_ A Comprehensive Guide.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Diabetes mellitus diagnosis method based random forest with bat algorithm
NewMind AI Weekly Chronicles - August'25 Week I
Building Integrated photovoltaic BIPV_UPV.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
Encapsulation_ Review paper, used for researhc scholars
Electronic commerce courselecture one. Pdf
Understanding_Digital_Forensics_Presentation.pptx
Cloud computing and distributed systems.
“AI and Expert System Decision Support & Business Intelligence Systems”
Dropbox Q2 2025 Financial Results & Investor Presentation
NewMind AI Monthly Chronicles - July 2025
Unlocking AI with Model Context Protocol (MCP)
Spectral efficient network and resource selection model in 5G networks
KodekX | Application Modernization Development

Evented Ruby VS Node.js