Skip to content
Edit this page View source of this page

Broadcast across processes

This page shows how to install the SQL backend from mankai-sockets-sql, configure it, and size your database pool for it. With the memory backend, a broadcast reaches only connections in the same process. The SQL backend carries broadcasts between processes through a database table. Use it when more than one Puma worker or server must deliver the same message, when WebSocket connections run in a separate process, or when jobs broadcast from a worker.

For every option, see the mankai-sockets-sql reference.

Before you begin

Make sure that your app has the following:

  • mankai-sockets, with the provider registered. See Add your first WebSocket channel.
  • hanami-db with a configured database, for example through DATABASE_URL. hanami-db registers the db.gateway component that the backend uses by default.

Install the backend

To install the backend and its table, complete the following steps:

  1. Add both gems to your Gemfile, in the :default and :cli groups. The hanami command loads only the :cli group, so if the SQL gem isn't in it, the installer can't find the gem and doesn't write the migration:

    # Gemfile
    gem "mankai-sockets", group: [:default, :cli]
    gem "mankai-sockets-sql", group: [:default, :cli]
    
  2. Install the bundle:

    bundle install
    
  3. Generate the migration:

    bundle exec hanami sockets install --backend=sql
    

    The installer writes create_mankai_sockets_messages to config/db/migrate.

  4. Run the migration:

    bundle exec hanami db migrate
    

    The migration is idempotent: running it again doesn't change an existing table.

Configure the backend

In config/providers/sockets.rb, require the SQL gem and set config.backend. Leave the other settings in place: without allowed_origins, channels, and either an authenticator or allow_anonymous, the provider fails at boot.

The following provider uses the SQL backend everywhere except in tests:

# config/providers/sockets.rb
require "mankai/sockets"
require "mankai/sockets/sql"

Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
  configure do |config|
    config.backend =
      if Hanami.env?(:test)
        :memory
      else
        Mankai::Sockets::SQL.backend(gateway: "db.gateway")
      end
    config.authenticator = lambda do |request, _token_subject|
      user_id = request.session[:user_id]
      user_id && Mankai::Sockets::Identity.new(key: "user:#{user_id}", value: user_id)
    end
    config.allowed_origins = :same_origin
    config.channels = {"chat" => "channels.chat"}
  end
end

The test environment keeps the memory backend, so specs don't depend on the table or a polling thread.

To confirm that broadcasts cross processes, open a page that subscribes to a stream, and then broadcast to that stream from bundle exec hanami console. The page receives the message within the polling interval.

Tune polling and retention

Mankai::Sockets::SQL.backend accepts options for polling and retention. The following example polls less often and keeps messages for one hour:

config.backend = Mankai::Sockets::SQL.backend(
  gateway: "db.gateway",
  polling_interval: 0.25,
  retention: 3_600
)

The most common options are the following:

  • polling_interval: the time between polls, in seconds. The default is 0.1.
  • retention: how long to keep messages, in seconds. The default is 86_400, one day.
  • gateway: the database to use. To keep the table in a separate database, point it at a second gateway.

For every option and its default, see Options. An unknown or invalid option raises Mankai::Sockets::ConfigurationError at boot.

The backend deletes old messages on its own: every trim_every publishes, it deletes a batch of rows older than retention. To trim immediately, call trim on the backend:

Hanami.app["sockets.backend"].trim

Size the database pool

Each process that serves WebSocket connections starts one listener, a thread that polls the table for rows with higher IDs on the streams its connections watch. The listener starts when the process accepts its first WebSocket connection. A process that only publishes, such as a job worker, doesn't start one.

A process that serves WebSocket connections needs a database pool of at least executor_threads connections, plus one for the listener. With silence_polling, which is on by default, the listener polls through a second pool, which opens one more connection in that process.

When the provider starts, the backend logs a warning for each of the following problems:

  • The app's pool is smaller than executor_threads plus one. Raise max_connections on the database URL.
  • A MySQL or MariaDB connection stores times in whole seconds. Add fractional_seconds=true to the database URL.
  • A SQLite connection has no busy handler.

The backend never changes the app's connection settings. Each warning names the setting to change.

Know the delivery guarantees

The SQL backend delivers each message at most once and never replays stored rows:

  • When a listener starts, it begins at the table's highest ID.
  • When a browser subscribes to a stream that no connection in that process was watching, the listener skips that stream's older rows, even though the table keeps them for retention.
  • The backend doesn't retry failed deliveries.

Don't use the backend for durable event delivery. To observe broadcasts, subscribe to the mankai.sockets.broadcast event; see Monitor events.

What's next