RailsConf 2016
Action Cable for Not-Another-Chat-App-Please

Action Cable for Not-Another-Chat-App-Please

by Jesse Wolgamott

In the presentation 'Action Cable for Not-Another-Chat-App-Please,' Jesse Wolgamott discusses the capabilities and applications of Action Cable, a feature introduced in Rails 5 that enables real-time updates through WebSockets. The talk highlights the evolution from traditional methods of updating content on the web, such as meta-refreshing and polling, to more dynamic solutions like WebSockets, which allow for two-way communication between the server and clients. Wolgamott frames the discussion by outlining the building blocks of Action Cable, which consist of cables, channels, broadcasting, and subscriptions. Key points include:

  • History of Real-time Updates: The evolution from page refreshes to polling techniques, exemplified by applications like Gmail and Campfire, leading to the introduction of WebSockets.
  • Benefits of WebSockets: WebSockets allow near-instant communication and can significantly enhance user experience by enabling real-time collaboration and updates without page reloads.
  • Features of Action Cable: Wolgamott emphasizes that Action Cable is not a universal solution for all applications but serves to enhance Rails applications with real-time features effectively.
  • Real-world Use Cases: The presentation illustrates how Action Cable can benefit applications beyond chat features. Examples include collaborative tasks in applications like Trello and real-time notifications for asynchronous processes, such as the completion of server-side tasks.
  • Deployment Considerations: The speaker covers deployment strategies, emphasizing the importance of managing connections efficiently, particularly when scaling applications. Using Redis for message synchronization across multiple servers is recommended to prevent message loss.

Wolgamott concludes by encouraging developers to explore Action Cable through the available documentation and examples, acknowledging the contributors to this technology and showing enthusiasm for its potential. The talk ultimately underscores the exciting capabilities Action Cable brings to Rails developers aiming to create more interactive and real-time web applications.

