Using WebSockets in Dallinger Experiments

Dallinger provides some helpers to facilitate realtime communication between participants and the experiment using the WebSocket protocol.

The experiment server runs two WebSocket routes. The first, /chat, implements a Publish-Subscribe pattern. Connecting to that service with a channel argument in the url will subscribe a client to all messages sent to the named channel. If the named “channel” doesn’t already exist it will be created on the server. Both clients (participants) and the experiment instance can subscribe and create channels. The second, /experiment-socket, hands each incoming message to the experiment on the web process holding the connection instead of publishing it, and is described in its own section below.

Websocket messages are strings consisting of a channel name followed by a : and then a message payload. The message payload is usually a string representing a JSON object.

Chat

The channel backend publishes all incoming messages to a redis queue. It also looks for new messages on the queue and relays channel specific messages to all channel subscribers (generally either participants or the experiment itself).

When a client makes a WebSocket connection to the /chat?channel=<channel> route (see The Web API) it opens a persistent connection to the experiment over which it can send messages (to any channel except the reserved "dallinger_control", "dallinger_direct", "dallinger_realtime_session" and "dallinger_time" channels) and will receive all messages published to the channel named in the initial request.

Additionally, Experiment classes can provide a channel attribute which will automatically subscribe the experiment class to the named channel. Experiments that specify a channel will also be subscribed to a control channel named “dallinger_control” to which client connection, disconnection, subscribe, and unsubscribe messages are automatically sent. Such experiments should implement a custom receive_message() method to receive and process incoming WebSocket messages.

Experiments may also send messages to all channel subscribers using the publish_to_subscribers() method.

A connection’s subscribed message is sent as soon as it joins its channel, which may be before redis has confirmed the subscription on that web process. Its connected message waits, for up to two seconds, until redis has confirmed that subscription and, if the connection named a participant, the one which carries directed messages. An experiment which replies to a newly arrived participant, whether on their channel or with publish_to_participants(), should reply to connected rather than subscribed, as a reply to subscribed may be sent before the connection can receive it.

It’s possible for an experiment class to subscribe to messages on additional WebSocket channels. To avoid duplicate subscriptions it’s generally best to create such subscriptions in your Experiment class’s on_launch() method which is only run at experiment launch time, or using the experiment’s background_tasks(). For example:

def on_launch(self):
    from dallinger.experiment_server.sockets import chat_backend
    chat_backend.subscribe(self, 'my_secondary_channel')

An experiment can create and subscribe to channels after launch, but would need to be careful to ensure each channel is only ever subscribed once per experiment run. This is likely to be difficult because the experiment potentially has many instances running concurrently across multiple processes and servers.

Messages are handled asynchronously by the receive_message() method of the experiment class. Experiments which wish to override the default asynchronous handling of WebSocket messages (e.g. because they retain non-persisted state in the experiment instance that is needed to process the message) may override the send() method of the experiment class.

If your experiment implements synchronous handling of messages either using a custom send() or by sending the immediate flag in your message payload, it will need to ensure that it takes care to manage any database sessions. The dallinger.db.scoped_session_decorator can be used to wrap functions and the dallinger.db.sessions_scope contextmanager can provide more granular/repeated session management.

The Experiment Socket

Both of the paths described so far run the experiment’s code on the process that subscribed the experiment to the channel, which is the one that served /launch. Messages reach it through redis, and by default a worker handles them some time later.

A connection to the /experiment-socket route works differently. Each incoming message goes straight to the handle_websocket_message() method, on the web process that owns the socket, before the next message is read. Nothing is published to redis on the way. Use it when a participant’s action has to be acted on immediately, such as a move in a turn-based game. Games in which players act at the same time, or which run on a timer, are better written for the real-time engine, which Real-Time Games describes. The dallinger.openExperimentSocket function opens such a connection, and is described along with the rest of the client library in its own section below:

var socket = dallinger.openExperimentSocket({channel: 'game_7'});
// Passed to handle_websocket_message with a channel_name of 'moves'
socket.send('moves', {type: 'move', action: 'rock'});

An experiment socket subscribes to channel just as a /chat connection does, so broadcasts to that channel reach the browser the same way. Only the inbound direction differs.

A socket on either route that joins a real-time session sends the frames on its game type’s channel to that session alone. They never reach handle_websocket_message(), or any other subscriber, so a game’s hidden information stays hidden. Frames on its other channels are handled as they would be without a session.

