SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
Real-Time with




I’m going to talk about the most prominent aspect in our single page app.
@lautis
Wear funny hats and have a messy desk at Flowdock. Occasionally write code. Spend much
time in backend these days.
“There’s no time
                like real-time”


Real-time is necessary for a chat app. Interval polling wouldn’t work.
Big part of our app, no Backbone etc.
Demo
Stream changes
          from backend



                     And send messages

* stream and apply changes
* send some messages to server
=> To achieve this, some kind of transport channel between server and client is necessary.
Long-polling
       XHR-streaming
       HTMLFile
        Server-Sent Events
            WebSocket
       JSONP streaming
      XHR multipart
Each have their shortcomings, work on different browsers, and some work cross-domain,
others not.
3 implementations
            with 7 transports


We couldn’t really decide what to use. There isn’t really a one-size fits all option, but you
definitely could do with less.
Long-polling

            HTTP/1.1 200 OK
            Content-Type: application/json;


            [{'content': 'json'}]




The most obvious choice, works on every browser. Wait until you have something to tell to
client. Rinse, repeat.
XHR-streaming

               HTTP/1.1 200 OK


               {'content': 'json'}
               {'content': 'json'}
               {'content': 'json'}



Streaming: multiple chunks in one response. Widely used, not much advertised.
XHR-streaming works by parsing the response after each onReadyStateChange.
ResponseText will be huge if your HTTP request runs for long time, so periodic reconnection
is needed. Flowdock uses 60 seconds, requests have payload about user activity.
Server-Sent Events
                 HTTP/1.1 200 OK
                 Content-Type: text/event-stream


                 data: {'content': 'json'}


                 id: 2         Sent to server on reconnect
                 data: {'content': 'json'}


SSE aka ES is standardization of XHR streaming pattern. ID attribute allows seamless
reconnections from client point-of-view.
Hopefully will be in FD mobile soon.
In JavaScript
        var es = new EventSource('/events');
        es.onmessage = function (e) {
           console.log(JSON.parse(e.data));
        };




There’s actually something worth showing. Simple, bind message event listener.
Other events too
Built-in in modern
                browsers


Good news: Chrome, Safari 5, FF6, Opera 11
No IE



Even IE10 seems unlikely
No Android



Unlike iOS, Andriod doesn’t have ES. Even Android 4.0 is missing this. Maybe Chrome for
Android will fix this.
Use shim instead
              https://github.com/Yaffle/EventSource




Because SSE are “just” HTTP, you can implement it in JavaScript, today. And many have done
it. Use some available shim.
Streams are
                   unidirectional


XHR requests are needed to post data
Sockets are
                      bidirectional


Some kind of socket interface would be nice. Luckily for us, WebSockets are part of HTML5.
WebSockets
              var socket = new WebSocket('/socket');
              socket.onmessage = function (e) {
                 console.log(JSON.parse(e.data));
              };

              socket.onopen = function() {
                var m = {'content': 'json'};
                socket.send(JSON.stringify(m));
              }




I’m not going to exaplain the WebSocket protocol here, the standardized version is a bit more
complicated than what we saw previously. The JavaScript API is more interesting.
Receiving messages with websockets is pretty similar to EventSource. Sending messages is
trivial as long as you have received onopen.
Caveats

           • Limited browser support
           • Proxy problems
           • Safari crashes when used with Proxy
               Auto-Configuration




Safari has different protocol than others, IE 10 will be the first IE to support WS. NO SHIMS
WebSockets require full HTTP 1.1.
No way to detect if user has PAC. Rare.
Socket.IO
              “It's care-free realtime
                100% in JavaScript.”


Abstraction layer on top of different transports. NO SSE. Server-side and client-side.
We’ve been rolling Socket.IO out slowly for last month or so (bugs!).
Bugs

           • Reconnection race-conditions
           • Infinite loops with XHR-polling
           • DOM Exception 11


*Socket.IO didn’t know that there already was a reconnection attempt on going and
established multiple connections.
* XHR-polling transport client could get in state where it didn’t handshake properly but only
hammered the XHR-polling endpoint.
* INVALID_STATE_ERR, send data with unopened websocket. Yet another race-condition.
Socket.IO
“It's care-free realtime
  100% in JavaScript.”
