New releases

Hotwire Club tooling is now open-source

Explore the agentic skills pack and the MCP server for building assistant workflows.

Stimulus - Auto-Sorting

Use a MutationObserver to sort websocket messages that arrived out of order.

View Solution on Patreon
Stimulus - Auto-Sorting

Premise

In this challenge, we are going to tackle a common but often overlooked scenario: Resolving the ordering of websocket messages that arrive jumbled up. Think of a chat application where several people are typing in their messages and the backing web server is using multiple processes (or even multiple servers) to process the form submissions. There’s no guarantee whatsoever that messages arrive in the correct order at each of the participants, yet it’s crucial to understanding the conversation. We are going to take a look at how to resolve that.

Challenge

First up, let’s assume that each message has a timestamp of when it arrived at the server and that this timestamp is correct (i.e., can be used to sort the messages). To simulate the out-of-order arrival I’ve set up a procedure that slices a random element out of the messages array and transports them as Turbo Stream broadcasts over the websocket:

These messages are appended to a <ul> on the index page, where a sort Stimulus controller is already connected:

https://stackblitz.com/edit/stimulus-auto-sort?file=index.html%3AL42

To visualize this a bit, I’ve used the simple but effictive auto-animate Javascript library.

Your task is to conceive a Stimulus controller that handles the ordering of the messages as they come in:

https://stackblitz.com/edit/stimulus-auto-sort?file=index.html%3AL42,app.js,controllers%2Fsort_controller.js

Here’s a peek at the end result:

Auto-Sorting of Incoming Chat Messages

Caveats

You will need a MutationObserver, but be mindful of infinite loops. Think carefully of when to start, stop, and restart observing.

Teaser

Can you think of other ways to insert messages at the correct spot right before they are appended to the DOM?

This is The Hotwire Club

46 hands-on challenges with detailed solutions, published biweekly since 2023. Subscribe to access all solutions and join the Discord community.

Subscribe on Patreon

More from

Turbo Frames - Chained Selects
24 March 2026

Build dependent dropdown menus that update dynamically using Turbo Frames and a small Stimulus controller.

Stimulus - Web Share API
25 November 2025

Use the native browser web sharing capabilities from Stimulus

Faceted Search with Stimulus and Turbo Frames
10 December 2024

Harness the power of Stimulus and Turbo Frames to drive a simple but powerful faceted search solution

Cookies
essential