channel is optional. A connection that leaves it out subscribes to nothing and receives nothing, which suits a game socket that only reports moves. It can still send, because each message carries its own channel prefix, which is passed to the method as channel_name.

scope is optional, and Dallinger does not interpret it. Whatever the browser sends is stored on the connection and reported back unchanged, both to the method and in the client payload of every control channel event. It exists because two connections from the same participant are otherwise indistinguishable. What it should contain is the experiment’s decision; identifying the page the participant is on is one choice, and lets a handler ignore a message from a page they have since left. A socket opened with dallinger.openExperimentSocket or dallinger.openChatSocket makes that choice by default, sending dallinger.pageScope, a value generated once per page load, unless it is given a scope of its own or a scope of null.

Messages must be text. Dallinger splits each one on its channel prefix, and a binary frame has no prefix to split on, so the connection is closed with code 1003 and the reason text frames only.

An experiment socket must name a participant that exists, because every message is reported to the method as coming from someone. Dallinger closes the socket otherwise, with code 1008 and the reason unknown participant.

The lookup proves only that a row with that id exists. /experiment-socket is not authenticated, so the id says which participant the connection claims to be, not who is sending the messages. Treat it as Dallinger treats every other participant_id.

An experiment that needs more can check each connection as it opens, by overriding accept_websocket_connection(). It is given the participant id and the connection’s scope. To accept only connections from a participant’s own pages, render each page with a token the server signs, and have the page open its socket with dallinger.openExperimentSocket({scope: token}). The token below is a random nonce and a signature of the participant id and that nonce, so nothing needs to be stored, and each page still has a scope of its own, which keeps directed sends going to the page that asked:

import hashlib
import hmac
import os
import secrets

def signature(participant_id, nonce):
    key = os.environ["FLASK_SECRET_KEY"].encode()
    message = "{}:{}".format(participant_id, nonce).encode()
    return hmac.new(key, message, hashlib.sha256).hexdigest().encode()

def page_token(participant_id):
    nonce = secrets.token_hex(16)
    return nonce + "." + signature(participant_id, nonce).decode()

class MyExperiment(Experiment):
    def accept_websocket_connection(self, participant_id, scope):
        nonce, _, mac = (scope or "").partition(".")
        expected = signature(participant_id, nonce)
        return bool(nonce) and hmac.compare_digest(mac.encode(), expected)

Don’t keep a token anywhere a route returns it: GET /participant/<id> returns a participant’s property1 to property5 and details to anyone who asks. The scope isn’t hidden from the people running the experiment either. Dallinger logs it, includes it in control channel events, and saves it with real-time records, so the check stops one participant’s page from connecting as another participant, not someone who can read the logs or the data.

A falsy return closes the socket with code 1008 and the reason refused by the experiment, before it subscribes to any channel or joins a real-time session. A /chat connection that names a participant, as dallinger.openChatSocket() does once the page knows its participant, is checked the same way, so pass it the same token. One that names no participant isn’t checked: it can subscribe to channels and receive their broadcasts, but it isn’t sent directed messages and can’t join a real-time session. The waiting room’s connection (dallinger.waitForQuorum()) names no participant, so a token check doesn’t hold it up.

Three failures that are not the client’s fault close with 1013 instead, which tells the client to try again later: a participant lookup that raises, an experiment class that fails to build, and an accept_websocket_connection that raises.

A socket opened with dallinger.openExperimentSocket or dallinger.openChatSocket stops reconnecting when the server refuses it, and passes the close code and reason to its onRefused callbacks, or logs them to the console if there are none:

socket.onRefused(function (code, reason) {
  console.error('The server refused the connection: ' + reason);
});

A ReconnectingWebSocket created directly reconnects after every close, and reports the close code on its connecting event rather than on close. A refusal is therefore indistinguishable from a dropped network connection, and repeats forever. Pass such a socket to dallinger.stopReconnectingIfRefused to handle it:

socket = new ReconnectingWebSocket(...);
dallinger.stopReconnectingIfRefused(socket, function (code, reason) {
  console.error("The server refused the connection: " + reason);
});

The callback is optional. The socket is left in the CLOSED state, so code that reads readyState can tell a refusal from a reconnect still in progress. A close with any other code, including the 1013 above, still reconnects.

Reaching Other Participants from a Handler

A message that goes to the handler never reaches the channel, so no other client sees it. That is what a turn-based game wants, since a player’s raw move should not be echoed to the room before the experiment has ruled on it. A chat room wants the opposite.