Why bother?


If it’s so horrible, why even bother?
Science! It Works, Bitches.




Let’s look at the numbers.
Latency matters




We knew websockets would be fastest, but by how much?
Benchmark by sending a message and test how long it took to receive it
300


            225


            150


             75


              0
                         Ping           XHR-streaming         WebSocket




          Round-trip latency
Baseline: ping to our servers in Germany was 52ms
XHR: 240ms. TCP and especially SSL handshake is expensive. Streaming part doesn’t add
much penalty.
WebSockets came pretty close to ping, about 61ms. Node proxy in test setup + our backend
server added latency.
Real-world metrics
            from Flowdock


How many can use websockets? Clients as guinea pigs.
96% use
                      WebSockets
                            No Flash fallback




Over 80% have up-to-date Webkit based browsers.
3% have obsolete
                  browsers


IE users are minority.
1% have network
                   issues
                 (or have disabled WebSockets)




We don’t really know.
Network still sucks
Can’t just wait for reply even with websockets.
Network latencies vary, we have clients all around the world.
Render
                     optimistically


You have two basic choices, either use loading indicator or render users changes
optimistically. Needless to say, we try to be on the optimistic end of the road.
Basic operations in
               Flowdock
          1.Post new stuff
          2.Receive new stuff
          3.Modify existing stuff


Post new stuff: send messages
Receive: simple, just append to the stream. unless conflicts
Modify: mostly tag edits, but can also be message deletion. Highlights and unread handling
are tags.
Posting messages

           • Clients process messages as much
               as possible

           • Server adds unique ID and
               timestamp to data

           • Message echoed to client

Client processes messages. In our case, this basically means that tags are parsed and
message rendered to DOM. Later, if necessary, these changes can be reverted.
Server adds some information to messages, which is needed to add new tags. Client uses this
information to complete the message.
Last, message is echoed to all clients, including sender. This causes duplication, but data is
needed to “complete” outgoing messages.
Order sync
                                            SUP


                                            LOL


                       BAR                  FOO



                       FOO



"Undo" pending operations
Apply operation from network
Re-apply pending ops
A bit like git rebase, but cheat a little
Modifying stuff


• Add/remove tag to message
• Mark message as deleted
Idempotent
                          changes
           "Operation, which can be applied multiple
         times without changing the result beyond the
                      initial application."




Tags are good fit for this. You can add the same tag to a message multiple times. This is
used as our event-stream contains messages the client has sent.
Error handling is
                    tricky


Handling errors becomes quickly quite tricky. Good MVC would make it easier, but also it’s
not easy to know when some operation has failed because of poor network with WebSockets
and Socket.IO.
UX implications!
Protips

           • Socket.IO will bite you
           • SSE is safe choice for streaming
           • Design for broken internet


People put laptop to sleep, live with it. Important for single page apps. Avoid reloading.
Thanks!

Weitere ähnliche Inhalte

Was ist angesagt?

0-60 with Goliath: Building High Performance Ruby Web-Services
0-60 with Goliath: Building High Performance Ruby Web-Services0-60 with Goliath: Building High Performance Ruby Web-Services
0-60 with Goliath: Building High Performance Ruby Web-ServicesIlya Grigorik
 
Ruby Proxies for Scale, Performance, and Monitoring - GoGaRuCo - igvita.com
Ruby Proxies for Scale, Performance, and Monitoring - GoGaRuCo - igvita.comRuby Proxies for Scale, Performance, and Monitoring - GoGaRuCo - igvita.com
Ruby Proxies for Scale, Performance, and Monitoring - GoGaRuCo - igvita.comIlya Grigorik
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Masoud Kalali
 
Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011David Troy
 
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSocketsGunnar Hillert
 
Event Driven Architecture - MeshU - Ilya Grigorik
Event Driven Architecture - MeshU - Ilya GrigorikEvent Driven Architecture - MeshU - Ilya Grigorik
Event Driven Architecture - MeshU - Ilya GrigorikIlya Grigorik
 
Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Arun Gupta
 
