SlideShare a Scribd company logo
1 of 64
Download to read offline
Lourens Naudé, Trade2Win


Embracing Events
Stop polling … react.
Bio
   http://github.com/methodmissing
       Ruby contractor
       General misfit for the current economy
     Ruby, C#, Java, admin 500 nodes, CSS * deferred payment
     Currently building out a consumer forex platform @ Trade2Win
      Slippage matter.
   creator
       scrooge, mysqlplus_adapter, mri_instrumentation
   contributor
       Rails, mysqlplus, query_memcached, thinking-sphinx,
        em-spec
e-vent [i-vent]
something that happens or is regarded as
happening; an occurrence, esp. one of
some importance.
A change in state ...
   MySQL server sends results down the wire
       Connection file descriptor becomes readable
            Process results
            Render results

   Ignorance is bliss
       Never be flooded
       Only handle events that matter
Talk#to_a
   Context switches
   Scheduling
   Programming models
   Frameworks
       Eventmachine
       Neverblock
   Operating System
   Lessons from massively multiplayer online games
   Testing
   Q&A?
Getting Fibers
(coroutines) and
    Threads
Scenario we all can relate to ...
   Quiet weekend day, erratic thoughts from the
    week before comes together
   Sharing space with your better half ... who's
    being chatty
   You're being interrupted at random
   Let's assume an average quot;in the zonequot; startup
    threshold of 2 minutes per interruption
   Deadlock's not an option ...
Multithreading
   Let the initial pattern of thought and the
    interruption be distinct Threads
   The interruption's effective right away
   The context switch is 'expensive' : coding VS
    whichever chore's been neglected
   Preemptive scheduling == constant interruption
Fiber / coroutine pool
   Two distinct Fibered contexts
   Able to defer the interruption
   Cheap switching : being thick skinned buys time
   You#resume the interruption if and when there's
    time to handle it
Thread
   Scheduling
       Handled by the VM – timesliced @ 10ms by MRI
       Executes as soon as CPU resources become available
   Availability
       MRI 18: Maps to a single native thread
       MRI 19: 1 x native thread for each Ruby thread - GIL
       JRuby: 1 x Java thread for each Ruby thread
   Overheads
       Large initial stack size
       MRI uses a SIGVTALRM to signal a context switch
Fiber
   Scheduling
       No concurrency – scheduled by application code
       Never executes right away
   Availability
       MRI 18: Patch by Aman Gupta && Joe Damato
       MRI 19: Core Fiber class
       JRuby: Poor Man's Fibers
   Overheads
       Small initial stack size @ 4k
       Context switches exclusively in user space – very fast
Why Fibers matter
   Computes a partial result - generator
   Yields back to the caller
   Saves execution state
   Caller resumes
   Data exchange
       Accept arguments through Fiber#resume
       Return values through Fiber.yield
Threads as Coroutines
   Through a voodo combination of
       Thread priorities
       Thread.pass
       Thread.stop
       Thread#run (yields CPU) or Thread#wakeup (no CPU)
   Poor Man's Fibers piggy backs off a Queue
   MRI 18 Fibers = Threads – preemptive
    scheduling, much like continuations, but with a
    smaller stack.
   Performant, but not as lightweight as Fibers
Cooperative scheduling
   Request / response with evented DB access
       HTTP request wrapped in a Fiber
       => mysql->fd : SELECT * FROM users WHERE id = 1
       Execution paused
       <= mysql->fd : #<User id: 1 uname: methodmissing>
       Execution resumed
       => mysql->fd: SELECT * FROM wishlist WHERE
        user_id = 1
       Execution paused
       <= mysql->fd: #<Wishlist id: 20 user_id 1>
Cooperative VS preemptive
   Fibered dispatch, query = *, result = +, int = &
       <GET /orders>       * + *+*+*+*+*+*+
       <POST /checkout>   * + * + *+*+
       <DELETE /sessions> *+

   Threaded dispatch, interupted every 10ms
       <GET /orders>       * & + *+*+&*+*+*&+*+
       <POST /checkout>   * + * +& *+*&+
       <DELETE /sessions> &*+
Scheduling
           active        time

Thread 1

                      idle                  10 ms
                                            quanta
Thread 2



                    idle              No scheduling time

 Fiber 1
                                   active    Run as long as you need

 Fiber 2


               Cooperative VS Preemptive
Event-driven Programming
   Program flow determined by events
   Characterized by an event handler, main
    loop or reactor
   The reactor typically 'owns' the process
   loop { button.on(:click).dispatch }
   Binds event handlers to events
   Deep nesting of callbacks and constructs
    eg. Twisted for Python
Batch programming
 wysiwig
 Flow determined by the developer
 Read → process → output
Event-driven
   execution,
synchronous API.
Database ...
class FiberedMysqlConnection
  def query( sql )
    send_query sql
    Fiber.yield
    get_result
  end
end

EM.run{ conn.query( 'SELECT SLEEP 1' ) }
… app server
class UsersController < AC::Base
  def index
     @users = User.paginate( :page => 1 )
   end
end
Thin::Server.start('0.0.0.0', 3000) do
 Fiber.new{ AC::Dispatcher.call( env ) }