Messages can be sent to particular participants using the publish_to_participants() method, which is described in its own section below. To fan a message out to all of the subscribers of a channel, publish it from the handler:

def handle_websocket_message(
    self, message, *, channel_name, participant_id, scope, receive_time
):
    # ... act on the message, commit whatever it changed ...
    self.publish_to_subscribers(message, "chatroom_broadcast")

Publish to a channel the experiment does not subscribe to, as above, and give the browsers that channel to listen on. Dallinger subscribes the experiment to its channel at launch, so publishing a handled message back to that channel delivers it to the experiment a second time, through send() and a worker.

Leaving the publish out is easy to miss. The database rows are correct and the sender’s own browser shows the message, while every other client sees nothing.

Sessions and the Experiment Socket

Dallinger removes the database session after each message, so a handler always starts with an empty identity map, and nothing holds a transaction open between messages. Two consequences for experiment code:

  • Load rows inside the handler and let them go when it returns. An ORM object kept on the experiment instance, or on anything else that outlives the call, is detached by the time the next message arrives.

  • Commit your own writes. Dallinger does not commit for you here, just as it does not for a worker event.

The experiment instance is built once per web process and shared by every sync socket that process is serving, which is the arrangement the launched experiment already has on the process that served /launch. Keep per-participant state off it.

The same rule reaches back into configure(). Dallinger removes the session as soon as the constructor returns, so a row loaded there and kept on self is detached before the first message arrives, and stays that way for the life of the process. Setting plain values from the configuration, which is what configure is for, is unaffected.

An exception raised by a handler is logged, and the connection stays open.

What a Handler Blocks

A handler blocks the whole web process, not just the connection it came from.

Dallinger’s web workers run under gunicorn’s gevent worker, and gevent switches greenlets only at a yield point. Nothing in psycopg2 yields; it waits for the database inside a C socket call. So while one handler waits on a query, every other websocket on that worker, and every HTTP request it is serving, waits with it.

Budget accordingly. A couple of indexed queries is fine. A sequential scan, an external HTTP call, or anything whose duration grows with the number of participants enrolled is not. Send that work to a worker with dallinger.db.get_queue(), which is what the default handle_websocket_message() does. An experiment that opens an experiment socket without overriding the method gets the same asynchronous handling /chat gives. A game that has to answer moves at once can be written for the real-time engine instead, which keeps the game’s state in redis and needs no database work on the web process.

Calling redis while holding a row lock can stall other processes too. Code locks a row by updating it or with with_for_update(), and keeps the lock until it commits. If it calls redis in between, including through publish_to_participants() or publish_to_subscribers(), the lock is held for as long as redis takes to answer, which can be seconds if redis is busy or unreachable. A web process that needs the same row waits all that time, and every socket and request it serves waits with it. A job on a worker process waits too, though the worker’s other jobs carry on. Sending the message with dallinger.db.run_after_commit() releases the lock before redis is called.

A handler will typically dispatch on the message type, doing the work that has to happen immediately and queueing the rest:

def handle_websocket_message(
    self, message, *, channel_name, participant_id, scope, receive_time
):
    data = json.loads(message)
    if data["type"] == "move":
        participant = db.session.get(Participant, int(participant_id))
        # Assign a new dict rather than mutating the existing one
        participant.details = dict(
            participant.details,
            move=data["action"],
            at=receive_time.isoformat(),
        )
        db.session.commit()
        self.publish_to_participants(
            {"type": "move_accepted", "by": participant_id},
            participant_ids=[self.partner_of(participant_id)],
        )
    else:
        db.get_queue("high").enqueue(score_the_round, participant_id)

The explicit commit is required, because Dallinger removes the session once the handler returns and discards any uncommitted work along with it. score_the_round must be a module-level function in the experiment package, since the worker process imports it by name.

details is an ordinary JSONB column with no change tracking, so SQLAlchemy will only notice the write if the attribute is assigned a new value, and a datetime such as receive_time has to be converted with isoformat() before it can be stored in one.

A payload carrying the immediate flag is the exception. The default implementation passes the message to send(), which runs receive_message() inline for such a payload. On an experiment socket that inline work happens on the web process rather than on a worker, and the budget above applies to it.

Making Database Waits Cooperative

Dallinger applies psycogreen in the gunicorn web workers and in the RQ gevent workers. psycogreen registers a gevent wait callback so that psycopg2 socket waits yield to the gevent event loop rather than blocking the OS thread — a database wait in one greenlet no longer stalls every other request on the same worker.