Servlet 3.1 Async I/O
Servlet 3.1 Async I/OServlet 3.1 Async I/O
Servlet 3.1 Async I/OSimone Bordet
 
Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with javaJeongHun Byeon
 
Plone Deployment Secrets & Tricks
Plone Deployment Secrets & TricksPlone Deployment Secrets & Tricks
Plone Deployment Secrets & TricksSteve McMahon
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaJames Falkner
 
Plone Deployment (PloneConf Edition)
Plone Deployment (PloneConf Edition)Plone Deployment (PloneConf Edition)
Plone Deployment (PloneConf Edition)Steve McMahon
 
Ruby Proxies for Scale, Performance, and Monitoring
Ruby Proxies for Scale, Performance, and MonitoringRuby Proxies for Scale, Performance, and Monitoring
Ruby Proxies for Scale, Performance, and MonitoringIlya Grigorik
 

Was ist angesagt? (20)

0-60 with Goliath: Building High Performance Ruby Web-Services
0-60 with Goliath: Building High Performance Ruby Web-Services0-60 with Goliath: Building High Performance Ruby Web-Services
0-60 with Goliath: Building High Performance Ruby Web-Services
 
Ruby Proxies for Scale, Performance, and Monitoring - GoGaRuCo - igvita.com
Ruby Proxies for Scale, Performance, and Monitoring - GoGaRuCo - igvita.comRuby Proxies for Scale, Performance, and Monitoring - GoGaRuCo - igvita.com
Ruby Proxies for Scale, Performance, and Monitoring - GoGaRuCo - igvita.com
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
 
Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011Servers with Event Machine - David Troy - RailsConf 2011
Servers with Event Machine - David Troy - RailsConf 2011
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
WebSockets in JEE 7
WebSockets in JEE 7WebSockets in JEE 7
WebSockets in JEE 7
 
Introduction to WebSockets
Introduction to WebSocketsIntroduction to WebSockets
Introduction to WebSockets
 
Event Driven Architecture - MeshU - Ilya Grigorik
Event Driven Architecture - MeshU - Ilya GrigorikEvent Driven Architecture - MeshU - Ilya Grigorik
Event Driven Architecture - MeshU - Ilya Grigorik
 
Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014
 
Html5 security
Html5 securityHtml5 security
Html5 security
 
Servlet 3.1 Async I/O
Servlet 3.1 Async I/OServlet 3.1 Async I/O
Servlet 3.1 Async I/O
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
Realtime web application with java
Realtime web application with javaRealtime web application with java
Realtime web application with java
 
Plone Deployment Secrets & Tricks
Plone Deployment Secrets & TricksPlone Deployment Secrets & Tricks
Plone Deployment Secrets & Tricks
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
Plone Deployment (PloneConf Edition)
Plone Deployment (PloneConf Edition)Plone Deployment (PloneConf Edition)
Plone Deployment (PloneConf Edition)
 
SPDY - or maybe HTTP2.0
SPDY - or maybe HTTP2.0SPDY - or maybe HTTP2.0
SPDY - or maybe HTTP2.0
 
Cometdの紹介
Cometdの紹介Cometdの紹介
Cometdの紹介
 
Ruby Proxies for Scale, Performance, and Monitoring
Ruby Proxies for Scale, Performance, and MonitoringRuby Proxies for Scale, Performance, and Monitoring
Ruby Proxies for Scale, Performance, and Monitoring
 
WebSocket protocol
WebSocket protocolWebSocket protocol
WebSocket protocol
 

Andere mochten auch

Product / Market Fit – Our Travels Towards It
Product / Market Fit – Our Travels Towards ItProduct / Market Fit – Our Travels Towards It
Product / Market Fit – Our Travels Towards ItFlowdock
 
Flowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDBFlowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDBFlowdock
 
A Tale of a Server Architecture (Frozen Rails 2012)
A Tale of a Server Architecture (Frozen Rails 2012)A Tale of a Server Architecture (Frozen Rails 2012)
A Tale of a Server Architecture (Frozen Rails 2012)Flowdock
 
