SlideShare una empresa de Scribd logo
1 de 51
Asynchronous
Architectures
  Mark Ethan Trostler
   mark@zzo.com
       @zzoass
Motivation

 Write programs that do one thing and do it well. Write
  programs to work together. Write programs to handle
  text streams, because that is a universal interface.

 Controlling complexity is the essence of computer
  programming

 The only way to write complex software that won't fall
  on its face is to hold its global complexity down — to
  build it out of simple parts connected by well-defined
  interfaces, so that most problems are local and you
  can have some hope of upgrading a part without
  breaking the whole.
The Goal
 Bite sized

 Text-based communication

 Independent

 KISS

 Naturally private methods

 Naturally loosely coupled

 Fail gracefully

 Maximize processor
Code Complexity

 #1 indicator of bugs: code size ( > 9300 chars)

 In the eye of the beholder: the Co-Worker Test

 Dependency count - coupling
Dependencies

 Required for object operation

 Lots of dependencies make code complex

 Long chains of dependencies make code
  complex

 More code loaded locally – more chance for
  something to go wrong

* Load JS, ‘require’

 Minimize Dependencies!
Coupling

 What do you do with a dependency??
   Instantiate it?
   Call methods?
   Access properties?
   Change shared global state?
   Alter all of them (prototype)?




 Keep Coupling Loose!
Application?
Applications are message passing systems with a bag of
objects in the middle with input and output at either
ends.




                 Object1

                            Object2

                 Object3
Current Application Paradigms

 Method based APIs
   Tight coupling adds complexity

 Remote interfaces
   Non-local – sync or async
   Local interface to remote object (Model)

 Object-based callbacks
   Eventing/Callbacks require dependent object to
    be local
Current: Method-based API
Current: Method-based API

 Maximizes coupling

 Easy to add dependencies

 Synchronous across objects (typically) – blocks
  caller

 Local

 Understood
Method / Event Hybrid

 Local reference to object

 Synchronous emitter

 Asynchronous listener

 Same process / memory space

 Same coupling

 Same dependencies
Pure Event API

 Local reference

 Same dependency / Same coupling

 Return values?

 Semantics?

 Not as understood

 Something still wrong…
A Different App Paradigm
Pure Event with Hub

 Asynchronous emitter

 Asynchronous listener

 NO local reference

 Shared nothing

 Loose coupling

 Function callbacks
Central Hub

 Independent modules cannot find each other

 All connect to central hub

 Hub unicast/broadcast events/responses

 Session handling

 Authorization services

 Event registration

 No local references

 Services run anywhere (no same-domain)
What Does It Look Like?

Listeners on event name, get an object and an
   optional callback

Emitters send event name, data object and an
  optional callback

Callback function expects (error, response) where
  error is either an object or string or null and
  response is an object (NodeJS standard)
Emitter
hub.fire('user:getProfile', function(err,
 userObject) {
      if (!err) {
        Y.one(‘#user’).set(‘innerHTML’,
      JSON.parse(userObject));
      } else {
          hub.fire(‘ui:error’, { msg: err} );
      }
});
Emitter / Listener
hub.on('user:getProfile', function(obj, callback) {

      hub.emit('session:get', { 'eventHub:session':
  obj['eventHub:session'] }, function(err, session) {

                if (err) {

                    callback(err);

                } else {

                    redis.hgetall('user:' + session.user, callback);

                }

          });

    });
Listener
var redis = require('redis').createClient();

hub.on('session:get', function(obj, callback) {

        var session = obj['eventHub:session'];

        if (session) {

            redis.hgetall('session:' + session, callback);

        } else {

            callback('No session');

        }

  });
Typical Web Server/App
Browser
                                            Controller /
                                              Router
                        Sink/Source ALL
                                                                   Session
                        communication




          Servlet container                                                    Models




                                   HTTP
          540+ apache
            modules
                                  Server                                      Authentication




                DB connectors                                          Authorization




                                 Static content        Threading
Webserver??

 HTTP server is just a module

 Serves only static content

 No entangled business logic

 No entangled routes

 Do not need to restart on changes to other
  modules