The trade-off is that psycogreen puts psycopg2 into asynchronous mode, which does not support the COPY command. dallinger export and dallinger.data.ingest_zip use COPY, but they run as CLI commands in a separate process where psycogreen is never applied, so they are unaffected. The limitation applies to experiment code: if a handler or RQ job calls data.export() or ingest_zip() directly, it will fail inside a patched process. Psycopg 3 would keep COPY cooperative natively, but requires the SQLAlchemy 2.0 upgrade first. Issue #9807 has the full comparison.

Sending to Specific Participants

While publish_to_subscribers() sends a message to every subscriber of a channel, the publish_to_participants() method sends a payload to particular participants, named by their participant ids:

self.publish_to_participants(
    {"type": "move_accepted", "by": participant_id},
    participant_ids=[partner_id],
)

The recipients do not need a channel of their own, and do not need to subscribe to anything. Any connection which included a participant_id argument in its url, on either the /chat or the /experiment-socket route, can be addressed in this way, and the payload will be delivered to every connection that participant currently holds, whichever web process is holding it. The method may be called from anywhere, including a WebSocket handler, a worker event, or an ordinary route.

This replaces the pattern of giving each participant a channel named after them, such as participant_12_channel. Named channels remain the natural choice for a group of participants who should all receive the same messages.

Neither WebSocket route is authenticated by default. Both check only that the participant a connection names exists, so a connection is addressed by the participant_id it claims rather than by one it has proved it owns, and anyone who can guess a participant id can open a socket naming it and be sent that participant’s directed messages. An experiment that overrides accept_websocket_connection() to check a token, as above, makes directed messages private to the participant’s own pages. Without that check, treat the id as Dallinger treats every other participant_id, and keep out of a payload anything another participant must not read. Channel broadcasts are never private: any connection may subscribe to any channel that isn’t reserved. Nor do they say who sent them: a message published through /chat is relayed as the client wrote it, so a sender or participant id in its payload is whatever the client put there. For messages attributed to their sender, use /experiment-socket, where handle_websocket_message() is given the admitted participant’s id.

Naming a participant who has no open connection, or who is not connected to this deployment at all, delivers nothing and is not an error. As with a broadcast, no message is buffered or replayed, so a payload published while a participant is reconnecting will not reach them. Anything a client must not miss should be stored in the database, with the directed message serving as a prompt to fetch it.

A redis failure is the one delivery problem which is reported. It raises, and the payload will have reached none of the recipients, so the call can be retried as a whole.

Directed Message Format

Directed messages arrive on the client prefixed with the reserved dallinger_direct channel name, using the same channel:payload format as every other WebSocket message, so a single connection can receive both channel broadcasts and directed messages. A socket opened with dallinger.openChatSocket or dallinger.openExperimentSocket passes them to its onDirect callbacks, and its channel’s broadcasts to its onBroadcast callbacks:

socket.onDirect(function (data) {
    // Take different actions based on message type
    switch (data.type) {
       ...
    }
});

Like dallinger_control, the dallinger_direct channel and the dallinger_realtime_session channel, which carries real-time sessions’ views and tells pages when their sessions start, are reserved for Dallinger’s own use. Experiments should not publish to them, and clients may neither publish to them nor subscribe to them; the server discards such a message or subscription and logs a warning. All three carry messages in the same format as the ones a client expects to receive, so a subscriber would be given other participants’ messages as though they were its own.

Connection Scope

A participant may hold more than one connection at a time, for example a page which opens two sockets, or a reload whose previous socket has not yet timed out. By default every one of them receives the payload. The optional scope argument limits delivery to those connections which included the same scope value in their url:

def handle_websocket_message(
    self, message, *, channel_name, participant_id, scope, receive_time
):
    ...
    self.publish_to_participants(
        {"type": "accepted"}, participant_ids=[participant_id], scope=scope
    )

The handler is given the scope of the connection its message arrived on, so replying with that value reaches the page which sent the message and leaves a tab open on an earlier page untouched.

That value should not be passed on when addressing a different participant. Their connections will have supplied a scope of their own, and a payload scoped to the sender’s page won’t be sent to them. Supply a scope when addressing the same participant, and omit it otherwise, unless the experiment has defined scope as a value which both participants share.

Dallinger compares the two values as strings and does not interpret them; what a scope means is up to the experiment. A connection which supplied no scope will only receive messages which were published without one.

Cross-Process Delivery