Beacons and their Impact on Search & SEO
Beacons and their Impact on Search & SEOBeacons and their Impact on Search & SEO
Beacons and their Impact on Search & SEOTom Anthony
 
SEO Split-Testing - Why and How
SEO Split-Testing - Why and HowSEO Split-Testing - Why and How
SEO Split-Testing - Why and HowTom Anthony
 

Andere mochten auch (6)

Product / Market Fit – Our Travels Towards It
Product / Market Fit – Our Travels Towards ItProduct / Market Fit – Our Travels Towards It
Product / Market Fit – Our Travels Towards It
 
API? WTF!
API? WTF!API? WTF!
API? WTF!
 
Flowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDBFlowdock's full-text search with MongoDB
Flowdock's full-text search with MongoDB
 
A Tale of a Server Architecture (Frozen Rails 2012)
A Tale of a Server Architecture (Frozen Rails 2012)A Tale of a Server Architecture (Frozen Rails 2012)
A Tale of a Server Architecture (Frozen Rails 2012)
 
Beacons and their Impact on Search & SEO
Beacons and their Impact on Search & SEOBeacons and their Impact on Search & SEO
Beacons and their Impact on Search & SEO
 
SEO Split-Testing - Why and How
SEO Split-Testing - Why and HowSEO Split-Testing - Why and How
SEO Split-Testing - Why and How
 

Ähnlich wie Real-Time with Flowdock

Server-Sent Events (real-time HTTP push for HTML5 browsers)
Server-Sent Events (real-time HTTP push for HTML5 browsers)Server-Sent Events (real-time HTTP push for HTML5 browsers)
Server-Sent Events (real-time HTTP push for HTML5 browsers)yay w00t
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersViktor Gamov
 
wa-cometjava-pdf
wa-cometjava-pdfwa-cometjava-pdf
wa-cometjava-pdfHiroshi Ono
 
D1-3-Signaling
D1-3-SignalingD1-3-Signaling
D1-3-SignalingOleg Levy
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web servicesNeil Ghosh
 
Web services Concepts
Web services ConceptsWeb services Concepts
Web services Conceptspasam suresh
 
Comet / WebSocket Web Applications
Comet / WebSocket Web ApplicationsComet / WebSocket Web Applications
Comet / WebSocket Web ApplicationsCodemotion
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsNaresh Chintalcheru
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketShahriar Hyder
 
How do I - Networking and Webservices - Transcript.pdf
How do I - Networking and Webservices - Transcript.pdfHow do I - Networking and Webservices - Transcript.pdf
How do I - Networking and Webservices - Transcript.pdfShaiAlmog1
 
Krug Fat Client
Krug Fat ClientKrug Fat Client
Krug Fat ClientPaul Klipp
 
Comet: Making The Web a 2-Way Medium
Comet: Making The Web a 2-Way MediumComet: Making The Web a 2-Way Medium
Comet: Making The Web a 2-Way MediumJoe Walker
 
Netty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/ConnectivityNetty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/ConnectivityC4Media
 

Ähnlich wie Real-Time with Flowdock (20)

Server-Sent Events (real-time HTTP push for HTML5 browsers)
Server-Sent Events (real-time HTTP push for HTML5 browsers)Server-Sent Events (real-time HTTP push for HTML5 browsers)
Server-Sent Events (real-time HTTP push for HTML5 browsers)
 
Web-Socket
Web-SocketWeb-Socket
Web-Socket
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
 
wa-cometjava-pdf
wa-cometjava-pdfwa-cometjava-pdf
wa-cometjava-pdf
 
D1-3-Signaling
D1-3-SignalingD1-3-Signaling
D1-3-Signaling
 
Nodejs + Rails
Nodejs + RailsNodejs + Rails
Nodejs + Rails
 
Intro to web services
Intro to web servicesIntro to web services
Intro to web services
 
Websocket
WebsocketWebsocket
Websocket
 
Web services Concepts
Web services ConceptsWeb services Concepts
Web services Concepts
 
ServerSentEvents.pdf
ServerSentEvents.pdfServerSentEvents.pdf
ServerSentEvents.pdf
 