00:00:09.620 Welcome to the 'What is New in Rails 5' track! I'm extremely proud to be part of it, and I'm excited for all the other talks today. I think this is a really cool release, so let's dive into Action Cable.
00:00:25.920 This was the first cable box I ever saw. Look, it's got a cable! I don’t know if any of you are old enough to have seen one of these, but it would sit and connect to your TV, and you’d have to navigate to find your channels. But that's not the cable we're talking about in this presentation.
00:00:39.780 For this presentation, I made several high-quality 8-bit art diagrams. You’re welcome in advance! Here, we see our intrepid user connecting to Rails through a cloud.
00:01:07.710 So how can Action Cable change this up? What we're going to discuss is the history of Action Cable and WebSockets. We will talk about what it is and what it's not. We'll cover building blocks, including what code is available for you to use, as well as some patterns. Additionally, we'll discuss deployment strategies to help you make use of this technology.
00:01:21.960 My name is Jesse Wolgamott, and you can find me on Twitter and GitHub as @jwoah. If you have questions or comments about this talk, I don’t think we'll have time for Q&A, but feel free to tweet at me, and I'll do my best to get you an answer.
00:01:55.200 I found that the best way to look forward at the changes that are going to take place is to look back and see where we stand in this march of time. So let’s start with our F5 refresh or Command-R, which is how we traditionally update a page.
00:02:11.430 In the past, checking your email was quite frustrating; you had to click refresh and then make sure your limited storage wasn’t being filled up by someone sending you a large JPEG. Today, kids with their gigs upon gigs of storage just don’t understand that struggle! If we want a page to update itself, we might have it auto-refresh using a meta tag, which would instruct the browser to refresh every few seconds. This was how sites like Drudge Report functioned for a long time, maintaining dynamic content while being paid by ad impressions.
00:02:57.090 By the time 2002-2003 came along, we all wanted something better, and so we got polling. Gmail adopted this approach, notifying you with messages like "You have two new messages" without actually updating the page. Campfire, a chat application, still makes use of polling to this day, effectively serving as a poster child for the technology, even as WebSockets evolved. Polling remains a great way to make your app dynamic if sub-second responses aren't required. Live updates in Basecamp rely on polling, which works for a wide array of websites.
00:04:09.930 Though there are applications that don’t need sub-second responses, keeping things dynamic through JavaScript makes a lot of sense in many scenarios. Enter WebSockets, which opened up new possibilities. I first saw WebSockets in action with a service called Pusher, which simplified the process tremendously. Their system allowed background image processing and then pushed updates to clients, making real-time communication easy.
00:05:22.600 The WebSocket standard, introduced in RFC 6455 in 2011, established the principle of two-way communication between clients and servers. Unlike traditional HTTP calls, which are stateless, WebSockets require the remote host to opt into the communication, meaning clients need to request a connection, and the server has to agree. Technologies like Socket.IO have simplified these processes in environments like Node.js.
00:06:14.590 Notably, Patrick McKenzie created a fascinating fake stock market game that utilized WebSockets to send trades in real-time, as opposed to repeatedly polling for updates. The advantage of WebSockets is clear: they allow for high-frequency trading by enabling almost instant notifications of new trades.
00:06:46.450 The challenge, however, is in managing connections. How can a server track numerous client connections without running into memory issues? While some languages like Elixir are well-equipped for scaling, Ruby has its challenges. If every connection consumes memory, the simple health of the system is at stake. This raises a critical question: how do we scale out, not just up, especially as we may need to manage thousands of connections? Spoiler alert: there's a solution.
00:07:57.760 Although the future of real-time applications may not be about defaulting to Action Cable for every feature, it certainly can add pizzazz and speed to the updates of certain applications, particularly where low latency is essential.
00:08:15.080 Now let’s take a closer look at what Action Cable is and what it is not. It's important to recognize its limitations as well as its benefits; this way, we can determine if it fits within our development toolkit.
00:09:00.040 To begin with, Action Cable is not a silver bullet; it won't automatically make everything great. It is primarily designed to function within the Rail ecosystem and although I can foresee a future where it is detached from that environment, we are not there yet.
00:09:38.930 It’s also important to note that Action Cable is not necessarily a significant leap forward for Rails in terms of JavaScript integration. There is JavaScript involved, but ultimately, it remains a feature akin to Jbuilder or Turbolinks, but it isn’t on the same level as the asset pipeline or Active Record.
00:10:02.830 It’s a solid feature that adds value to your application without needing to be more than that. Essentially, it allows for a nice enhancement to Rails applications, creating a ‘wow’ factor when updates occur in real-time. Picture having two windows open and seeing changes propagate across them—it’s undeniably cool.
00:10:23.769 Now, when we discuss chat applications, I want to clarify that this talk will not primarily focus on them. I initially dreaded the concept of this talk becoming just another presentation about user-to-user chat. While chat applications are an essential use case for WebSockets, they are not the full story. Many applications can gain more substantial benefits from utilizing Action Cable beyond just chat functions.
00:12:11.879 Take collaboration, for instance. Imagine a Trello-style application where multiple users can edit the same document or card, or perhaps update product prices in real-time. Action Cable can significantly enhance the user experience by delivering updates without requiring a page refresh.
00:13:06.859 Another good use case for Action Cable is handling asynchronous tasks. If a task, like generating a PDF from an invoice, is being executed server-side, you might create a channel that pushes notifications to the client when the task completes. This adds a fun and impactful way of indicating progress to users.
00:13:59.604 Now, let’s delve into the early days of Action Cable. The concept was announced in 2015 with a simple diagram but no code. Later that year, we got our first glimpse of the code itself during a beta release. It was still quite rough, lacking generators and a deployment story. A lot of people struggled with it, and while getting it to work was possible, the process was not user-friendly.
00:15:37.739 However, if you had tried Action Cable back then and weren't impressed, I'm happy to report that the experience has greatly improved. The core functionality remains, but the sugar coating makes it much easier to work with today. The current beta version, released in February 2016, maintained consistency across Rails versions and added features that made the framework much more approachable.
00:19:13.380 Let’s now discuss the building blocks of Action Cable. Action Cable is comprised of four key components: the cable, channels, broadcasting, and subscriptions. The cable serves as the actual connection between the client and server.
00:20:50.050 Channels are essentially rooms where you listen for events. On the Rails side, a channel possesses a stream name which could target all products or be scoped to a specific user. Broadcasting is the mechanism used to send information from the Rails server to the client through channels. On the client side, subscriptions facilitate listening and receiving data from the server.
00:22:37.710 Let’s dive deeper into each component. The cable is established using Action Cable's JavaScript library, creating a global app object. The actual connection can be configured to process WebSocket connections.
00:24:25.839 A channel on the Rails side functions like a controller, grouping related ideas. For instance, a products controller could correspond with a user’s inbox for updates. Each channel can inherit from an application connection and has the ability to define the current user object, which enhances its control over specific user connections.
00:26:14.520 We discuss how broadcasting works, using Action Cable to send messages to a JavaScript channel. You'll initiate broadcasts from parts of your Rails application, which can occur in controllers, Jobs, or even model callbacks.
00:27:49.270 The JavaScript subscription listens for any broadcasts on the designated channel, calling a specific function upon receipt of data. For example, a product update can be processed to refresh the displayed content automatically.
00:28:08.360 This allows for a seamless user experience where changes are instantly reflected without manual page reloading.
00:28:37.609 Let’s think about collaboration patterns. Imagine working in a browser with multiple tabs open. If one tab is updated—say, adding an item to a cart—you'd want all open tabs to reflect that change without needing to refresh.
00:29:53.170 Using Action Cable to broadcast changes ensures that all connected tabs are in sync. Broadcasting updates can maintain consistency across user sessions.
00:30:49.230 Asynchronous task management is another significant use case for Action Cable, especially when dealing with time-consuming processes that demand user updates.
00:31:07.610 Utilizing Action Cable allows you to provide notifications about the task’s status and completion, allowing users to receive real-time feedback on long-running processes.
00:32:02.540 Now let's talk about deployment. For basic use cases, Action Cable can be set up easily. You only need one server, and everything can operate effectively without requiring complex background job management. However, if you're working with multiple servers, you'll want to implement Redis to handle message synchronization across all instances.
00:32:59.160 Remember, without Redis, messages will be stored in-memory on individual servers, resulting in lost messages when connections switch.
00:35:09.360 When deploying applications using Action Cable, it is preferable to manage connections efficiently. Also be cautious about missed messages; consider using Action Jobs to schedule broadcasts efficiently. Always consider security by configuring request origins.
00:36:46.600 As we conclude, if you are curious to explore more on Action Cable, there are simplified examples available, plus the official documentation to guide you through implementation. I'd like to extend many thanks to DHH for the vision behind this technology, to the 42 plus contributors who have made it possible, and to The Iron Yard for sponsoring my seat at RailsConf.
00:38:09.940 If you're interested in learning to teach, make the world better, and improve diversity, feel free to reach out to me on Twitter. Thank you very much for your time!