EventHub Architecture

               HTTP
              Server

     User
                        Session
    Module

              Event
               Hub
    Browser
                          DB
    Module

              Browser
               View
Unicast and Broadbast

 Both kinds!

 Event sent to one listener or many

 Still must register for the event for broadcast!

 Hub can return error if no one is listening
No Dropped Events
    UNICAST
    REGISTER


M                                          M N
o   EVENT FLOW                             o E
                     Event      UNICAST
d                    Hub
                                REGISTER   d W
u                                          u
l   DONE EVENT                   EVENT     l
                               FLOW
e                                          e

    FINAL FLOW /
    SHUTDOWN
Wither MVC?
Processes vs. Threads

  PROCESSES EASY      THREADS HARD

• IPC handled by    • Non-deterministic
  hub               • Synchronization
• Independent         issues
  modules           • Deadlock
• Deterministic     • Testing dicey
• Straightforward   • Syntactic cruft
  testing
• DB ACID
Performance



   Methods          Events

• FASTer        • SLOWer
• synchronous   • asynchronous
Scaling Web Apps

 Webservers behind VIPs / load balacners

 Load balancers affinity / sticky sessions

 Serialize session data
Scaling Event-based Apps

 Multiple hubs with replicated modules

 Clients specify hub – dynamic or static

 Broadcast events – bring up more modules
Complexity

    Method               Event

• Dependencies      • Self-contained
• Straightforward   • More moving
• Internal            pieces
  complexity        • External
• Bigger pieces       complexity
                    • Smaller pieces
Testability

   Methods             Events

• Coupled         • Isolatable
  dependencies    • Loosely
• Threads Non-      coupled
  deterministic   • Processes
                    deterministic
Deploy

  Method           Events

• Big Bang      • Only
• No              incremental
  incremental     changes
  changes       • Complex
• Simple
Third Party Options

   Method           Event Hub

•Import locally   •Import locally
•Hosted           •Hosted
 remotely          remotely
•Loaded           •Global
 locally           hosted
                   remotely
                  •Not Loaded!
FAILURE

 Monolithic systems fail completely

 Event-based systems fail
 incrementally
  Can route around failure
  Degrade gracefully
The Goal

 Bite sized

 Text-based communication

 Independent

 KISS

 Naturally private

 Naturally loosely coupled

 Fail gracefully
Solves World Hunger?
Theories

 Actor Model

 Hypervisors

 Microkernels

 Event hub analogy: Ethernet
   Hubs
   Switches
   Router
EventHub

 Built on socket.io

 Hub serves JS

 Server clients
   NodeJS

 Browser clients
   YUI
   jQuery
Practices

 EventHub https://github.com/zzo/EventHub

 Korus http://code.google.com/p/korus/

 Akka http://akka.io

 Netty http://www.jboss.org/netty/



 Minix 3.2 http://www.minix3.org/

 L4 http://www.l4hq.org/
Multi-Process JavaScript Architectures

Más contenido relacionado

La actualidad más candente

Windows communication foundation ii
Windows communication foundation iiWindows communication foundation ii
Windows communication foundation iiSwamy Gowtham
 
WCF (Windows Communication Foundation)
WCF (Windows Communication Foundation)WCF (Windows Communication Foundation)
WCF (Windows Communication Foundation)ipower softwares
 
Mule core concepts
Mule core conceptsMule core concepts
Mule core conceptsSindhu VL
 
Web Services - A brief overview
Web Services -  A brief overviewWeb Services -  A brief overview
Web Services - A brief overviewRaveendra Bhat
 
Developing and Hosting SOAP Based Services
Developing and Hosting SOAP Based ServicesDeveloping and Hosting SOAP Based Services
Developing and Hosting SOAP Based ServicesStephenKardian
 
Wcf architecture overview
Wcf architecture overviewWcf architecture overview
Wcf architecture overviewArbind Tiwari
 
REST, JSON and RSS with WCF 3.5
REST, JSON and RSS with WCF 3.5REST, JSON and RSS with WCF 3.5
REST, JSON and RSS with WCF 3.5Rob Windsor
 
WebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIWebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIRajkattamuri
 
Web services concepts, protocols and development
Web services concepts, protocols and developmentWeb services concepts, protocols and development
Web services concepts, protocols and developmentishmecse13
 
introduction to Windows Comunication Foundation
introduction to Windows Comunication Foundationintroduction to Windows Comunication Foundation
introduction to Windows Comunication Foundationredaxe12
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIKevin Hazzard
 

La actualidad más candente (20)

Windows communication foundation ii
Windows communication foundation iiWindows communication foundation ii
Windows communication foundation ii
 
Web services
Web servicesWeb services
Web services
 
WCF for begineers
WCF  for begineersWCF  for begineers
WCF for begineers
 
WCF (Windows Communication Foundation)
WCF (Windows Communication Foundation)WCF (Windows Communication Foundation)
WCF (Windows Communication Foundation)
 
zigbee
zigbeezigbee
zigbee
 
Mule core concepts
Mule core conceptsMule core concepts
Mule core concepts
 
Overview of java web services
Overview of java web servicesOverview of java web services
Overview of java web services
 
Web Services - A brief overview
Web Services -  A brief overviewWeb Services -  A brief overview
Web Services - A brief overview
 
WCF Introduction
WCF IntroductionWCF Introduction
WCF Introduction
 
Developing and Hosting SOAP Based Services
Developing and Hosting SOAP Based ServicesDeveloping and Hosting SOAP Based Services
Developing and Hosting SOAP Based Services
 
Wcf architecture overview
Wcf architecture overviewWcf architecture overview
Wcf architecture overview
 
REST, JSON and RSS with WCF 3.5
REST, JSON and RSS with WCF 3.5REST, JSON and RSS with WCF 3.5
REST, JSON and RSS with WCF 3.5
 
WebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIWebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDI
 
Web services concepts, protocols and development
Web services concepts, protocols and developmentWeb services concepts, protocols and development
Web services concepts, protocols and development
 
introduction to Windows Comunication Foundation
introduction to Windows Comunication Foundationintroduction to Windows Comunication Foundation
introduction to Windows Comunication Foundation
 
Web service
Web serviceWeb service
Web service
 
Web Services
Web ServicesWeb Services
Web Services
 
Web Service
Web ServiceWeb Service
Web Service
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
 
Web services SOAP
Web services SOAPWeb services SOAP
Web services SOAP
 

Destacado

Destacado (6)

Greenrevolution
GreenrevolutionGreenrevolution
Greenrevolution
 
Living fearlessly e book
Living fearlessly e bookLiving fearlessly e book
Living fearlessly e book
 
JUTE Workshop
JUTE WorkshopJUTE Workshop
JUTE Workshop
 
Gm’s position on the u
Gm’s position on the uGm’s position on the u
Gm’s position on the u
 
Nota ea ting 4
Nota ea ting 4Nota ea ting 4
Nota ea ting 4
 
Testable JavaScript: Application Architecture
Testable JavaScript:  Application ArchitectureTestable JavaScript:  Application Architecture
Testable JavaScript: Application Architecture
 

Similar a Multi-Process JavaScript Architectures

Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tourcacois
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionPrasoon Kumar
 
Decomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you painDecomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you painDennis Doomen
 
An Azure of Things, a developer’s perspective
An Azure of Things, a developer’s perspectiveAn Azure of Things, a developer’s perspective
An Azure of Things, a developer’s perspectiveBizTalk360
 
Microservices with .Net - NDC Sydney, 2016
Microservices with .Net - NDC Sydney, 2016Microservices with .Net - NDC Sydney, 2016
Microservices with .Net - NDC Sydney, 2016Richard Banks
 
Linking Services and Linked Data: Keynote for AIMSA 2012
Linking Services and Linked Data: Keynote for AIMSA 2012Linking Services and Linked Data: Keynote for AIMSA 2012
Linking Services and Linked Data: Keynote for AIMSA 2012John Domingue
 
