Rails World 2026: A deep dive into Solid Cable (Nick Pezza) Video: https://www.youtube.com/watch?v=9WEABvHEKws Talk page: https://www.rubyevents.org/talks/a-deep-dive-into-solid-cable Unedited machine transcript, generated with Whisper. It contains recognition errors (names, technical terms). Check the video before quoting. ---- Hey there. I'm Nick Pezza. I wrote and maintained solid cable. And today, we're going to look at how it works and how it compares to the other Action Cable adapters in Rails. Prior to Rails 8, Action Cable relied on one of three adapters-- Redis, Postgres, and Async. They all solved the same basic problem. When your application broadcasts a message, is responsible for getting that message to the Rails processes they need to know about it. From there, those processes can send the message down to the connected browsers over their website connections. The important difference between these adapters is really about where those messages are able to travel. The async adapter is the simplest and has no dependencies, but it only works within a single Rails process, which works great in development, but production Rails apps usually run across multiple processes, often spread across multiple machines. Think of it like talking inside of a single room. room can hear you, but that message can't leave the room. Redis and Postgres solve this by giving your Rails process a shared place to communicate through. One Rails process publishes a message, Redis or Postgres distributes it, and every process that needs that message can receive it. But they come with their own trade-offs. If you choose Redis, deploying your Rails app now meant learning how to manage yet another data store alongside your primary database. If your app already used Postgres, the Postgres adapter mostly just worked. Straight-off is that its Pub/Sub mechanism limits payloads to roughly eight kilobytes. That's usually fine, but if you're using Turbo to broadcast larger chunks of HTML, you could run into that limit. And if your app uses SQLite or MySQL, signing up Postgres just for Action Cable didn't make much sense. So Redis tends to become the default choice. At work, we were using Redis for both Action Cable and caching. I unexpectedly found myself responsible for managing all of our infrastructure, so I started looking for ways to simplify things and make my life a lot easier. I moved our caching over to Solid Cache, which just left Action Cable as the last thing keeping Redis around. It was right around this time that I saw this issue that David had filed in Rails about extracting an Active Record-based adapter out of Campfire. So I figured I just had to wait for Campfire to land, drop the new adapter in, and finally remove Redis from our stack. But then a little while later, I saw this comment come through where Campfire ended up using Redis for Action Cable after all. So I figured how hard can it be to implement an adapter that only uses Active Record? Redis and Postgres both keep a persistent connection open to each Rails process. So when a new message arrives, they can send that to the connected Rails process immediately. To build an adapter on top of ActiveRecord that's database agnostic, we can't depend on Redis' Pub/Sub or Postgres' Listen/Notify mechanisms. So just like Solid Q, we can lean on a little bit of low tech. Polling. We can set up an infinite loop, ask the database if it has any new messages, and then sleep for a few milliseconds before checking again. Before looking at the code for the adapter, at the core of Solid Cable is our messages model, which has a channel and a payload along with an index on channel, since that's what we'll be querying by as it pulls for new messages. The adapter is really made up of two classes. One inherits from Action Cable's base adapter class, which sets up some shared state and defines the methods every adapter needs to implement. The other is the listener, which in Solid Cable's case handles polling. It inherits from Action Cable's subscriber map, and handles delivering broadcasts out to them. Our adapter class implements four main methods, broadcast, subscribe, unsubscribe, and listener. Let's start with broadcast. It just inserts a row into the messages table. Using insert lets us skip active record callbacks, validations, and the usual transaction wrapping, none of which we need here, so we can make the write as lightweight as possible. Next up is subscribe. It calls listener, and then calls add subscriber on listener with the channel in the subscriber. So let's look at what that listener is actually doing. The listener method is responsible for instantiating the second half of the adapter, the listener object. But the listener itself doesn't define the add subscriber method. That comes from its subscriber map superclass. Inside subscriber map, initialization sets up a hash that tracks subscribers by channel. When we add a subscriber, we append it to the list for that channel, and all that happens inside of a mutex to avoid those pesky race conditions. the add channel method, which is implemented by our listener class. Add channel just adds the channel name to a list of watch channels that we'll use to gather messages to be sent out during polling. This is where Redis would call its subscribe method, or Postgres would call its listen command inside of their adapters. Set subscribe. Let's look at unsubscribe. As you expect, unsubscribe does the inverse of subscribe. It calls the remove subscriber on the listener object, and just like add subscriber, that method actually lives on subscriber map. We removed the subscriber from the channels list, and if there are no subscribers left, we call removeChannel, which is eliminated by our listener class. It just removes the channel name from our list of watched channels. This is where Redis we call unsubscribe, and Postgres we call unlistened inside their adapters. And with that, we've covered the main methods the adapter class defines. Pretty simple stuff. Now let's go look at the listener's class initialization. At the end of initialization, the listener starts a new thread and calls listen inside it. Let's go look at what that listen method is actually doing. Listen starts a loop that keeps running until the listener gets shut down. On each pass through that loop, we query for any messages for the channel with an ID greater than the last one we've seen, and then broadcast each of those messages out to their subscribers. After we broadcast each message, we update last ID to that message's ID so the next poll knows where to continue from. And when the listener first starts up, initialize last ID to the most recent message already in the table so we don't replay old broadcasts. And finally, we sleep for a configured amount of time before starting the loop again. By default, it's 100 milliseconds. And that's it. In version one, the adapter and the listener together were only about 112 lines of code, plus the message model and a little configuration parsing. That's the version I ended up deploying at work, and it let me remove a register from our infrastructure without a hitch. And then a few months after the release of version one, to my surprise, I got this email from DHH about adding solid cable to Rails as the default adapter. But one of the blockers to doing so was adding auto-trimming. Once a message has been already broadcast, we don't need to keep it around forever. Auto-trimming periodically deletes older messages so the tables stay small and the polling queries stay fast. Now when we broadcast out a message, we check if the config is auto-trimming enabled, and if so, we run the trim job. Rather than trimming on a fixed schedule, solid cable ties cleanup to write activity. In adult settings, each write has a small chance of triggering a trim of up to the batch size of old messages. The probability is tuned so that over time, trimming has roughly twice the capacity of incoming writes. That gives the table consistent downward pressure as traffic increases, while the configurable retention period determines which messages are old enough to delete. The other change the folks at 37Signal suggested was adding a hashed version of the channel name to each message. We use SHA-256 to turn the name into a fixed-sized integer, store that alongside the payload, column. That gives us a much smaller index and cheaper lookups. So when the listener checks for new messages, it's queried by the channel hash rather than the channel name. One of the more notable bugs that was found after release was around how we determined which messages should be broadcast. Originally, Solid Cable tracked a single last ID for the whole listener. Problem is that if you subscribe to a new channel while the listener is already running, there may be older messages for that channel still sitting at the table that this new subscriber should never receive. So we started tracking a separate last scene ID for each subscribed channel. When a channel is added, we record the newest ID at that point, which gives that subscription its own starting line. Because the first channel last scene IDs can be added, updated, and removed from one thread while the listener is polling on another, we move that channel state into a concurrent map and use atomic updates to avoid races. We still keep the global last ID to efficiently scan forward through the table, and we eagerly initialize it now when the listener starts, between initialization and the first poll. Then before broadcasting a message, we also check the last scene ID for that specific channel. So the global ID keeps polling efficient and makes startup safe, while the per channel ID makes sure subscribers only receive messages that were broadcast after that channel was added. All right, let's look at some numbers and see how these adapters compare. All these benchmarks were run using solid cable version 4.0 and Rails main from a July 31st commit on a box with two CPUs and eight gigs of RAM. Redis, MySQL, and Postgres were all running on that same machine to avoid any network hops, and SolidCable was configured with a 100 millisecond polling interval, and I also disabled auto-trimming to isolate the adaptive performance. I used Grafana's K6 to generate the load and capture the metrics, and all of the benchmarking app and loading testing scripts are available in the bench directory of the SolidCable repo. So the first benchmark up is constant load. It keeps a fixed number of users active at all times. Each user connects, sends a ping, waits for the polling message, and repeats that 20 times. Once they finish, they disconnect, and a new user immediately takes their place. That cycle runs continuously for five minutes, so we're simulating a steady stream of users connecting, exchanging messages, and leaving. And these are the throughputs for each adapter at different user counts. We're measuring how many messages per second make the full trip through the system and back. At 250 users, all the adapters are pretty close to around 280 messages per second. But once we really start saturating the system, Redis and the native Postgres adapter Solid Cable and SQLite holds up pretty well, while Postgres and especially MySQL start to level off around the 500 user mark. The other thing we care about in this benchmark is latency. How long it takes a ping to go out and the corresponding pong to come back. As latency increases, clients spend more time waiting, which eventually limits how much throughput the adapter can sustain. Up through about 500 users, things are still pretty healthy. Around 750 in 1,000 users, though, latency starts climbing across the board. more aggressively under that load, especially on MySQL, while Redis and the native Postgres adapter hold their latency down for longer. Next benchmark up is Thundering Herd. It connects a fixed number of users simultaneously, and each user subscribes, sends one ping, validates the Pong, and then disconnects. It's testing how an adapter handles a sudden burst in connections, for example, after a deployment forces every client to reconnect at once. The main thing we're looking at is how quickly each adapter works through the resulting backlog, see in total completion time. At 250 users, the total completion times are all very close, right around two seconds. At 500 users, we start to see a little separation, but the adapter still clears the storm in roughly three seconds. By 1,000 users, though, the differences are a little more obvious. Redis finishes in 5.2 seconds, and the native Postgres adapter in about five. Solid cable on Postgres is still close at 5.7 seconds, while SQLite is even closer at 5.2, with MySQL bringing up the rear in around six. So even under a pretty aggressive reconnect storm, solid cable is still in the same general range as the push-based adapters. And last up is the lecture benchmark. It subscribes a number of users to the same channel, then publishes seven messages per second for five minutes. It's designed to show how efficiently a single broadcast can fan out to a large number of subscribers at the same time. These are the latency numbers. At 250 subscribers, Redis and the native Postgres adapter stay around 70 milliseconds on average, while solid cable is closer to 120. Since our polling interval is set to 100 milliseconds, that difference is mostly the cost of polling showing up. At 500 subscribers, everything is still holding together pretty well. Redis and the native Postgres adapter are around 90 millisecond average, and solid cable is around 145. At 750 subscribers, though, you start to see the system come under some real pressure. Redis and the native Postgres adapter are still under 200 millisecond P95, while solid cable climbs to the 400 to 500 range. I'll also note at 10 messages per second, instead of the seven we used at 750 subscribers, every adapter failed the benchmark. We'll come back to why that happened in a bit. So in aggregate, solid cables stayed pretty competitive at the lower end of the load test, even with a 100 millisecond polling interval. But as we pushed the system harder and added more users, its weaknesses started to show. And after staring at those higher end load numbers for a while and trying to find some positive way to put a spin on them, the immortal words of the great Dr. Ian Malcolm kept coming to minds. We can do better. So I instrumented a bunch of different parts of solid cable to see where the time was actually going. And pretty quickly, a few obvious hotspots showed up that we could speed up. First up was configuration handling. Every broadcast checks whether auto-trimming is enabled, and every pass through the polling loop checks the polling interval and whether polling logs should be silenced. Problem was that each of those checks went back through reading the cable config, reparsing YAML and all the values, and allocating objects over and over again. Not super great. amount of redundant work and GC pressure. So instead, we move all that parsing into a Memoized Configuration object. We read the cable config once, memorize all the values, and reuse that object everywhere. Next up was how we tracked watch channels. When channels added to our watch list, we stored the raw channel name as the key in our map. Then on every polling pass, we take all those channel names, hash them again, and use those hashes in the polling query. Now we hash the channel once when it's added and store that hash key in our channel map. Then when our listener polls, those hashes are ready to go straight into the query. No rehashing every channel and every pass through the loop. Next up is batching writes. Right now, every broadcast results in its own insert into the messages table. That's simple, but under heavy load, it means a lot of individual writes hitting the database. We're already batching reads by pulling for multiple messages at once, so we can apply the same idea on the write side. Collect broadcasts together and insert them in batches to reduce write pressure. The new broadcaster groups messages into batches based on either a maximum batch size or maximum delay, whichever happens first. When it starts up, it creates a queue for incoming broadcasts and spins up a dedicated thread to watch that queue. Each call to broadcast just wraps the channel in the payload in a small message object and pushes it onto that queue. The thread that watches the queue starts by waiting for the first message to show up in the queue. Pop blocks the thread here until one arrives so we're not spinning there while there's nothing to do. Once that first message comes in, we drain anything else that may already be waiting in the queue into our batch in case we've gotten behind. Then we keep collecting messages until either the batch reaches its target size or the delay expires, whichever happens first. And then we stop collecting and flush the batch. Instead of doing one insert per broadcast, we use insert all to write the entire batch in a single SQL statement. That cuts down on the number of writes in the database and reduces a lot of the overhead we were seeing under heavier load. Lastly, like I said, while running the lecture benchmark, at 750 subscribers in 10 messages per second instead of seven, Redis, Postgres, and Solid Cable all crapped out. Since all the adapters failed around the same load, that led me to believe this was an issue inside Action Cable. And sure enough, it was. When we call a stream from, Action Cable builds a handler for that stream. If you don't provide a custom callback, it uses the default handler whose job is basically just to take the broadcast and send it down the WebSocket. Before this change, even that simple default handler with a worker pool stream handler. So every incoming message took an extra trip through the connection worker thread pool before being sent to the client. That extra pool is useful for custom callbacks because they can run arbitrary application code and you don't want that work blocking the executor. But for the default handler, that extra hop just meant bouncing every message through another thread pool for no real benefit. After this change, we only use the worker pool when there's actually user supply callback. For the normal case, the default stream handler runs directly. from every broadcast this change will be included in the upcoming rails release so let's rerun the benchmarks and see where we landed after all these changes i've removed the postgres adapter from the upcoming charts to give us a little more room in the charts since its results were generally very close to redis i've also skipped the thundering herd benchmark here since it didn't really change after these updates mainly because it had so little sustained traffic for solid cable i configured the batch broadcaster with a batch size of four and a one millisecond delay The first benchmark up is constant load, and we get. These are throughput numbers. At 250 users, things are basically unchanged. The traffic just isn't high enough for these changes to make much difference. At 500 and 750 users, though, we start seeing the gains. Postgres and MySQL close a lot of the gap with SQLite, and all three move much closer to Redis. At 1,000 users, the improvement is much bigger. SQLite actually edges past Redis at 1,048 messages per second. Postgres jumps from 609 to 1,000, from 491 to 961. It's an even better story with latency. Before these changes, solid cables' latency started falling apart as we pushed into the higher user counts. Now the curve is dramatically flatter from 500 to 1,000 users. MySQL's P95 drops from 412 milliseconds to 174 at 500 users, and from 953 to 228 milliseconds at 750. Postgres shows the same pattern drop from 668 milliseconds to 231 at 750 users. users. At 1,000 users, SQLite drops from 390 millisecond average to 140. Postgres drops from 477 to 179. And MySQL goes from taking over a second to just 210 milliseconds. And the tail latency is the real winner here. SQLite now has a dramatically better P95 than Redis at 750 in 1,000 users, which results in more throughput. While Postgres and MySQL have gone from being way behind to basically matching Redis at 1,000 users. And finally, the lecture benchmark. Here we see solid improvements across the board as the subscriber count climbs. Latency stays much flatter than before instead of starting to run away at the higher end. And more importantly, all the adapters now make it through the 750 user 10 messages per second test, which failed before. That works out to roughly a 35% uplift in messages being handled. And these improvements mostly come from the stream handler changes inside Action Cable, so the benefit actually applies across adapters. Solid Cable gives us a handful of knobs and dials to tune how it behaves. So let's see what those actually do to performance. For the next few benchmarks, I'm going to stick with just the constant load test since it gives us the most balanced view of throughput and latency. Solid Cable's default polling interval is 100 milliseconds. So what happens if we drop that to 25? We'll be polling the database four times as often, but in exchange, we should be able to pick up new messages sooner. Let's see what that does to throughput and latency. And sure enough, it gives us a pretty big latency improvement through 500 users and even into 750. from roughly 160 millisecond p95 to around 90. And at 500 users, we're down around 100 or 115 milliseconds. Not quite down to Redis, but much closer. Once we start saturating the system at 750 to 1,000 users, those extra reads start to show diminishing returns for Postgres and MySQL. SQLite, on the other hand, keeps stretching its legs, pulling further ahead. Just to see how far we could push it, I also ran SQLite at a 10 millisecond polling interval with 250 users. millisecond average and 78 millisecond p95. Closer still, but Redis still keeps the lead. Throughput tells a similar story. Dropping the polling interval gives us a nice bump across most of the solid cable adapters. SQLite benefits the most, climbing to 1,071 messages per second at 1,000 users. Postgres and MySQL show modest gains through 750 users, with MySQL giving a little bit back at the very top end. So if your traffic is relatively low and delivery latency matters, may be worth lowering your polling interval. But as your system gets more saturated, pulling too aggressively can start to work against you, depending on the database you're using. There isn't one perfect value, so tune in for what your infrastructure can handle and what your latency requirements are. Now let's look at the cost of auto trimming. I'll be using a trim batch size of 100 messages and a retention period of 30 seconds. So for most of the five-minute benchmark, we'll be actively trimming old messages in the background. I'm also back to using the default 100 millisecond polling interval, in one variable at a time. At 250 and 500 users, auto-trimming is basically free. So I've dropped this from the chart and zoomed in at the higher end. Even here, the throughput impact is tiny. At 1,000 users, SQLite is essentially unchanged. Postgres drops from 1,000 to 956 messages per second in MySQL from 961 to 942. Latency takes a somewhat bigger hit on Postgres in MySQL, but overall, the cost of continuously cleaning up the table is pretty modest. So unless you're already operating right capacity auto trimming is probably a pretty reasonable trade-off which is why it's enabled by default set solid cable it offers a simpler infrastructure alternative while still delivering performance that can now stay surprisingly close to redis even under fairly heavy load and in some cases like sqlite exceeded the biggest trade-off shows up at the low end when the system isn't under much load redis and the native postgres adapter usually have a lower delivery latency because they can push messages immediately instead of waiting for the next poll SolidCable gives you room to tune the polling interval and close some of that gap. But for a lot of Rails apps, though, the database you already have is probably more than capable of handling ActionCable 2. All the improvements I've shown today are included in the 4.1 release of SolidCable, which is out now. I did bring one more gift, though. ActionCable currently doesn't guarantee message delivery order. Because messages are handed off to a thread pool, two broadcasts can be received in one order, but actually delivered in another, as threads get scheduled. Most of the time, that's not a big deal. If two notifications arrive slightly out of order, nobody notices. But for something like streaming and LLM response, order matters a lot. If chunks of the response are delivered out of sequence, the text can be assembled incorrectly. Here I have an example of that. I'm firing off a stream that just appends incrementing numbers as fast as possible, and they appear out of order. Absolute chaos. This is where Solid Cable has an advantage. Because every message is stored in the database, information right alongside it if we give each message a sequence within its channel then we have enough information to make sure that those messages are consumed in the same order that they were broadcast so i'm working on a new gem called chrono cable which is basically a collection of monkey patches for action cable and solid cable that allows a channel to keep its messages in order and can recover dropped messages this is very much a work in progress so lots may still change chrono cable adds a new channel model that stores the channel hash tracks the current sequence number for that channel and records whether messages on that channel should be delivered in order. You can opt a stream into order delivery with a new deliver and order option on stream from. When the stream is set up, Chrono Cable creates the corresponding channel record and marks it for order delivery. If you're using Turbo, you can pass deliver and order through the data attributes on Turbo stream from to opt that stream into order delivery. When we broadcast, Chrono Cable first checks whether that channel uses order delivery. If it does, we lock the channel record, and attach that channel-specific ID to the message before it gets queued for storage. ChronoCable also adds a new channel ID column on the messages table that stores this sequence ID. The downside of this is it cuts into some of the benefit we were getting from batching because ordered channels now need extra database work on every broadcast. Still experimenting with ways to reduce that cost, but for now, let's look at how the front end works. This is where a lot of the new work happens because the browser now has to keep a little bit of state ordered stream. The subscription starts like normal. The browser sends a subscribe message to the server with the channel it wants to listen to. When the subscription is confirmed, the server now sends back to us the current sequence ID for each stream in that subscription. That tells the browser the last message on chat was one, so the next message it should expect is two. When a message is broadcast, we now include the stream name along with that message's sequence ID. We check that the message ID is the next one we're expecting. is we consume the message and advance the expected ID to the next one in the sequence. But if a message arrives ahead of the one we're expecting, we don't consume it yet. And instead, we set it aside and ask the server for the stream's history, starting from the last message ID that we successfully consumed. While we're waiting for the missing message, another newer message might arrive. Since it is ahead as well, we set it aside with the others. When the history comes back, we consume the missing messages in order, three and then four, and then advance the expected as we go. Then we work through the messages we set aside. We already recovered message four from the history response, so we discard it. Message five is new, so we consume it and advance the expected ID again. With the waiting queue empty, we're caught back up, so we can go right back to listening for new messages like normal. If the website gets disconnected, say your internet drops, when the browser reconnects and resubscribes, the subscription confirmation will tell us that the stream is currently in message seven, still expecting message six. So now we know we've missed something while the connection was down. So we can ask the server for the stream history again, starting with the last message we saw. And we can use that to catch back up. We consume message six and then seven in order, advance what we're expecting next, and then go right back to normal streaming. And that's Chrono Cable. If you've got channels where message order really matters, give it a whirl and let me know. And that's it. Here are the repo links if you want to check it out and give any feedback or issues. And thanks. Thank you.