Building Real-Time Features with Action Cable and Turbo Streams

1 min read
Building Real-Time Features with Action Cable and Turbo Streams

Real-Time Rails Applications

Modern web applications require real-time features to provide engaging user experiences. Rails offers two powerful tools for this: Action Cable and Turbo Streams.

Understanding WebSockets

WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time data transfer between client and server.

Setting Up Action Cable

# app/channels/messages_channel.rb
class MessagesChannel < ApplicationCable::Channel
  def subscribed
    stream_from "messages_#{params[:room_id]}"
  end

  def speak(data)
    Message.create!(
      content: data['message'],
      user: current_user,
      room_id: params[:room_id]
    )
  end
end

Turbo Streams Integration

Turbo Streams allows you to send HTML updates over WebSocket connections:

<%= turbo_stream_from "messages_#{@room.id}" %>

<div id="messages">
  <%= render @messages %>
</div>

Broadcasting Updates

# app/models/message.rb
class Message < ApplicationRecord
  after_create_commit :broadcast_message

  private

  def broadcast_message
    broadcast_prepend_to "messages_#{room_id}",
      target: "messages",
      partial: "messages/message",
      locals: { message: self }
  end
end

Performance Considerations

  • Use Redis for Action Cable in production
  • Implement connection throttling
  • Consider using Anycable for better performance
  • Monitor WebSocket connections

Best Practices

  1. Authentication: Always verify user permissions in channels
  2. Rate Limiting: Prevent spam and abuse
  3. Error Handling: Gracefully handle connection failures
  4. Testing: Use Action Cable test helpers