A guide through the Azure Messaging services - Update Conference
A guide through the Azure Messaging services - Update ConferenceA guide through the Azure Messaging services - Update Conference
A guide through the Azure Messaging services - Update ConferenceEldert Grootenboer
 
Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...
Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...
Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...Dennis Doomen
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationStuart (Pid) Williams
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)Tech in Asia ID
 
Event Bus as Backbone for Decoupled Microservice Choreography - Lecture and W...
Event Bus as Backbone for Decoupled Microservice Choreography - Lecture and W...Event Bus as Backbone for Decoupled Microservice Choreography - Lecture and W...
Event Bus as Backbone for Decoupled Microservice Choreography - Lecture and W...Lucas Jellema
 
.NET microservices with Azure Service Fabric
.NET microservices with Azure Service Fabric.NET microservices with Azure Service Fabric
.NET microservices with Azure Service FabricDavide Benvegnù
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate
 
Node Session - 1
Node Session - 1Node Session - 1
Node Session - 1Bhavin Shah
 
Deconstructing Monoliths with Domain Driven Design
Deconstructing Monoliths with Domain Driven DesignDeconstructing Monoliths with Domain Driven Design
Deconstructing Monoliths with Domain Driven DesignVMware Tanzu
 
Dennis Doomen. Using OWIN, Webhooks, Event Sourcing and the Onion Architectur...
Dennis Doomen. Using OWIN, Webhooks, Event Sourcing and the Onion Architectur...Dennis Doomen. Using OWIN, Webhooks, Event Sourcing and the Onion Architectur...
Dennis Doomen. Using OWIN, Webhooks, Event Sourcing and the Onion Architectur...IT Arena
 

Similar a Multi-Process JavaScript Architectures (20)

Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Decomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you painDecomposing the Monolith using Microservices that don't give you pain
Decomposing the Monolith using Microservices that don't give you pain
 
An Azure of Things, a developer’s perspective
An Azure of Things, a developer’s perspectiveAn Azure of Things, a developer’s perspective
An Azure of Things, a developer’s perspective
 
Microservices with .Net - NDC Sydney, 2016
Microservices with .Net - NDC Sydney, 2016Microservices with .Net - NDC Sydney, 2016
Microservices with .Net - NDC Sydney, 2016
 
Linking Services and Linked Data: Keynote for AIMSA 2012
Linking Services and Linked Data: Keynote for AIMSA 2012Linking Services and Linked Data: Keynote for AIMSA 2012
Linking Services and Linked Data: Keynote for AIMSA 2012
 
A guide through the Azure Messaging services - Update Conference
A guide through the Azure Messaging services - Update ConferenceA guide through the Azure Messaging services - Update Conference
A guide through the Azure Messaging services - Update Conference
 
Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...
Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...
Decomposing the monolith into embeddable microservices using OWIN, WebHooks, ...
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
 
RavenDB overview
RavenDB overviewRavenDB overview
RavenDB overview
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to Node.JS
 
Event Bus as Backbone for Decoupled Microservice Choreography - Lecture and W...
Event Bus as Backbone for Decoupled Microservice Choreography - Lecture and W...Event Bus as Backbone for Decoupled Microservice Choreography - Lecture and W...
Event Bus as Backbone for Decoupled Microservice Choreography - Lecture and W...
 
.NET microservices with Azure Service Fabric
.NET microservices with Azure Service Fabric.NET microservices with Azure Service Fabric
.NET microservices with Azure Service Fabric
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
 
Node Session - 1
Node Session - 1Node Session - 1
Node Session - 1
 
Deconstructing Monoliths with Domain Driven Design
Deconstructing Monoliths with Domain Driven DesignDeconstructing Monoliths with Domain Driven Design
Deconstructing Monoliths with Domain Driven Design
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
Best node js course
Best node js courseBest node js course
Best node js course
 
Dennis Doomen. Using OWIN, Webhooks, Event Sourcing and the Onion Architectur...
Dennis Doomen. Using OWIN, Webhooks, Event Sourcing and the Onion Architectur...Dennis Doomen. Using OWIN, Webhooks, Event Sourcing and the Onion Architectur...
Dennis Doomen. Using OWIN, Webhooks, Event Sourcing and the Onion Architectur...
 