netty_qcon_v4
netty_qcon_v4netty_qcon_v4
netty_qcon_v4
 
Comet / WebSocket Web Applications
Comet / WebSocket Web ApplicationsComet / WebSocket Web Applications
Comet / WebSocket Web Applications
 
ServerSentEventsV2.pdf
ServerSentEventsV2.pdfServerSentEventsV2.pdf
ServerSentEventsV2.pdf
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocket
 
How do I - Networking and Webservices - Transcript.pdf
How do I - Networking and Webservices - Transcript.pdfHow do I - Networking and Webservices - Transcript.pdf
How do I - Networking and Webservices - Transcript.pdf
 
Krug Fat Client
Krug Fat ClientKrug Fat Client
Krug Fat Client
 
Real time web apps
Real time web appsReal time web apps
Real time web apps
 
Comet: Making The Web a 2-Way Medium
Comet: Making The Web a 2-Way MediumComet: Making The Web a 2-Way Medium
Comet: Making The Web a 2-Way Medium
 
Netty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/ConnectivityNetty @Apple: Large Scale Deployment/Connectivity
Netty @Apple: Large Scale Deployment/Connectivity
 

Kürzlich hochgeladen

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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
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
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
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
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
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
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Kürzlich hochgeladen (20)

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.
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
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
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
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
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
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
 
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
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

