Connection
The Ably Realtime library establishes and maintains a connection to the Ably service, using the most efficient transport available, typically WebSockets. The Ably realtime protocol operates and multiplexes all channel traffic over that connection. Channels are separate from Connections and are used to logically separate messages into different topics, see the channels documentation for further information.
Getting started
The Ably Realtime library will open and maintain a connection to the Ably realtime servers as soon as it is instantiated. The Connection
object provides a straightforward API to monitor and manage connection state.
The following example relies on the default auto-connect behavior of the library, and then subscribes to the connection’s connected
event.
const ably = new Ably.Realtime({ '<loading API key, please wait>' });
ably.connection.on('connected', () => {
console.log('Connected to Ably!');
});
Demo OnlyCopyCopied!
If using the promises interface:
const ably = new Ably.Realtime.Promise('<loading API key, please wait>');
await ably.connection.once("connected");
console.log('Connected to Ably!');
Demo OnlyCopyCopied!
Note that all examples on this page assume you are running them within an EventMachine reactor. Find out more in our Realtime usage documentation
Connection state explained
Although connection state is temporary, the Ably protocol provides continuity of message delivery between the client and the service, provided that a dropped connection is reestablished by the client within a limited interval (typically around 2 minutes). Beyond that, the connection becomes stale and the system will not attempt to recover the connection state. The lifecycle of a connection, and the strategy for reconnecting on failure, reflect the transient nature of the connection state.
The client library is responsible for managing the connection; this includes selecting a transport (in those environments supporting multiple transports), selecting a host to connect to (automatically falling back to an alternate datacenter host if the closest datacenter is unreachable), and managing continuity of operation when the connection drops.
When the library is instantiated, if connectivity to the service is available, the library will establish a connection immediately, and if the connection drops at any time it will attempt to re-establish it by making repeated connection attempts every 15 seconds for up to two minutes.
If, after that time, there has been no connection, the library falls back to a lower level of activity, still periodically attempting reconnection at 30 second intervals. This reflects the assumption that there will no longer be recoverable connection state and the client may be offline for a period of time. As soon as a reconnection attempt has been successful, the system reverts to the more active connection behavior. Further, you can explicitly trigger a reconnection attempt at any time if you wish to implement a different reconnection strategy.
The connection object provides methods to observe the lifecycle of the connection and to trigger state transitions.
Available connection states
A series of connection states is defined as follows:
- initialized
- A
Connection
object having this state has been initialized but no connection has yet been attempted. - connecting
- A connection attempt has been initiated. The connecting state is entered as soon as the library has completed initialization, and is reentered each time connection is re-attempted following disconnection.
- connected
- A connection exists and is active.
- disconnected
- A temporary failure condition. No current connection exists because there is no network connectivity or no host is available.The disconnected state is entered if an established connection is dropped, or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt to open a new connection (approximately every 15 seconds), anticipating that the connection will be re-established soon and thus connection and channel continuity will be possible. In this state, developers can continue to publish messages as they are automatically placed in a local queue, to be sent as soon as a connection is reestablished. Messages published by other clients whilst this client is disconnected will be delivered to it upon reconnection, so long as the connection was resumed within 2 minutes. After 2 minutes have elapsed, recovery is no longer possible and the connection will move to the
suspended
state. - suspended
- A long term failure condition. No current connection exists because there is no network connectivity or no host is available.The suspended state is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended state, the library will periodically attempt to open a new connection every 30 seconds. Developers are unable to publish messages in this state. A new connection attempt can also be triggered by an explicit call to
connect()
on theConnection
object.Once the connection has been re-established, channels will be automatically re-attached. The client has been disconnected for too long for them to resume from where they left off, so if it wants to catch up on messages published by other clients while it was disconnected, it needs to use the history API. - closing
- An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection will be forcibly terminated and the connection state will become
closed
. - closed
- The connection has been explicitly closed by the client.In the closed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. No connection state is preserved by the service or by the library. A new connection attempt can be triggered by an explicit call to
connect()
on theConnection
object, which will result in a new connection. - failed
- This state is entered if the client library encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service (e.g. an attempt to connect with an incorrect API key), or some local terminal error (e.g. the token in use has expired and the library does not have any way to renew it).In the failed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. A new connection attempt can be triggered by an explicit call to
connect()
on theConnection
object.
Typical connection state sequences
The library is initialized and initiates a successful connection.
initialized → connecting → connected
An existing connection is dropped and reestablished on the first attempt.
connected → disconnected → connecting → connected
An existing connection is dropped, and reestablished after several attempts but within a two minute interval.
connected → disconnected → connecting → disconnected → … → connecting → connected
There is no connection established after initializing the library.
initialized → connecting → disconnected → connecting → … → suspended
After a period of being offline a connection is reestablished.
suspended → connecting → suspended → … → connecting → connected
Listening for state changes
The Connection
object is an EventEmitter
and emits an event whose name is the new state whenever there is a connection state change. An event listener function is passed a ConnectionStateChange object as the first argument for state change events.
The Connection
object can also emit an event that is not a state change: an update
event. This happens when there’s a change to connection conditions for which the connection state doesn’t change – that is, when the library remains connected, e.g. after a reauth.
realtime.connection.on('connected', (stateChange) => {
console.log('Ably is connected');
});
CopyCopied!
Alternatively a listener may be registered so that it receives all state change events.
realtime.connection.on((stateChange) => {
console.log('New connection state is ' + stateChange.current);
});
CopyCopied!
Previously registered listeners can be removed individually or all together.
/* remove a listener registered for a single event */
realtime.connection.off('connected', myListener);
/* remove a listener registered for all events */
realtime.connection.off(myListener);
/* remove all event listeners */
realtime.connection.off();
CopyCopied!
Handling failures
The client libraries will attempt to automatically recover from non-fatal error conditions. However, it will emit events to say what it’s doing, so you can handle them yourself if you prefer.
Fatal errors
Some classes of errors are fatal. These cause the connection to move to the FAILED
state. The client library will not attempt any automatic recovery actions. For example, if your token expires and the client library has no way to get a new token (so no authUrl and authCallback), the connection will enter the FAILED
state
While the library will not automatically attempt to reconnect in the FAILED
state, explicit calls to connect()
will make the client try again.
Nonfatal errors
Other classes of error are nonfatal. For example, a client may have network connectivity issues. The library will attempt to automatically reconnect and recover from these sort of issues, as detailed in the DISCONNECTED
and SUSPENDED
explanations in the Available connection states section.
If message continuity is lost in the process, e.g. because you have been disconnected from Ably for more than two minutes, the library will notify you though the resumed
-flag mechanism, detailed in the Channels and Messages page.
Connection state recovery
The Ably system preserves connection state to allow connections to continue transparently across brief disconnections. The connection state that is tracked includes the messages sent to the client on the connection, members present on a channel and the set of channels that the client is attached to.
There are two modes of connection state recovery:
resume
: this is transparent recovery of a live client instance across disconnections. Upon disconnection, the library will automatically re-attempt connection and, once the connection is re-established, any missed messages will be sent to the client. The developer does not need to do anything to trigger this behavior; all client channel event listeners remain attached and are called when the backlog of messages is received.
recover
: this addresses the case in which a new client library instance wishes to connect and recover the state of an earlier connection. This occurs typically in a browser environment when the page has been refreshed and therefore the client instance is disposed and no client state is retained. In this case any message listeners associated with channels will no longer exist so it is not possible for the library simply to send the message backlog on reconnection; instead the client must re-subscribe to each channel it is interested in within 15 seconds, and its message listener(s) will be called with any message backlog for that channel. If it had any members in the presence set, they will need to explicitly re-enter. If the previously attached channels are not re-attached within 15 seconds of a connection being recovered, the client will lose the ability to continue the message stream from before; any subsequent attach() will result in a fresh attachment, with no backlog sent. A client requests recovery of connection state by including a recovery string in the client options when instancing the Realtime library. See connection state recover options for more info.
In either case, when a connection is resumed or recovered, the message backlog held on the server will be pushed to the client. However, any new messages published will be sent as they become available or messages could be indefinitely deferred on very heavily loaded connections. Therefore the system does not guarantee that messages received after reconnection are delivered in the same order that would have occurred if the connection had not been dropped. In the recover
case, in particular, the order of the message delivery depends on the timing of the re-attachment of each channel.
Connection state recover options
In recover
mode it is necessary to request recovery mode in the client options when instancing the library. Recovery requires that the library knows the previous connection’s recoveryKey
value (which includes both the private unique Connection#key
and the last message serial received on that connection). As the recovery key is never shared with any other clients, it allows Ably to safely resend message backlogs to the original client.
In the browser environment, if a callback is provided in the recover
option, when the window.beforeunload
event fires, the connection details, including the recoveryKey
, are stored in the browser’s sessionStorage. The provided recover
callback is then invoked whenever the connection state can be recovered and just before a connection is established, passing in the LastConnectionDetails
. The callback is then responsible for confirming whether the connection state should be recovered or not. For example, it is common to recover connection state when the page is reloaded but not for different pages the user has navigated to. The callback allows the developer to decide if the connection should be recovered or not at the time the new connection is established by inspecting the LastConnectionDetails
and evaluating that against any other application state. Below are two examples:
- Always recover – always recover the previous connection state if possible
const ably = new Ably.Realtime({
authUrl: '/obtainToken',
recover: (_, cb) => { cb(true); }
});
CopyCopied!
- Sometimes recover – recover the previous connection state conditionally based on some logic
const ably = new Ably.Realtime({
authUrl: '/obtainToken',
recover: (lastConnectionDetails, cb) => {
/* Only recover if the current path hasn't changed, start a
* fresh connection if it has. This is just an example, you
* can use whatever logic your app requires */
if (lastConnectionDetails.location.href === document.location.href) {
cb(true); /* recover connection */
} else {
cb(false); /* do not recover connection */
}
}
});
CopyCopied!
Please note that as sessionStorage
is used to persist the LastConnectionDetails
between page reloads, it is only available for pages in the same origin and top-level browsing context.
Alternatively, if it is necessary to be explicit about the connection recoveryKey
, the connection can be recovered by providing the last value of the connection’s recoveryKey
value in the client options recover
attribute when instancing the library.
Connection recovery constraints
Connection recovery requires that the new client library instance uses credentials that are compatible with those used for the inherited connection; this requires that the same authentication mode is used, with the same key. If token auth was used, the same token is not required, but the token used must have the same capability
and clientId
. This ensures that the client recovering the connection cannot receive a backlog of messages that its new credentials are not entitled to access. Incompatible credentials will result in an unrecoverable connection error.
Heartbeats
Heartbeats enable Ably to identify clients that abruptly disconnect from the service, such as where an internet connection drops out or a client changes networks.
Ably sends a heartbeat to connected clients every 15 seconds. If a client goes more than 25 seconds without seeing any server activity from Ably, it assumes that something has gone wrong with the connection and the connection state will become disconnected
. The 25 seconds the client waits is the heartbeat interval plus a 10 second margin of error to allow for network delays.
Ably also uses this mechanism to detect dropped client connections, though some details vary depending on the transport used.
It is important to note that this mechanism is only used when something disrupts communication and not does not properly terminate the TCP connection. It isn’t used when a connection is deliberately closed or disconnected, for example by calling the close()
method or being disconnected by the server.
The 15 second interval between heartbeats is used to strike a balance between optimizing battery usage for client devices and the time it takes to identify a dropped or unstable connection.
The interval between heartbeats can be customized if your app requires increased battery preservation or to identify dropped connections more quickly. Set a value between 5000 and 1800000 milliseconds (5 seconds and 30 minutes) using the heartbeatInterval
parameter within the transportParams
property of the clientOptions
object.
Using a higher heartbeatInterval
can increase the time taken for the Ably service and the client itself to identify a connection has dropped when an abrupt disconnect occurs. The number of peak connections may also appear higher as it can take longer to terminate dropped connections. Although heartbeatInterval
can be set as high as 30 minutes, Ably does not recommend setting it this high.
The following example code demonstrates establishing a connection to Ably with a heartbeatInterval
of 10 seconds:
const ably = new Ably.Realtime(
{
key: '<loading API key, please wait>',
transportParams: { heartbeatInterval: 10000 }
}
);
Demo OnlyCopyCopied!
API Reference
View the Connection API Reference.