This document discusses evented programming in Node.js and Ruby. It explains that evented programming uses callbacks and asynchronous non-blocking I/O. Node.js uses this approach to improve concurrency over blocking I/O models. Ruby can also implement evented programming using libraries like EventMachine that provide asynchronous abstractions while keeping app code procedural. The document provides examples of building evented applications in both languages.
6. 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.
7. 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
8. Blocking I/O
F = Fast F18 Hornet
S = Slow Banana Slug
data = File.read(‘file.txt’)
FSSSSSSSSSSSSSSSSSF
CPU is idle
23. Think ruby way
• Instead of waiting for something to happen
before executing code,
• Put that code in proc,
• Invoke the proc when something happens
24. 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)
25. Evented Ruby
• Ruby is capable of evented programming
• Multi-paradigm: procedural, evented, parallel
• Mix and match paradigms
33. OK, so how do I use EM?
• gem install ‘eventmachine’
• require ‘eventmachine’
34. 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.
35. 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.
53. 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