Real-Time with Flowdock

  • 1. Real-Time with I’m going to talk about the most prominent aspect in our single page app.
  • 2. @lautis Wear funny hats and have a messy desk at Flowdock. Occasionally write code. Spend much time in backend these days.
  • 3. “There’s no time like real-time” Real-time is necessary for a chat app. Interval polling wouldn’t work. Big part of our app, no Backbone etc.
  • 5. Stream changes from backend And send messages * stream and apply changes * send some messages to server => To achieve this, some kind of transport channel between server and client is necessary.
  • 6. Long-polling XHR-streaming HTMLFile Server-Sent Events WebSocket JSONP streaming XHR multipart Each have their shortcomings, work on different browsers, and some work cross-domain, others not.
  • 7. 3 implementations with 7 transports We couldn’t really decide what to use. There isn’t really a one-size fits all option, but you definitely could do with less.
  • 8. Long-polling HTTP/1.1 200 OK Content-Type: application/json; [{'content': 'json'}] The most obvious choice, works on every browser. Wait until you have something to tell to client. Rinse, repeat.
  • 9. XHR-streaming HTTP/1.1 200 OK {'content': 'json'} {'content': 'json'} {'content': 'json'} Streaming: multiple chunks in one response. Widely used, not much advertised. XHR-streaming works by parsing the response after each onReadyStateChange. ResponseText will be huge if your HTTP request runs for long time, so periodic reconnection is needed. Flowdock uses 60 seconds, requests have payload about user activity.
  • 10. Server-Sent Events HTTP/1.1 200 OK Content-Type: text/event-stream data: {'content': 'json'} id: 2 Sent to server on reconnect data: {'content': 'json'} SSE aka ES is standardization of XHR streaming pattern. ID attribute allows seamless reconnections from client point-of-view. Hopefully will be in FD mobile soon.
  • 11. In JavaScript var es = new EventSource('/events'); es.onmessage = function (e) { console.log(JSON.parse(e.data)); }; There’s actually something worth showing. Simple, bind message event listener. Other events too
  • 12. Built-in in modern browsers Good news: Chrome, Safari 5, FF6, Opera 11
  • 13. No IE Even IE10 seems unlikely
  • 14. No Android Unlike iOS, Andriod doesn’t have ES. Even Android 4.0 is missing this. Maybe Chrome for Android will fix this.
  • 15. Use shim instead https://github.com/Yaffle/EventSource Because SSE are “just” HTTP, you can implement it in JavaScript, today. And many have done it. Use some available shim.
  • 16. Streams are unidirectional XHR requests are needed to post data
  • 17. Sockets are bidirectional Some kind of socket interface would be nice. Luckily for us, WebSockets are part of HTML5.
  • 18. WebSockets var socket = new WebSocket('/socket'); socket.onmessage = function (e) { console.log(JSON.parse(e.data)); }; socket.onopen = function() { var m = {'content': 'json'}; socket.send(JSON.stringify(m)); } I’m not going to exaplain the WebSocket protocol here, the standardized version is a bit more complicated than what we saw previously. The JavaScript API is more interesting. Receiving messages with websockets is pretty similar to EventSource. Sending messages is trivial as long as you have received onopen.
  • 19. Caveats • Limited browser support • Proxy problems • Safari crashes when used with Proxy Auto-Configuration Safari has different protocol than others, IE 10 will be the first IE to support WS. NO SHIMS WebSockets require full HTTP 1.1. No way to detect if user has PAC. Rare.
  • 20. Socket.IO “It's care-free realtime 100% in JavaScript.” Abstraction layer on top of different transports. NO SSE. Server-side and client-side. We’ve been rolling Socket.IO out slowly for last month or so (bugs!).
  • 21. Bugs • Reconnection race-conditions • Infinite loops with XHR-polling • DOM Exception 11 *Socket.IO didn’t know that there already was a reconnection attempt on going and established multiple connections. * XHR-polling transport client could get in state where it didn’t handshake properly but only hammered the XHR-polling endpoint. * INVALID_STATE_ERR, send data with unopened websocket. Yet another race-condition.
  • 22. Socket.IO “It's care-free realtime 100% in JavaScript.”
  • 23. Why bother? If it’s so horrible, why even bother?
  • 24. Science! It Works, Bitches. Let’s look at the numbers.
  • 25. Latency matters We knew websockets would be fastest, but by how much? Benchmark by sending a message and test how long it took to receive it
  • 26. 300 225 150 75 0 Ping XHR-streaming WebSocket Round-trip latency Baseline: ping to our servers in Germany was 52ms XHR: 240ms. TCP and especially SSL handshake is expensive. Streaming part doesn’t add much penalty. WebSockets came pretty close to ping, about 61ms. Node proxy in test setup + our backend server added latency.
  • 27. Real-world metrics from Flowdock How many can use websockets? Clients as guinea pigs.
  • 28. 96% use WebSockets No Flash fallback Over 80% have up-to-date Webkit based browsers.
  • 29. 3% have obsolete browsers IE users are minority.
  • 30. 1% have network issues (or have disabled WebSockets) We don’t really know.
  • 31. Network still sucks Can’t just wait for reply even with websockets. Network latencies vary, we have clients all around the world.
  • 32. Render optimistically You have two basic choices, either use loading indicator or render users changes optimistically. Needless to say, we try to be on the optimistic end of the road.
  • 33. Basic operations in Flowdock 1.Post new stuff 2.Receive new stuff 3.Modify existing stuff Post new stuff: send messages Receive: simple, just append to the stream. unless conflicts Modify: mostly tag edits, but can also be message deletion. Highlights and unread handling are tags.
  • 34. Posting messages • Clients process messages as much as possible • Server adds unique ID and timestamp to data • Message echoed to client Client processes messages. In our case, this basically means that tags are parsed and message rendered to DOM. Later, if necessary, these changes can be reverted. Server adds some information to messages, which is needed to add new tags. Client uses this information to complete the message. Last, message is echoed to all clients, including sender. This causes duplication, but data is needed to “complete” outgoing messages.
  • 35. Order sync SUP LOL BAR FOO FOO "Undo" pending operations Apply operation from network Re-apply pending ops A bit like git rebase, but cheat a little
  • 36. Modifying stuff • Add/remove tag to message • Mark message as deleted
  • 37. Idempotent changes "Operation, which can be applied multiple times without changing the result beyond the initial application." Tags are good fit for this. You can add the same tag to a message multiple times. This is used as our event-stream contains messages the client has sent.
  • 38. Error handling is tricky Handling errors becomes quickly quite tricky. Good MVC would make it easier, but also it’s not easy to know when some operation has failed because of poor network with WebSockets and Socket.IO. UX implications!
  • 39. Protips • Socket.IO will bite you • SSE is safe choice for streaming • Design for broken internet People put laptop to sleep, live with it. Important for single page apps. Avoid reloading.