The process which publishes a directed message delivers it to any matching connections it holds itself, and publishes an envelope naming the recipients to redis so that the other web processes can deliver it to theirs. Every process reads every envelope and delivers to whichever of the named participants it holds connections for. The payload is serialized once, by the publishing process, so every recipient of a single call is sent identical bytes.

Client Implementation

The default experiment layout includes dallinger2.js, whose dallinger.openChatSocket and dallinger.openExperimentSocket functions open a connection to the /chat and /experiment-socket routes respectively. Both identify the participant from dallinger.identity, and both return a dallinger.Socket which takes care of the message format, reconnection, and refusal.

Typically experiments set up a WebSocket connection after completing the initial call to createAgent using code similar to this:

var broadcast_socket;
var open_socket = function (channel_id) {
    // Subscribe to the channel
    var socket = dallinger.openChatSocket({channel: channel_id});
    // Once the connection is established, send an initial message to the channel
    socket.onOpen(function (event) {
        socket.send(channel_id, {message: 'Hello world!'});
    });
    // Handle any incoming messages on the channel
    socket.onBroadcast(function (data) {
        // Take different actions based on message type
        switch (data.type) {
           ...
        }
    });
    return socket;
};
// Create the agent.
var create_agent = function () {
    dallinger.createAgent()
        .done(function (resp) {
            ...
            broadcast_socket = open_socket('broadcast_channel');
        })
        .fail(function (rejection) {
            ...
        });
};

The send method takes a channel name and a payload, which will be encoded as JSON unless it is already a string. Messages may be sent to any channel, not just the one to which the connection is subscribed. The exceptions are "dallinger_control", which is reserved for the server’s own connection and subscription events, "dallinger_direct", which is reserved for directed messages, "dallinger_realtime_session", which carries the views of pages in real-time sessions, and "dallinger_time", which carries their clock measurements. send refuses all four names. The server also discards a message a client addresses to any of the first three and logs a warning, since the experiment treats anything arriving on the control channel as genuine.

Callbacks passed to onBroadcast and onDirect receive the payload parsed as JSON, or the payload string itself if it is not JSON, followed by the payload string. A connection subscribes to at most one channel, so additional subscriptions can be established by opening further connections with different channel values.

A message sent while the connection is down will be held, and sent in order once the connection reopens. Messages published to the client in the meantime are not replayed, so a page which must not miss one should fetch whatever it needs from the experiment in an onOpen callback. Those callbacks run each time the connection opens, including after a reconnect, and the isReconnect property of the event they are passed is false the first time.

The close method ends the connection for good, discarding any messages still held. It returns a Deferred which resolves once the connection has closed, so a page can let the messages it has already sent reach the server before navigating away:

socket.send('chatroom', {type: 'log', content: 'Goodbye.'});
socket.close().always(function () {
    dallinger.goToPage('questionnaire');
});

Both functions include the participant’s worker_id and participant_id in the connection url, along with the connection’s scope. Those values will be included in the automatically generated JSON messages alerting the experiment to WebSocket connection, disconnection, subscription, and un-subscription events over the "dallinger_control" channel. The server checks only that the participant_id exists, and the experiment’s hook may check the scope. The worker_id is never checked, so don’t rely on it, and a connection without a participant_id reports none. The full interface is listed in the Javascript API.

Connecting Without the Helpers

Any WebSocket client may connect to either route directly, using the query parameters described in The Web API. Every message in either direction is a channel name followed by : and the payload, so a client reading messages itself will need to check each message’s channel prefix before parsing its payload. A connection that names a participant is checked like an experiment socket, so pass its scope, leave participant_id out when the page doesn’t know it, and wrap the socket in dallinger.stopReconnectingIfRefused so that a refused connection is not retried:

var ws_scheme = (location.protocol === 'https:') ? 'wss://' : 'ws://';
var url = ws_scheme + location.host + '/chat' +
    '?channel=' + encodeURIComponent(channel_id) +
    '&scope=' + encodeURIComponent(dallinger.pageScope);
if (dallinger.identity.participantId) {
    url += '&worker_id=' + encodeURIComponent(dallinger.identity.workerId) +
        '&participant_id=' + encodeURIComponent(dallinger.identity.participantId);
}
var socket = dallinger.stopReconnectingIfRefused(
    new ReconnectingWebSocket(url),
    function (code, reason) { console.error('Refused: ' + reason); }
);
socket.onmessage = function (msg) {
    // Ignore messages not from the subscribed channel
    if (msg.data.indexOf(channel_id + ':') !== 0) { return; }
    // Parse the payload
    var data = JSON.parse(msg.data.substring(channel_id.length + 1));
    ...
};