end
Frameworks
Eventmachine
 Implementation of the Reactor pattern
 C++ with Ruby Bindings
 JRuby compatible through jeventmachine
 High performance event driven IO : epoll
  on Linux, kqueue on BSD and derivatives
The Reactor
   Maintains a global current loop time
   Quantum is just under 100ms … adjustable
   Verifies descriptors through a heartbeat
   Runs timer events
   New descriptors dropped onto a different
    queue
   Modified descriptors processed outside loop
   Stopped with special Loop Break Descriptor
Bindings and Callbacks
 A portable signature registry / list,
  implemented as UUID identifiers
 Callback triggers :
       timer fired
       connection    read
       connection    completed
       connection    accepted
       connection    unbound
Eventable File Descriptors
 Nonblocking
 Notify of read and writability
 Closed in 3 ways
       hard
       immediate ( when possible, next tick )
       after writing ( protocol handlers, serve HTTP page,
        close connection
Deferrables
 A callback ... specifically a callback for
  :success or :failure
 Immediately pushed to the background and
  scheduled for future execution
 Deferrables should have an associated
  timeout
Timers
 Periodic or oneshot
 Set a max timer count to avoid flooding the
  reactor
 Can be cancelled
Files
 Very fast transfer of < 32k files with
  EM#send_file_data
 File watch API
       Notified when modified, deleted or moved
   fastfilereader extension
       Memory <=> disk transfer with mmap
Processes
 Supports deferrable child processes
  through pipes
 EM#system
 Process watch API
       Notified when forked or exits
Client / Server
module Challenge
 def post_init
  send_data 'psw?'
 end
 def receive_data( data )
  ( @data ||= '' ) << data
 end
end
EM.run{ EM.connect 'localhost', 80, Challenge }
Neverblock
Why ?
   Most web apps block on IO
   Ruby processes has 'high' memory
    overheads
   60MB RSS blocking 30ms on IO == $$$
   Allocated in slabs – 80MB -> 120MB
   Significantly reduces capacity for
    concurrent requests
   eSpace stepped in
How ?
   Fibered connection pool – typically 8 to 12
   Attaches to either EM or Rev as main loop
   Patches for Evented Mongrel && Thin to
    wrap requests in Fibers
   Fibered DB connections for postgres &&
    mysql ( with mysqlplus )
   Respects transactions - BEGIN ... COMMIT
    required to be on the same connection
Fiber 1
                          (active
                             )


Connection 1 (idle)



Connection 2 (idle)


                                Fiber 2
                              (inactive)
   Fiber 1 is executing
Fiber 1
                                             (inactive
                                                 )
                                         SELECT ...

              Connection 1 (busy)



              Connection 2 (idle)


                                                      Fiber 2
                                                      (active)
Fiber 1 issues a SQL query and passes control to Fiber 2
Fiber 1
                                            (inactive
                                                )


             Connection 1 (busy)



             Connection 2 (busy)       UPDATE …




                                                  Fiber 2
                                                  (inactiv
                                                     e)
Fiber 2 issues a SQL query and both fibers are inactive
Fiber 1
                                                    (active)



                                             Alfred, 28, …
                   Connection 1 (idle)
                                             Tamer, 20, …
                                                   .
                                                   .

                  Connection 2 (busy)


                                                             Fiber 2
                                                             (inactiv
                                                                e)
Reactor notices first connection is finished so it resumes Fiber 1
Fiber 1
                                                    (done)



                  Connection 1 (idle)



                  Connection 2 (idle)

                                        3600 rows affected

                                                             Fiber 2
                                                             (active)
Fiber 1 is done and reactor notices second connection is finished
                       so it resumes Fiber 2
Patches to Ruby IO
   Clever redirection to non-blocking methods
       IO#read* => IO#read_nonblock
       IO#write* => IO#write_nonblock
   Catches IO errors
       Errno::EWOULDBLOCK
       Errno::EAGAIN
       Errno::EINTR
   Rescue attaches to the event loop
       Requests notification of read / writability
       Detach on success
Operating System
     Events
Signals
 Software interrupts
 Portable
       Signal.list supported on all host systems
   Unobtrusive
       Caught Signal.trap( 'IO' ){ puts 'readable' }
       Sent with Process.kill( 'IO', $ )
 Can be scoped to a single process or a
  process group
 Daemons: SIGHUP && SIGTERM
Handling Signals
   Ignore them – except KILL && STOP
   Catch with trap('IO'){}
   Let the default action apply
   SIGVTALRM is reserved for threading
   Signals the process every 10ms
   Flags that it's time to schedule
   Green threading maps to 1 OS thread, 1
    per process, signals scoped per process
Processes
   Process groups
       Leader ? Process#pid == process group identifier
       Group persist when leader exists as long as there's
        some members
Multi-process Quality of Service
   Signals to enforce QOS
       URG: Slow down
       CONT: Resume normal operation
       XCPU: Crawl
 Monitoring agent sends URG during load
  spike
 Sends CONT when load drops
 XCPU during extremely high load,
  effectively pausing the worker(s)
POSIX Realtime Extensions
   Well supported, but implementations differ
       Linux Kernel 2.6
       FreeBSD / Darwin
       Solaris
 Kernel level asynchronous IO
 Supports thread, signal based or no-op
  callbacks
 Reduces syscall overheads in IO bound
  applications
How it works
   Control block
       Struct: fd, buffer, notification, offset, number of bytes
 aio_read( '/tmp/file' ) # signal notification
  with SIGIO
 Returns right away, faster than
  O_NONBLOCK
 Kernel signals with SIGIO on completion
       Handler notification contains pointer to the the original
        control block
Why it matters
   Parallel execution of aio_read && aio_write
       lio_listio( LIO_WRITE, list_of_cbs, 90, &list_sig )
 A single user to kernel space switch
 90 operations, a single signal notification
 Experimental rb_aio extension
 AIO.write( { :filename => 'buffer' } )
Project Darkstar
http://www.projectdarkstar.com
Gaming @ a Rails conf ?
 Rails Rack compatibility
 Middleware + ESI
 SOA architecture with thin processes +
  layers
 Russian doll pattern
Architecture Overview
   Communications
       Pubsub && direct channels suported
   Execution Kernel
       Stateless execution of tasks
   Data storage
       Transactional storage of serialized objects
Task Execution
   Spawned and managed by a task manager
   Appears monothreaded, executes in parallel
   Immediate, delayed or periodic
   Parent <=> child relationships
   Guaranteed to execute in order
   Children inherits priority of parent
Task Lifetime
 Max execution time is 100ms - configurable
 Split long running tasks into multiple
  smaller tasks
Managed Objects && References
 Managed object == a persitable entity
 References
       Encapsulates all interactions with the data store
   Retrieval strategies
       Get with the intention of modifying state
       Get for read
       Object#mark_for_update to promote a read only
        instance
Listeners
   Application listener
       Initialize: setup any game play items when first booted
       Login callback: setup per player game state
   Client listener
       Defines methods to repond to client events eg. logout
Testing
Test strategies
 Define environments : test / production
 Ability to switch between an evented and
  batched programming model depending on
  the environment
 A desirable side effect of loose coupling
 Very well suited for integration testing
Block in testing mode
 Inject correlation middleware when in the
  test environment
 extend BlockInTest
 A single event may spawn *data
       @broker.collateral_report( 'ACCXXXX' )
       => [#<Report:0x202948>, #<Report:0x202234>]
   A single event may spawn many others
       @broker.collateral_report( 'ACCXXXX' )
        => [:acknowledge_reports, :reports]
Event => expectation
 Mapping Event X to Reaction *Y : Event
  IDXXXXXXX => { IDXXXXXXX => [Y,Y,Y] }
 Mapping Event X to Data Elements *Z :
  Event IDXXXXXXX => { IDXXXXXXX =>
  [Z,Z,Z] }
 Backbone of integration tests
Existing specs ?
 github.com/tmm1/em-spec
 Bacon and Rspec backends
 A reactor / event loop for context
 How ?
       Context executes in a Fiber, each expectation yields
   Unobtrusive
       describe 'This is a context'
       Em.spec 'This is an evented context
Questions ?
Slides + Code
http://github.com/methodmissing/ra
          ilswaycon_events
Thanks! Fork away.
      Follow
 @methodmissing
    on Twitter

More Related Content

What's hot

Galera Cluster - Node Recovery - Webinar slides
Galera Cluster - Node Recovery - Webinar slidesGalera Cluster - Node Recovery - Webinar slides
Galera Cluster - Node Recovery - Webinar slidesSeveralnines
 
Drupal Con My Sql Ha 2008 08 29
Drupal Con My Sql Ha 2008 08 29Drupal Con My Sql Ha 2008 08 29
Drupal Con My Sql Ha 2008 08 29liufabin 66688
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Rittercatherinewall
 
Demystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash SafetyDemystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash SafetyJean-François Gagné
 
Flink Architecture
Flink Architecture Flink Architecture
Flink Architecture Prasad Wali
 
Galera Multi Master Synchronous My S Q L Replication Clusters
Galera  Multi Master  Synchronous  My S Q L  Replication  ClustersGalera  Multi Master  Synchronous  My S Q L  Replication  Clusters
Galera Multi Master Synchronous My S Q L Replication ClustersPerconaPerformance
 
FOSDEM 2012: MySQL synchronous replication in practice with Galera
FOSDEM 2012: MySQL synchronous replication in practice with GaleraFOSDEM 2012: MySQL synchronous replication in practice with Galera
FOSDEM 2012: MySQL synchronous replication in practice with GaleraFromDual GmbH
 
Cassandra Architecture
Cassandra ArchitectureCassandra Architecture
Cassandra ArchitecturePrasad Wali
 
The Full MySQL and MariaDB Parallel Replication Tutorial
The Full MySQL and MariaDB Parallel Replication TutorialThe Full MySQL and MariaDB Parallel Replication Tutorial
The Full MySQL and MariaDB Parallel Replication TutorialJean-François Gagné
 
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009Hiroshi Ono
 
The consequences of sync_binlog != 1
The consequences of sync_binlog != 1The consequences of sync_binlog != 1
The consequences of sync_binlog != 1Jean-François Gagné
 
Oracle Clusterware and Private Network Considerations - Practical Performance...
Oracle Clusterware and Private Network Considerations - Practical Performance...Oracle Clusterware and Private Network Considerations - Practical Performance...
Oracle Clusterware and Private Network Considerations - Practical Performance...Guenadi JILEVSKI
 

What's hot (20)

Galera Cluster - Node Recovery - Webinar slides
Galera Cluster - Node Recovery - Webinar slidesGalera Cluster - Node Recovery - Webinar slides
Galera Cluster - Node Recovery - Webinar slides
 
Automated master failover
Automated master failoverAutomated master failover
Automated master failover
 
Conflict Resolution In Kai
Conflict Resolution In KaiConflict Resolution In Kai
Conflict Resolution In Kai
 
Drupal Con My Sql Ha 2008 08 29
Drupal Con My Sql Ha 2008 08 29Drupal Con My Sql Ha 2008 08 29
Drupal Con My Sql Ha 2008 08 29
 
How to understand Galera Cluster - 2013
How to understand Galera Cluster - 2013How to understand Galera Cluster - 2013
How to understand Galera Cluster - 2013
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 
How can your applications benefit from Java 9?
How can your applications benefit from Java 9?How can your applications benefit from Java 9?
How can your applications benefit from Java 9?
 
Demystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash SafetyDemystifying MySQL Replication Crash Safety
Demystifying MySQL Replication Crash Safety
 
近未来的並列 LL
近未来的並列 LL近未来的並列 LL
近未来的並列 LL
 
Flink Architecture
Flink Architecture Flink Architecture
Flink Architecture
 
Galera Multi Master Synchronous My S Q L Replication Clusters
Galera  Multi Master  Synchronous  My S Q L  Replication  ClustersGalera  Multi Master  Synchronous  My S Q L  Replication  Clusters
Galera Multi Master Synchronous My S Q L Replication Clusters
 
FOSDEM 2012: MySQL synchronous replication in practice with Galera
FOSDEM 2012: MySQL synchronous replication in practice with GaleraFOSDEM 2012: MySQL synchronous replication in practice with Galera
FOSDEM 2012: MySQL synchronous replication in practice with Galera
 
Cassandra Architecture
Cassandra ArchitectureCassandra Architecture
Cassandra Architecture
 
The Full MySQL and MariaDB Parallel Replication Tutorial
The Full MySQL and MariaDB Parallel Replication TutorialThe Full MySQL and MariaDB Parallel Replication Tutorial
The Full MySQL and MariaDB Parallel Replication Tutorial
 
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
Solving_the_C20K_problem_PHP_Performance_and_Scalability-phpquebec_2009
 
The consequences of sync_binlog != 1
The consequences of sync_binlog != 1The consequences of sync_binlog != 1
The consequences of sync_binlog != 1
 
Oracle Clusterware and Private Network Considerations - Practical Performance...
Oracle Clusterware and Private Network Considerations - Practical Performance...Oracle Clusterware and Private Network Considerations - Practical Performance...
Oracle Clusterware and Private Network Considerations - Practical Performance...
 
Introduction to Docker
Introduction to DockerIntroduction to Docker
Introduction to Docker
 
Galera Cluster 3.0 Features
Galera Cluster 3.0 FeaturesGalera Cluster 3.0 Features
Galera Cluster 3.0 Features
 
Apache con 2011 gd
Apache con 2011 gdApache con 2011 gd
Apache con 2011 gd
 

Similar to Embracing Events

Perfomance tuning on Go 2.0
Perfomance tuning on Go 2.0Perfomance tuning on Go 2.0
Perfomance tuning on Go 2.0Yogi Kulkarni
 
Call me maybe: Jepsen and flaky networks
Call me maybe: Jepsen and flaky networksCall me maybe: Jepsen and flaky networks
Call me maybe: Jepsen and flaky networksShalin Shekhar Mangar
 
High available energy management system
High available energy management systemHigh available energy management system
High available energy management systemJo Ee Liew
 
Troubleshooting Common Network Related Issues with NetScaler
Troubleshooting Common Network Related Issues with NetScalerTroubleshooting Common Network Related Issues with NetScaler
Troubleshooting Common Network Related Issues with NetScalerDavid McGeough
 
The Foundations of Multi-DC Kafka (Jakub Korab, Solutions Architect, Confluen...
The Foundations of Multi-DC Kafka (Jakub Korab, Solutions Architect, Confluen...The Foundations of Multi-DC Kafka (Jakub Korab, Solutions Architect, Confluen...
The Foundations of Multi-DC Kafka (Jakub Korab, Solutions Architect, Confluen...confluent
 
Mininet: Moving Forward
Mininet: Moving ForwardMininet: Moving Forward
Mininet: Moving ForwardON.Lab
 
Van jaconson netchannels
Van jaconson netchannelsVan jaconson netchannels
Van jaconson netchannelsSusant Sahani
 
FPGA based 10G Performance Tester for HW OpenFlow Switch
FPGA based 10G Performance Tester for HW OpenFlow SwitchFPGA based 10G Performance Tester for HW OpenFlow Switch
FPGA based 10G Performance Tester for HW OpenFlow SwitchYutaka Yasuda
 
Ccnp3 lab 3_1_en (hacer)
Ccnp3 lab 3_1_en (hacer)Ccnp3 lab 3_1_en (hacer)
Ccnp3 lab 3_1_en (hacer)Omar Herrera
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
Looming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfLooming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfjexp
 
Logging Last Resource Optimization for Distributed Transactions in Oracle We...
Logging Last Resource Optimization for Distributed Transactions in  Oracle We...Logging Last Resource Optimization for Distributed Transactions in  Oracle We...
Logging Last Resource Optimization for Distributed Transactions in Oracle We...Gera Shegalov
 
Lec13 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- Multicore
Lec13 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- MulticoreLec13 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- Multicore
Lec13 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- MulticoreHsien-Hsin Sean Lee, Ph.D.
 
riyaj_advanced_rac_troubleshooting_rmoug_2010_ppt.pdf
riyaj_advanced_rac_troubleshooting_rmoug_2010_ppt.pdfriyaj_advanced_rac_troubleshooting_rmoug_2010_ppt.pdf
riyaj_advanced_rac_troubleshooting_rmoug_2010_ppt.pdfabdulhafeezkalsekar1
 
Top Mistakes When Writing Reactive Applications - Scala by the Bay 2016
Top Mistakes When Writing Reactive Applications - Scala by the Bay 2016Top Mistakes When Writing Reactive Applications - Scala by the Bay 2016
Top Mistakes When Writing Reactive Applications - Scala by the Bay 2016Petr Zapletal
 
Managing an Akka Cluster on Kubernetes
Managing an Akka Cluster on KubernetesManaging an Akka Cluster on Kubernetes
Managing an Akka Cluster on KubernetesMarkus Jura
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Ciklum Minsk
 

Similar to Embracing Events (20)

Perfomance tuning on Go 2.0
Perfomance tuning on Go 2.0Perfomance tuning on Go 2.0
Perfomance tuning on Go 2.0
 
Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!Fork/Join for Fun and Profit!
Fork/Join for Fun and Profit!
 
Call me maybe: Jepsen and flaky networks
Call me maybe: Jepsen and flaky networksCall me maybe: Jepsen and flaky networks
Call me maybe: Jepsen and flaky networks
 
High available energy management system
High available energy management systemHigh available energy management system
High available energy management system
 
Troubleshooting Common Network Related Issues with NetScaler
Troubleshooting Common Network Related Issues with NetScalerTroubleshooting Common Network Related Issues with NetScaler
Troubleshooting Common Network Related Issues with NetScaler
 
The Foundations of Multi-DC Kafka (Jakub Korab, Solutions Architect, Confluen...
The Foundations of Multi-DC Kafka (Jakub Korab, Solutions Architect, Confluen...The Foundations of Multi-DC Kafka (Jakub Korab, Solutions Architect, Confluen...
The Foundations of Multi-DC Kafka (Jakub Korab, Solutions Architect, Confluen...
 
Mininet: Moving Forward
Mininet: Moving ForwardMininet: Moving Forward
Mininet: Moving Forward
 
Van jaconson netchannels
Van jaconson netchannelsVan jaconson netchannels
Van jaconson netchannels
 
FPGA based 10G Performance Tester for HW OpenFlow Switch
FPGA based 10G Performance Tester for HW OpenFlow SwitchFPGA based 10G Performance Tester for HW OpenFlow Switch
FPGA based 10G Performance Tester for HW OpenFlow Switch
 
Ccnp3 lab 3_1_en (hacer)
Ccnp3 lab 3_1_en (hacer)Ccnp3 lab 3_1_en (hacer)
Ccnp3 lab 3_1_en (hacer)
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Looming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfLooming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdf
 
10 sdn-vir-6up
10 sdn-vir-6up10 sdn-vir-6up
10 sdn-vir-6up
 
Ccnp labs
Ccnp labsCcnp labs
Ccnp labs
 
Logging Last Resource Optimization for Distributed Transactions in Oracle We...
Logging Last Resource Optimization for Distributed Transactions in  Oracle We...Logging Last Resource Optimization for Distributed Transactions in  Oracle We...
Logging Last Resource Optimization for Distributed Transactions in Oracle We...
 
Lec13 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- Multicore
Lec13 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- MulticoreLec13 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- Multicore
Lec13 Computer Architecture by Hsien-Hsin Sean Lee Georgia Tech -- Multicore
 
riyaj_advanced_rac_troubleshooting_rmoug_2010_ppt.pdf
riyaj_advanced_rac_troubleshooting_rmoug_2010_ppt.pdfriyaj_advanced_rac_troubleshooting_rmoug_2010_ppt.pdf
riyaj_advanced_rac_troubleshooting_rmoug_2010_ppt.pdf
 
Top Mistakes When Writing Reactive Applications - Scala by the Bay 2016
Top Mistakes When Writing Reactive Applications - Scala by the Bay 2016Top Mistakes When Writing Reactive Applications - Scala by the Bay 2016
Top Mistakes When Writing Reactive Applications - Scala by the Bay 2016
 
Managing an Akka Cluster on Kubernetes
Managing an Akka Cluster on KubernetesManaging an Akka Cluster on Kubernetes
Managing an Akka Cluster on Kubernetes
 
Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"Николай Папирный Тема: "Java memory model для простых смертных"
Николай Папирный Тема: "Java memory model для простых смертных"
 

More from Lourens Naudé

ZeroMQ as scriptable sockets
ZeroMQ as scriptable socketsZeroMQ as scriptable sockets
ZeroMQ as scriptable socketsLourens Naudé
 
TX/RX 101: Transfer data efficiently
TX/RX 101: Transfer data efficientlyTX/RX 101: Transfer data efficiently
TX/RX 101: Transfer data efficientlyLourens Naudé
 
In the Loop - Lone Star Ruby Conference
In the Loop - Lone Star Ruby ConferenceIn the Loop - Lone Star Ruby Conference
In the Loop - Lone Star Ruby ConferenceLourens Naudé
 
EuRuKo 2011 - In the Loop
EuRuKo 2011 - In the LoopEuRuKo 2011 - In the Loop
EuRuKo 2011 - In the LoopLourens Naudé
 
Event Driven Architecture
Event Driven ArchitectureEvent Driven Architecture
Event Driven ArchitectureLourens Naudé
 
RailswayCon 2010 - Dynamic Language VMs
RailswayCon 2010 - Dynamic Language VMsRailswayCon 2010 - Dynamic Language VMs
RailswayCon 2010 - Dynamic Language VMsLourens Naudé
 
RailswayCon 2010 - Command Your Domain
RailswayCon 2010 - Command Your DomainRailswayCon 2010 - Command Your Domain
RailswayCon 2010 - Command Your DomainLourens Naudé
 
Railswaycon Inside Matz Ruby
Railswaycon Inside Matz RubyRailswaycon Inside Matz Ruby
Railswaycon Inside Matz RubyLourens Naudé
 

More from Lourens Naudé (9)

ZeroMQ as scriptable sockets
ZeroMQ as scriptable socketsZeroMQ as scriptable sockets
ZeroMQ as scriptable sockets
 
TX/RX 101: Transfer data efficiently
TX/RX 101: Transfer data efficientlyTX/RX 101: Transfer data efficiently
TX/RX 101: Transfer data efficiently
 
In the Loop - Lone Star Ruby Conference
In the Loop - Lone Star Ruby ConferenceIn the Loop - Lone Star Ruby Conference
In the Loop - Lone Star Ruby Conference
 
EuRuKo 2011 - In the Loop
EuRuKo 2011 - In the LoopEuRuKo 2011 - In the Loop
EuRuKo 2011 - In the Loop
 
Event Driven Architecture
Event Driven ArchitectureEvent Driven Architecture
Event Driven Architecture
 
RailswayCon 2010 - Dynamic Language VMs
RailswayCon 2010 - Dynamic Language VMsRailswayCon 2010 - Dynamic Language VMs
RailswayCon 2010 - Dynamic Language VMs
 
RailswayCon 2010 - Command Your Domain
RailswayCon 2010 - Command Your DomainRailswayCon 2010 - Command Your Domain
RailswayCon 2010 - Command Your Domain
 
Barcamp PT
Barcamp PTBarcamp PT
Barcamp PT
 
Railswaycon Inside Matz Ruby
Railswaycon Inside Matz RubyRailswaycon Inside Matz Ruby
Railswaycon Inside Matz Ruby
 

Recently uploaded

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Recently uploaded (20)

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

Embracing Events

  • 1. Lourens Naudé, Trade2Win Embracing Events Stop polling … react.
  • 2. Bio  http://github.com/methodmissing  Ruby contractor  General misfit for the current economy  Ruby, C#, Java, admin 500 nodes, CSS * deferred payment  Currently building out a consumer forex platform @ Trade2Win Slippage matter.  creator  scrooge, mysqlplus_adapter, mri_instrumentation  contributor  Rails, mysqlplus, query_memcached, thinking-sphinx, em-spec
  • 3.
  • 4. e-vent [i-vent] something that happens or is regarded as happening; an occurrence, esp. one of some importance.
  • 5. A change in state ...  MySQL server sends results down the wire  Connection file descriptor becomes readable  Process results  Render results  Ignorance is bliss  Never be flooded  Only handle events that matter
  • 6. Talk#to_a  Context switches  Scheduling  Programming models  Frameworks  Eventmachine  Neverblock  Operating System  Lessons from massively multiplayer online games  Testing  Q&A?
  • 8. Scenario we all can relate to ...  Quiet weekend day, erratic thoughts from the week before comes together  Sharing space with your better half ... who's being chatty  You're being interrupted at random  Let's assume an average quot;in the zonequot; startup threshold of 2 minutes per interruption  Deadlock's not an option ...
  • 9. Multithreading  Let the initial pattern of thought and the interruption be distinct Threads  The interruption's effective right away  The context switch is 'expensive' : coding VS whichever chore's been neglected  Preemptive scheduling == constant interruption
  • 10. Fiber / coroutine pool  Two distinct Fibered contexts  Able to defer the interruption  Cheap switching : being thick skinned buys time  You#resume the interruption if and when there's time to handle it
  • 11. Thread  Scheduling  Handled by the VM – timesliced @ 10ms by MRI  Executes as soon as CPU resources become available  Availability  MRI 18: Maps to a single native thread  MRI 19: 1 x native thread for each Ruby thread - GIL  JRuby: 1 x Java thread for each Ruby thread  Overheads  Large initial stack size  MRI uses a SIGVTALRM to signal a context switch
  • 12. Fiber  Scheduling  No concurrency – scheduled by application code  Never executes right away  Availability  MRI 18: Patch by Aman Gupta && Joe Damato  MRI 19: Core Fiber class  JRuby: Poor Man's Fibers  Overheads  Small initial stack size @ 4k  Context switches exclusively in user space – very fast
  • 13. Why Fibers matter  Computes a partial result - generator  Yields back to the caller  Saves execution state  Caller resumes  Data exchange  Accept arguments through Fiber#resume  Return values through Fiber.yield
  • 14. Threads as Coroutines  Through a voodo combination of  Thread priorities  Thread.pass  Thread.stop  Thread#run (yields CPU) or Thread#wakeup (no CPU)  Poor Man's Fibers piggy backs off a Queue  MRI 18 Fibers = Threads – preemptive scheduling, much like continuations, but with a smaller stack.  Performant, but not as lightweight as Fibers
  • 15. Cooperative scheduling  Request / response with evented DB access  HTTP request wrapped in a Fiber  => mysql->fd : SELECT * FROM users WHERE id = 1  Execution paused  <= mysql->fd : #<User id: 1 uname: methodmissing>  Execution resumed  => mysql->fd: SELECT * FROM wishlist WHERE user_id = 1  Execution paused  <= mysql->fd: #<Wishlist id: 20 user_id 1>
  • 16. Cooperative VS preemptive  Fibered dispatch, query = *, result = +, int = &  <GET /orders> * + *+*+*+*+*+*+  <POST /checkout> * + * + *+*+  <DELETE /sessions> *+  Threaded dispatch, interupted every 10ms  <GET /orders> * & + *+*+&*+*+*&+*+  <POST /checkout> * + * +& *+*&+  <DELETE /sessions> &*+
  • 17. Scheduling active time Thread 1 idle 10 ms quanta Thread 2 idle No scheduling time Fiber 1 active Run as long as you need Fiber 2 Cooperative VS Preemptive
  • 18. Event-driven Programming  Program flow determined by events  Characterized by an event handler, main loop or reactor  The reactor typically 'owns' the process  loop { button.on(:click).dispatch }  Binds event handlers to events  Deep nesting of callbacks and constructs eg. Twisted for Python
  • 19. Batch programming  wysiwig  Flow determined by the developer  Read → process → output
  • 20. Event-driven execution, synchronous API.
  • 21. Database ... class FiberedMysqlConnection def query( sql ) send_query sql Fiber.yield get_result end end EM.run{ conn.query( 'SELECT SLEEP 1' ) }
  • 22. … app server class UsersController < AC::Base def index @users = User.paginate( :page => 1 ) end end Thin::Server.start('0.0.0.0', 3000) do Fiber.new{ AC::Dispatcher.call( env ) } end
  • 24. Eventmachine  Implementation of the Reactor pattern  C++ with Ruby Bindings  JRuby compatible through jeventmachine  High performance event driven IO : epoll on Linux, kqueue on BSD and derivatives
  • 25. The Reactor  Maintains a global current loop time  Quantum is just under 100ms … adjustable  Verifies descriptors through a heartbeat  Runs timer events  New descriptors dropped onto a different queue  Modified descriptors processed outside loop  Stopped with special Loop Break Descriptor
  • 26. Bindings and Callbacks  A portable signature registry / list, implemented as UUID identifiers  Callback triggers :  timer fired  connection read  connection completed  connection accepted  connection unbound
  • 27. Eventable File Descriptors  Nonblocking  Notify of read and writability  Closed in 3 ways  hard  immediate ( when possible, next tick )  after writing ( protocol handlers, serve HTTP page, close connection
  • 28. Deferrables  A callback ... specifically a callback for :success or :failure  Immediately pushed to the background and scheduled for future execution  Deferrables should have an associated timeout
  • 29. Timers  Periodic or oneshot  Set a max timer count to avoid flooding the reactor  Can be cancelled
  • 30. Files  Very fast transfer of < 32k files with EM#send_file_data  File watch API  Notified when modified, deleted or moved  fastfilereader extension  Memory <=> disk transfer with mmap
  • 31. Processes  Supports deferrable child processes through pipes  EM#system  Process watch API  Notified when forked or exits
  • 32. Client / Server module Challenge def post_init send_data 'psw?' end def receive_data( data ) ( @data ||= '' ) << data end end EM.run{ EM.connect 'localhost', 80, Challenge }
  • 34. Why ?  Most web apps block on IO  Ruby processes has 'high' memory overheads  60MB RSS blocking 30ms on IO == $$$  Allocated in slabs – 80MB -> 120MB  Significantly reduces capacity for concurrent requests  eSpace stepped in
  • 35. How ?  Fibered connection pool – typically 8 to 12  Attaches to either EM or Rev as main loop  Patches for Evented Mongrel && Thin to wrap requests in Fibers  Fibered DB connections for postgres && mysql ( with mysqlplus )  Respects transactions - BEGIN ... COMMIT required to be on the same connection
  • 36. Fiber 1 (active ) Connection 1 (idle) Connection 2 (idle) Fiber 2 (inactive) Fiber 1 is executing
  • 37. Fiber 1 (inactive ) SELECT ... Connection 1 (busy) Connection 2 (idle) Fiber 2 (active) Fiber 1 issues a SQL query and passes control to Fiber 2
  • 38. Fiber 1 (inactive ) Connection 1 (busy) Connection 2 (busy) UPDATE … Fiber 2 (inactiv e) Fiber 2 issues a SQL query and both fibers are inactive
  • 39. Fiber 1 (active) Alfred, 28, … Connection 1 (idle) Tamer, 20, … . . Connection 2 (busy) Fiber 2 (inactiv e) Reactor notices first connection is finished so it resumes Fiber 1
  • 40. Fiber 1 (done) Connection 1 (idle) Connection 2 (idle) 3600 rows affected Fiber 2 (active) Fiber 1 is done and reactor notices second connection is finished so it resumes Fiber 2
  • 41. Patches to Ruby IO  Clever redirection to non-blocking methods  IO#read* => IO#read_nonblock  IO#write* => IO#write_nonblock  Catches IO errors  Errno::EWOULDBLOCK  Errno::EAGAIN  Errno::EINTR  Rescue attaches to the event loop  Requests notification of read / writability  Detach on success
  • 43. Signals  Software interrupts  Portable  Signal.list supported on all host systems  Unobtrusive  Caught Signal.trap( 'IO' ){ puts 'readable' }  Sent with Process.kill( 'IO', $ )  Can be scoped to a single process or a process group  Daemons: SIGHUP && SIGTERM
  • 44. Handling Signals  Ignore them – except KILL && STOP  Catch with trap('IO'){}  Let the default action apply  SIGVTALRM is reserved for threading  Signals the process every 10ms  Flags that it's time to schedule  Green threading maps to 1 OS thread, 1 per process, signals scoped per process
  • 45. Processes  Process groups  Leader ? Process#pid == process group identifier  Group persist when leader exists as long as there's some members
  • 46. Multi-process Quality of Service  Signals to enforce QOS  URG: Slow down  CONT: Resume normal operation  XCPU: Crawl  Monitoring agent sends URG during load spike  Sends CONT when load drops  XCPU during extremely high load, effectively pausing the worker(s)
  • 47. POSIX Realtime Extensions  Well supported, but implementations differ  Linux Kernel 2.6  FreeBSD / Darwin  Solaris  Kernel level asynchronous IO  Supports thread, signal based or no-op callbacks  Reduces syscall overheads in IO bound applications
  • 48. How it works  Control block  Struct: fd, buffer, notification, offset, number of bytes  aio_read( '/tmp/file' ) # signal notification with SIGIO  Returns right away, faster than O_NONBLOCK  Kernel signals with SIGIO on completion  Handler notification contains pointer to the the original control block
  • 49. Why it matters  Parallel execution of aio_read && aio_write  lio_listio( LIO_WRITE, list_of_cbs, 90, &list_sig )  A single user to kernel space switch  90 operations, a single signal notification  Experimental rb_aio extension  AIO.write( { :filename => 'buffer' } )
  • 51. Gaming @ a Rails conf ?  Rails Rack compatibility  Middleware + ESI  SOA architecture with thin processes + layers  Russian doll pattern
  • 52. Architecture Overview  Communications  Pubsub && direct channels suported  Execution Kernel  Stateless execution of tasks  Data storage  Transactional storage of serialized objects
  • 53. Task Execution  Spawned and managed by a task manager  Appears monothreaded, executes in parallel  Immediate, delayed or periodic  Parent <=> child relationships  Guaranteed to execute in order  Children inherits priority of parent
  • 54. Task Lifetime  Max execution time is 100ms - configurable  Split long running tasks into multiple smaller tasks
  • 55. Managed Objects && References  Managed object == a persitable entity  References  Encapsulates all interactions with the data store  Retrieval strategies  Get with the intention of modifying state  Get for read  Object#mark_for_update to promote a read only instance
  • 56. Listeners  Application listener  Initialize: setup any game play items when first booted  Login callback: setup per player game state  Client listener  Defines methods to repond to client events eg. logout
  • 58. Test strategies  Define environments : test / production  Ability to switch between an evented and batched programming model depending on the environment  A desirable side effect of loose coupling  Very well suited for integration testing
  • 59. Block in testing mode  Inject correlation middleware when in the test environment  extend BlockInTest  A single event may spawn *data  @broker.collateral_report( 'ACCXXXX' )  => [#<Report:0x202948>, #<Report:0x202234>]  A single event may spawn many others  @broker.collateral_report( 'ACCXXXX' ) => [:acknowledge_reports, :reports]
  • 60. Event => expectation  Mapping Event X to Reaction *Y : Event IDXXXXXXX => { IDXXXXXXX => [Y,Y,Y] }  Mapping Event X to Data Elements *Z : Event IDXXXXXXX => { IDXXXXXXX => [Z,Z,Z] }  Backbone of integration tests
  • 61. Existing specs ?  github.com/tmm1/em-spec  Bacon and Rspec backends  A reactor / event loop for context  How ?  Context executes in a Fiber, each expectation yields  Unobtrusive  describe 'This is a context'  Em.spec 'This is an evented context
  • 64. Thanks! Fork away. Follow @methodmissing on Twitter