Robert Zhu - Realtime React Apps with GraphQL - React Conf 2017

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
good morning everyone how y'all doing all right my name is Robert I am a software engineer at the Facebook Boston office where I work on graph QL I am really excited to be here with you every a comp 2017 and today I'd like to talk about building real time react apps with graph QL subscriptions this talk has three parts the first we're going to talk about why we're interested in building real time apps and what we mean when we say real time apps the second part we'll talk about how we do it what are the state-of-the-art techniques where does graph skill subscriptions fit in in terms of the landscape of the solutions that we have available and to do that we'll also look at some examples and some demos and finally I'll end with where we are right now what the next steps are and how you can start using graphical subscriptions to power real time react apps today why are real time apps interesting they're certainly harder to build so what makes the trade-off worth it well I think it's because real time apps give us a sense of presence like we're part of something that happens we're seeing something nobody else has seen before and this gives us this feeling of connection to the the moment the event the world and other people it's like the difference between watching a sporting event live versus watching it pre-recorded three weeks later but just what do we mean when we say real time app well when I hear that word a couple examples come to mind probably the first one is various messaging apps when I have a conversation over one of these it usually happens in real time another example is rideshare apps using these apps we can see how far away the driver is we can see how long it's going to take to reach our destination and of course all varieties of cooperative and competitive multiplayer games but there are some less intuitive examples that we don't always think of when we hear that word these might include email Dropbox navigation and fitness apps in all these cases the app depends on remote data that is valuable immediately after it becomes available and we're no longer talking about the classic web app model where the client issues a request the server answers of the document and that's it in fact the communication pattern between the client and the server in these applications resembles a conversation a back-and-forth that lasts well after the initial request it's no surprise that react has played a large role in enabling us to build better and more real-time apps over the last few years react and the flux architecture have changed how we think about building apps in general not so long ago it was really difficult to build real-time apps in part because we were using imperative UI frameworks that made it really difficult to manage data but since react views our function of state the challenge of building a real-time app becomes focused on client-side state management and having a really good real time API there are mature client-side state management solutions such as relay and redux I'm going to focus on talking about the API there are two general categories of real-time API s push and pull and among push based real-time API s we can further subdivide them into live queries and subscriptions let's take a closer to look at all three imagine we're building an email app and on the client I'd like to display the number of unread email messages in my inbox and this limit this number changes over time like so the simplest way to do this is to pull and this is where the client asks the server how many unread emails do I have periodically like so let's make a few observations about this approach the first is that we don't capture every state transition notice the value jumping from 1 to 3 the second is that after the value is available on the server it might be a little bit of time before the client asks for that value again therefore resulting in latency and the third is that some polls do not actually yield any new or useful information now at this point you might be thinking polling doesn't count or polling sucks but I would encourage you to pause for a moment polling has the advantage of being simple stateless and intuitive and as a result it's very useful as a prototyping tool as a fallback solution when your fancy push space solution breaks and as a full-scale solution when data changes at a known frequency how can we improve polling let's take a look at that very first problem where we missed some of the state transitions naively I could just pull a lot faster but what I noticed now is I have even more waste all of the blue requests are not telling anything new about the state on the server but the red requests did yield new information and I want to keep those so how could I optimize this well if I had a stateful channel between the server and the client and I could detect when that data changes that I can build what we call a live query and it looks something like this conceptually it's just like the last slide except that we've gotten rid of all that waste now to build live queries we need reactive backends and that makes live queries challenging to integrate and scale let's consider what happens if we have a different requirement we want to display the number of unread messages only when we receive an important email now I'm sure if you're like me some emails you receive are more employment than others so if you receive a mix of important unimportant emails here's what the timeline might look like and if we only push data when we receive an important email this is we're describing a system that more closely resembles an event-based subscription let's make two observations about this approach first we're not detecting every state transition second when data is pushed from the server to the client we know exactly why it was pushed what caused this to happen now now that we've covered those approaches we find ourselves with two pushed based solutions who here loves api's with multiple inconsistent ways to do the same thing okay so we should ask our subscriptions and live queries actually the same thing can they be unified and to answer that question let's look at it from the clients perspective as a client using one of these api's do live queries and subscriptions have different contracts think about that for a moment for a live query I expect every state transition to be pushed once I execute a live query but for a subscription I only expect the state transitions associated with the event to be pushed and then when that data is pushed I know the reason why it was pushed because of these semantic differences I think live queries and subscriptions are two different tools in the real-time API toolbox now nothing we've discussed so far is new or controversial but we needed to establish some fundamentals and some terminology before dive deeper now let's go into event based subscriptions in more detail suppose we have a client that's subscribed subscribed to an event when the event triggers what do we tell the client well we have a few options we could tell it as little as possible perhaps just the ID of the thing that changed and in response the client might evict this entry in the client-side cache and to repopulate that entry it might have to issue a subsequent network request now this works but it rolls results in an extra network hop which results in latency but we commonly see this pattern being used by systems that heavily depend on a pubsub pattern another option is to send the exact same data to every subscriber per event and this works well when we have publicly available data and everybody should see the same data but one of the problems with this approach is that we might be sending extra information that the client doesn't need in this example if the biofield contains a lot of text and we simply don't display it on our mobile clients then we're wasting valuable network resources another dimension to consider is whether the payload that the data that you're sending is a subscriber varies between subscriber if we're trying to send a piece of information like unread email count in your inbox this number is unlikely to be the same between any two given clients as we consider these requirements we're starting to see a very familiar problem start to form how do we avoid sending the client too little or too much data what if we had a way to let clients specify exactly the data that they needed well we do it's called graph QL now can I get a show a hand how many in the room have heard of graph QL ok that's a lot of people for those of you who aren't familiar with graph QL don't worry it's an elegant idea for a more civilized age graphical is a declarative data query language that lets clients specify exactly the data that they need let's go over the basics my favorite way of introducing graph QL is through a technique I call wish driven design when I'm building the client I like to imagine the shape of the data that I wish I had now keep in mind I'm extremely lazy so the shape of this data ought to be in the exact shape that I can pass into my react component as props so if we were to build an email client and I want to display a list of emails I might wish I had a JSON object that looked like this now that I know the shape of this object I'm going to strip away the value portion of this object the value half the right side like so and if I clean up a double quotes and get rid of the commas this is what I'm left with now I'm just gonna do one small thing I'm going to add a route graph you all type to this and voila I have a graph GL query now the client sends this query to the server and in response the server returns a JSON object in the exact shape with the exact fields that the client asked for no more no less now that we've seen a graphical query let's take a quick look at what a subscription looks like pretty similar right we have a different route type subscription instead of query and we have a route field called important email which allows us to map to the event or set of events that will trigger this subscription what the subscription is saying is when certain events occur fetch the from subject and is read fields from the important email that just arrived when talking about graphs do all slides are okay but demos are much better or as Morpheus likes to say unfortunately nobody can be told what graph QL is you have to see it for yourself can everyone see the screen okay in the back yeah okay on the left here we have a really simple email client built with react and our newest version of relay and as you can see we've got two we've got several emails and for each email we display the from boots from the subject line and the body again on the right I have graphical graphical is the graphic UL IDE graphical allows us to explore a graph QL schema now graph GL schema is just a set of graphical types the set of fields they have and how they relate to one another let me show you I can use the graphical documentation Explorer now if I click in here to field two queries to inbox I can see that inbox is of type folder when I click through here I can see folder has a few fields ID name and unread count knowing that I can come in here and I can execute a query just like the ones that we saw in the previous slides so I could say something like inbox unread count me then I can edit I can execute it check out this field down here emails emails claims that it returns a collection of emails and then I click for the email it says it has fields ID arrived on from etc so if I wanted to grab all the data that I needed to populate this sample app sample email app on the Left I'm you just come in here and say emails from subject and now I have all the data that's displayed on the left we also saw a subscription let's see how that works so that's all I need to do in order to execute a subscription and if I actually run it unlike a query it's not going to come back with data immediately because remember the subscription runs in response to one the underlying event triggers so if I run it nothing is going to happen because this is not a real email server but I can start setting some demo emails and to do that let me show you the third route type in graph QL the mutation type I have a very simple mutation here called start demo it takes zero arguments and it'll start sending me sample emails now the mutation is typically how we do writes in graph QL so when I execute this you're going to see response come back as though it were a query cool now let's pray to the demo God's here we go yeah now we see some responses coming back so you can see that this this unread email count here okay now it might not be clear to you just from looking at graphical how you would integrate graphical subscriptions which you'll react at and to do that to show you how that looks like we're going to write some code together now before I dive into this code I want to mention that production react apps typically use graphics you all with some sort of client framework such as relay or Apollo an example we're going to look at we're going to focus on the underlying fundamentals rather than a specific framework can we see that okay oh okay so I skipped over slide there somewhere in your react app you probably have the opportunity to receive data from the API and to add it to your store and we're going to call this function modify flux store and since there are so many valid variations of how you organize your State we're just going to stub that out with a console log next I'm going to add a really simple function that just does two things first I'm going to new up assistance of a subscription second I'm going to subscribe to that subscription passing it to modify flux tour as the callback what this means is that whenever the subscription triggers the server pushes me new data I'm going to invoke the modified flux store and pass that data in now the subscription class we're looking at here is just an example it's a very thin wrapper around the WebSockets transport between the client in the server lastly of course I need to specify the actual subscription query that we're going to be looking at we saw that earlier from graphical so I'm going to stick that into the graph the subscription constructor let's run it the code on the left here should look very familiar there's just a couple of variations and I'll that'll walk through we have some imports we have this function here in knit subscriptions channel and as I said before we're using WebSockets in this demo so we have some setup that we need to do I've hidden that all behind this function notice that we're using a weight async hopefully you were here for Ben's talk yesterday and lastly I'm going to call start subscriptions at the very end I can start running this code like so and these emails are still coming in because the demo is still running the server is still pushing emails periodically so notice that on the Left I've selected from and subject from the important email and here I have from in subject from the important email coming back so hopefully that gives you an idea of what it might be like to integrate graphical subscriptions with your front-end cool where are we right now with graphical subscriptions at Facebook we've been operating graphical subscriptions at scale for over two years it powers familiar features such as live likes live comments and streaming reactions on live videos as a result we have a mature understanding of graphical subscriptions and we're confident that a concept is generally useful like react graphical embraces the philosophy of incremental improvement and to manage these incremental improvements we have something called the graph QL RFC process the RFC for graphical subscriptions the largest proposed change to graph scale since we first open sourced it in 2015 now the RFC itself has emerged and is currently undergoing review and discussion on our github repo once finalized the specification will enable the community to build an ecosystem of graphical subscriptions clients and servers across a variety of languages transports and backends suffice to say none of this would have been possible without the amazing support and contributions from the graph scale community if you're interested in following along or participating the evolution of graph QL I suggest to check out this RFC our partners at Apollo Graff cool and scaffold have implemented the graph QL subscription proposal in its current form and we just can't wait to use graphical subscriptions you should check them out I hope you're inspired to try building more real-time functionality react that I know hope this presentation has helped you understand the different techniques available to you thank you very much for your time and enjoy the rest of the conference [Applause]
Info
Channel: Facebook Developers
Views: 43,896
Rating: 4.8869448 out of 5
Keywords: react conf 2017, graphql, realtime, react, react native, api, json, rest, restful
Id: AYbVMNtO-ro
Channel Id: undefined
Length: 24min 0sec (1440 seconds)
Published: Thu Mar 16 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.