The onopen, onmessage and onclose handlers of a ReconnectingWebSocket must be assigned rather than called, since calling one does nothing. Its send method throws an exception while the connection is reconnecting, and its close method does not cancel a reconnection which has already been scheduled.

Experiment Channel Setup

Many experiment use cases will only need a “broadcast channel” to which all clients subscribe. That subscription can be established when the experiment starts (i.e. when createAgent returns). This “broadcast channel” would be separate from the one set in the Experiment.channel attribute, which we will call the “experiment control channel”.

Clients will receive all messages sent to the “broadcast channel” by either the experiment or other clients. The messages will generally contain JSON payloads that indicate the messages’ purpose. For example, messages may have a type property to differentiate e.g. “state” messages sent by the experiment server from “chat” messages sent by other clients. Additionally, such “chat” messages might have room or recipient properties to allow clients to filter out messages not intended for them.

Generally, clients will send messages about their actions to the “experiment control channel”. Those messages will be processed by the experiment and will not be relayed to other clients, because clients are not generally subscribed to the “experiment control channel”.

The experiment sends messages to all clients over the “broadcast channel”, but generally does not subscribe to the “broadcast channel”. If an experiment needs to handle messages sent by clients over the “broadcast channel”, then it’s generally simplest for clients to send such messages both to the “broadcast channel” and to the “experiment control channel” (perhaps with an additional broadcast flag). It is possible to subscribe the experiment to the “broadcast channel”, but that would also require the experiment to handle/ignore the messages that the experiment itself sends over that channel.

Multiple Client Channels

If an experiment needs group specific channels, e.g. to reduce the total number of messages sent to or processed by clients, then clients can subscribe to multiple channels. Channels organise traffic but don’t keep it private: any connection may subscribe to any channel that isn’t reserved, so a client that skips the filtering described below still receives a group’s messages.

For example, after launch an experiment could broadcast a create_chatroom type message with a chatroom property set to e.g. “room_1” and an array of participant_ids. Clients could then subscribe to the “room_1” channel using the /chat route only if their participant_id matches one of the values in participant_ids. That way the other clients’ pages would not be sent messages for “room_1”, though nothing stops them subscribing.

If these chat room messages need to be handled by the experiment code, then the clients could also send these messages to the “experiment control channel”, with an additional chatroom property to specify the channel. Alternatively, if the names of all chatrooms could be determined at experiment launch time, then duplicate messages can be avoided by having the experiment subscribe to all chatrooms in on_launch() or using background_tasks().

Don’t give each participant a channel of their own to send them private messages: anyone could subscribe to it. Send them directed messages with publish_to_participants() instead (see Sending to Specific Participants), and override accept_websocket_connection() to check a token, as described above, so that only the participant’s own pages receive them.

Connection Limits

Each web process holds one Redis connection for every channel that has at least one client in that process, and releases it when the last client leaves. Channels that the experiment itself subscribes to stay open for the whole run, and the listener for directed sends (dallinger_direct) keeps running after its last client leaves, so each process also holds one connection for it alongside the experiment and control channels. With one channel per participant, the number of Redis connections is therefore about the number of participants connected at once.

Channel subscriptions use their own pool of up to 1,000 Redis connections per web process, separate from the pool used for other Redis calls such as publishing and queueing jobs, so busy channels never hold up those calls. Once a process has 1,000 channels open, a further channel relays no messages until another channel closes and frees a connection; its listener keeps retrying in the meantime.

Because an empty channel is released, a client that joins it again starts a new Redis subscription. Messages published to that channel before the subscription reaches Redis are not relayed, so don’t rely on a message sent the instant a client connects; have the client request the current state once it is connected instead.

The 1,000-connection limits apply to each web process separately, so all the web processes of an app (see web_processes) together can open more connections than Redis accepts. Redis’s own client limit, maxclients, is shared by every process and defaults to 10,000, but Redis lowers it at startup when its own open-file limit is too low. Hosted Redis plans, such as those on Heroku, often allow far fewer clients. Run CONFIG GET maxclients in redis-cli to check the limit of your Redis server.

Each connection also uses a file descriptor in its web process, alongside the participant’s websocket. The web container of dallinger docker and dallinger docker-ssh deployments allows 65,536 open files per process, but other containers and hosts often keep a soft limit of 1,024, which caps each web process at about 500 participants with their own channel.