Último

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
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
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
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
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 

Último (20)

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
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
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
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
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 

Multi-Process JavaScript Architectures

  • 1. Asynchronous Architectures Mark Ethan Trostler mark@zzo.com @zzoass
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12. Motivation  Write programs that do one thing and do it well. Write programs to work together. Write programs to handle text streams, because that is a universal interface.  Controlling complexity is the essence of computer programming  The only way to write complex software that won't fall on its face is to hold its global complexity down — to build it out of simple parts connected by well-defined interfaces, so that most problems are local and you can have some hope of upgrading a part without breaking the whole.
  • 13. The Goal  Bite sized  Text-based communication  Independent  KISS  Naturally private methods  Naturally loosely coupled  Fail gracefully  Maximize processor
  • 14.
  • 15. Code Complexity  #1 indicator of bugs: code size ( > 9300 chars)  In the eye of the beholder: the Co-Worker Test  Dependency count - coupling
  • 16. Dependencies  Required for object operation  Lots of dependencies make code complex  Long chains of dependencies make code complex  More code loaded locally – more chance for something to go wrong * Load JS, ‘require’  Minimize Dependencies!
  • 17. Coupling  What do you do with a dependency??  Instantiate it?  Call methods?  Access properties?  Change shared global state?  Alter all of them (prototype)?  Keep Coupling Loose!
  • 18. Application? Applications are message passing systems with a bag of objects in the middle with input and output at either ends. Object1 Object2 Object3
  • 19. Current Application Paradigms  Method based APIs  Tight coupling adds complexity  Remote interfaces  Non-local – sync or async  Local interface to remote object (Model)  Object-based callbacks  Eventing/Callbacks require dependent object to be local
  • 21. Current: Method-based API  Maximizes coupling  Easy to add dependencies  Synchronous across objects (typically) – blocks caller  Local  Understood
  • 22. Method / Event Hybrid  Local reference to object  Synchronous emitter  Asynchronous listener  Same process / memory space  Same coupling  Same dependencies
  • 23. Pure Event API  Local reference  Same dependency / Same coupling  Return values?  Semantics?  Not as understood  Something still wrong…
  • 24. A Different App Paradigm
  • 25. Pure Event with Hub  Asynchronous emitter  Asynchronous listener  NO local reference  Shared nothing  Loose coupling  Function callbacks
  • 26. Central Hub  Independent modules cannot find each other  All connect to central hub  Hub unicast/broadcast events/responses  Session handling  Authorization services  Event registration  No local references  Services run anywhere (no same-domain)
  • 27. What Does It Look Like? Listeners on event name, get an object and an optional callback Emitters send event name, data object and an optional callback Callback function expects (error, response) where error is either an object or string or null and response is an object (NodeJS standard)
  • 28. Emitter hub.fire('user:getProfile', function(err, userObject) { if (!err) { Y.one(‘#user’).set(‘innerHTML’, JSON.parse(userObject)); } else { hub.fire(‘ui:error’, { msg: err} ); } });
  • 29. Emitter / Listener hub.on('user:getProfile', function(obj, callback) { hub.emit('session:get', { 'eventHub:session': obj['eventHub:session'] }, function(err, session) { if (err) { callback(err); } else { redis.hgetall('user:' + session.user, callback); } }); });
  • 30. Listener var redis = require('redis').createClient(); hub.on('session:get', function(obj, callback) { var session = obj['eventHub:session']; if (session) { redis.hgetall('session:' + session, callback); } else { callback('No session'); } });
  • 31. Typical Web Server/App Browser Controller / Router Sink/Source ALL Session communication Servlet container Models HTTP 540+ apache modules Server Authentication DB connectors Authorization Static content Threading
  • 32. Webserver??  HTTP server is just a module  Serves only static content  No entangled business logic  No entangled routes  Do not need to restart on changes to other modules
  • 33. EventHub Architecture HTTP Server User Session Module Event Hub Browser DB Module Browser View
  • 34. Unicast and Broadbast  Both kinds!  Event sent to one listener or many  Still must register for the event for broadcast!  Hub can return error if no one is listening
  • 35. No Dropped Events UNICAST REGISTER M M N o EVENT FLOW o E Event UNICAST d Hub REGISTER d W u u l DONE EVENT EVENT l FLOW e e FINAL FLOW / SHUTDOWN
  • 37. Processes vs. Threads PROCESSES EASY THREADS HARD • IPC handled by • Non-deterministic hub • Synchronization • Independent issues modules • Deadlock • Deterministic • Testing dicey • Straightforward • Syntactic cruft testing • DB ACID
  • 38. Performance Methods Events • FASTer • SLOWer • synchronous • asynchronous
  • 39. Scaling Web Apps  Webservers behind VIPs / load balacners  Load balancers affinity / sticky sessions  Serialize session data
  • 40. Scaling Event-based Apps  Multiple hubs with replicated modules  Clients specify hub – dynamic or static  Broadcast events – bring up more modules
  • 41. Complexity Method Event • Dependencies • Self-contained • Straightforward • More moving • Internal pieces complexity • External • Bigger pieces complexity • Smaller pieces
  • 42. Testability Methods Events • Coupled • Isolatable dependencies • Loosely • Threads Non- coupled deterministic • Processes deterministic
  • 43. Deploy Method Events • Big Bang • Only • No incremental incremental changes changes • Complex • Simple
  • 44. Third Party Options Method Event Hub •Import locally •Import locally •Hosted •Hosted remotely remotely •Loaded •Global locally hosted remotely •Not Loaded!
  • 45. FAILURE  Monolithic systems fail completely  Event-based systems fail incrementally  Can route around failure  Degrade gracefully
  • 46. The Goal  Bite sized  Text-based communication  Independent  KISS  Naturally private  Naturally loosely coupled  Fail gracefully
  • 48. Theories  Actor Model  Hypervisors  Microkernels  Event hub analogy: Ethernet  Hubs  Switches  Router
  • 49. EventHub  Built on socket.io  Hub serves JS  Server clients  NodeJS  Browser clients  YUI  jQuery
  • 50. Practices  EventHub https://github.com/zzo/EventHub  Korus http://code.google.com/p/korus/  Akka http://akka.io  Netty http://www.jboss.org/netty/  Minix 3.2 http://www.minix3.org/  L4 http://www.l4hq.org/

Notas del editor

  1. Introduce yourself!
  2. Batch programming – job schedulerCoding pad– (72 columns) – because card (intro by IBM 1928) had 80 columns –but machines could only read 72 columns – a key puncher made a card –each card was 1 line of code - on tray to remote job entry = card reader = set in queue in memory = output to printer – look @ core dump if failed – repunch changes ~1980s crt came out & interactiveLate 1970s timesharing – DEC (ethernet & networking) & IBM (PS/0) came interactivityWhere we came fromWrite program on coding pad – give to keypunchers – feed into computer - wait (up to 24 hours) – get printout – repeat = batch processing – only operators ran computers – everything else offlineLong waits between steps – once computer running it can’t do anything else until program quits or dies80 columns card A 4.7 GB DVD, with 80 characters per card, would require about 58 million cards, or a stack about 10 km high.
  3. OMG SLOW!!Pdp10Cpus still expensive so had to share them –bob’s big boy restaurant - time sharing you paid for what u used – did not have to own your own computer &/or can share it w/lots of people simultaneously (CLOUD!) – hooked up via terminal & modem – renting all of this stuff & tracking usage because a big business & security was now a concern – financial institutions didn’t want others to see their data (first sec. conf. 1971 because of it) until…CPUs became CHEAP! Cost of transistors plummeted. Don’t need timesharing anymore everyone has their own cpu (6502 $25!)But now had similar problem –instead of waiting for other people’s jobs to finish you were waiting for your own job to finish. bursty CPU activity followed by waiting for IO sitting at a terminal – waiting.Led to multiprogramming – running multiple processes at the same timeInitially coop mt = programs would voluntarily give up CPU – one bad program hung the system (pre Windows NT & 95 & Mac OS 9)Waiting for peripherals (tape) very slow so switched to another batch program – nothing was interactive so I didn’t matter how long each program tookBut people wanted to get on the computer! Time sharing – individuals ‘inefficient’ – groups not- time shared systems first polled & then interrupted for input when idleBursts of activity then idle = web apps! Single server can handle lots of simultaneous ‘users’Time sharing led to multiprogramming = cpus became cheap enough that time sharing wasn’t necessaryCooperative multitasking = tasks voluntarily giving up cpu – 1 program can hog cpu & bring server downPreemptive multitasking – cpus kicks u out – timeslice – OS can deal with external events like data coming inEvery process is IO bound or CPU bound – now with interrupts and preemptive MT processes no longer poll or busywait – when data is ready current process is context switched to the one that was waiting.IO bound process waits while CPU bound process executesAmiga first pMT then Windows NT and 95 & later macos 9.xBob bemerhttp://www.trailing-edge.com/~bobbemer/TIMESHAR.HTMU of Mich first timesharing machine – could not figure out how to bill time – so guy spent 10k hours on machine & built unix
  4. Process context switches more costlyCrazy fastcpus1971 intel 4004 2300 transistors – address 640 bytes of memoryKeep cpus busyPreemptive multitaskingHighest priorityTimesliceProcessesScheduled by kernelNo shared memoryThreadsScheduled in userland or kernelShared memoryAll softwareCooporative multitasking
  5. Cpu prices dropped – everyone can afford one1977 Apple II1977 TRS-801981 IBM PC1982 Commodore 641984 Apple MacEveryone has a cpu at home & at workSuddenly cpus have plenty of time lying aroundUntil mac there was nothing else to do – could not have multiple programms
  6. So inter-process scheduling on a uniprocessor is handled!Uniprocessor systems can now reliably multitask between processes efficientlyMULTITASKING1984 macBut now everyone has their own CPU – unwashed masses need something to look at! Amiga Workbench 1.0 - 1985 – first preemptive multitasking…1985 windows 1.0 cooperative mtMultitasking coop in Windows before XP and Mac OSX before XLinux always preempt.Windows NT/95 first supported threads 1993Linux Kernel 2.6 kernel threads 1993 JAVA 1995! Green threads on Sun - The next issue was a responsive UI – all apps now have GUIs.Don’t wanna block Uis while work happening – threads share memory & are cheap to create but have issues. Windows OS optimized for threads – linux for processes-------------------------------------------------------------------But my app now has a UI – I need to be responsiveBut starting a process is ‘slow’ and IPC is cumbersome. It’d be neat Was waiting for disk – now I’m waiting for UI and network.What else can I do while I’m/CPU is waiting? Creating a new process WAS heavyweight and communicating between processes via IPC was cumbersome. My program can still do work while waiting for IO – how about ‘light weight processes’: threads
  7. Computers had to WAIT – for user input – for disk drives & secondary storage & by the late 1980s/early 1990s networkInstead of people waiting – cpus were waiting
  8. Process context switches more costlyCrazy fastcpus1971 intel 4004 2300 transistors – address 640 bytes of memoryKeep cpus busyPreemptive multitaskingHighest priorityTimesliceProcessesScheduled by kernelNo shared memoryThreadsScheduled in userland or kernelShared memoryAll softwareCooporative multitasking
  9. 2001 OSX preemptive MT1995 preemptive2.6 2003 – fully preemptive kernel O(1) scheduler1994 linux 1.0 – preemptive scheduler
  10. Java 1996 (linux green threads) java 1.3 (2000) kernel threads (using clone) (windows threads in process itself)Pthreads 1995 – standardized api- Linux supportuserland threads – 2.6 kernel moved pthreads to kernel ghreadsUserland access to threading
  11. Hardware support via hyper-threading came to Xenon 2002 and Pentium 4 2002 – needed OS SMP & HT support (Windows XP & Linux < 2.4)First dual core intel 2005 Pentium D desktopsAMD first dual core 2005 Athlon 64 X2Since 2005 we’ve been able to take full advantage of multicore/HT cpus with preemtivpemt + kernel threadsLinux kernel fully preemptible 2.6
  12. unix philosophy:Doug McIlroy, the inventor of Unix pipesBrian Kernighan 1976Unix philosophy faqLoosely coupled set of independent modules working together w/o knowledge of the other focused on ONLY 1 thing
  13. SmallJSON-izedUpgraded / restarted w/o effecting systemIPC vs. threadingPrivate methods hard to test – don’t use / need so many of them
  14. Charles Perrow's "Catastrophic Potential" model: Normal Accidents: Living with High-Risk Technologies: systems-behavior expert Apps fails because systems complexity makes failures inevitable(At Chernobyl, tests of a new safety system helped produce the meltdown and subsequent fire.)Tightly coupled code = ‘bad’Loosely coupled code = ‘good’Complex = ‘bad’Simple = ‘good’What does that look like?
  15. http://www.enerjy.com/papers.html - open source java projectsStatic code analysisComplexity measuresMoredeps = more tests
  16. Required by your object to workExternal to objectPulled in by object: DI, or instantiation or passed in or globalTesting more difficult – mock/stub them all outSystem more brittle – complex & lots to maintainBesides the number of dependencies & length of dep chain: deps are described how they relate to your objectThe way dependencies are handled is described by….How are deps expressed??
  17. Tight coupling – cannot be pulled apartLoose coupling – barely togetherCoupling describes dependeniesWhen testing need to deal with coupled deps
  18. Tight coupling – cannot be pulled apartLoose coupling – barely togetherCoupling describes dependeniesWhen testing need to deal with coupled deps
  19. You gotta have a referenceInstantiate or inject or globalYour object waits for your responseUNDERSTOOD so there’s that
  20. With some eventsPromotes couplingFor JS:Load the fileInstantiate maybeUse
  21. You gotta have a referenceInstantiate or inject or globalYour object waits for your response
  22. e.g. ButtonConstructorClick eventStill need the object locally
  23. Still same as method-based apisGet some asynchronicityBut basically very similar to method-basedProblems with using all events all the time – what about return values? Will each object have a mish-mash of interfaces? Still needs the object locally to fire/listen to its events.
  24. This is a star architecture – with many emitters & listeners – anyone can be anythingAnalogous to a network switch- switch learns the topology – & unicast directly to listener if unicast event otherwise broadcastFrom network world.Given that apps pass messages from end to end – so do networks. There are control messages between nodes to help route messages.
  25. http webserver brokers ALL communication for your webapp!http webserver brokers ALL LOGIC of you webappRestart whole thing for changesOh ya browser over there in the corner – a special case
  26. Module can be in-browser or in-serverLocal or remote – anywhere on webBuild on IPC NOT threading
  27. Views instantiate Models to use them1973 first proposed for smalltalk (inspiration for JS)Decouple model from viewsAsync-arch = split model – data independent of methodsTheory remains – communication changes – no more views instantiating models or controllers instantiating views
  28. You don’t have to use threads anymore!The biggest gain of event-based arch – no more threads!
  29. Don’t need to load scripts / libraries locally!
  30. If it can happen it will happenApps failPieces dieBoxes crashShit happens
  31. SmallJSON-izedUpgraded / restarted w/o effecting systemIPC vs. threadingPrivate methods hard to test – don’t use / need so many of them
  32. JavaPerlJavascriptPythonRubyFlashErlang, Lua. GoWebSocktesHTTPIFRAMEJSONP PollingAJAX long pollingAJAX multipart streamingFlash
  33. Microkernelmach
  34. That’s all software! All threading was done by software – either in userland or in the kernel – CPUs are single threadedOnly supercomputers &/or specialized operating systems could handle multiple cpus UNICOS and IRIX – sys V variants – early 1990sNow they all run variants of linuxK computer in japan – 86000 ultrasparc64s – 10.51 petaflops – 864 racks