Warning: You are viewing an old version (1.0) of this documentation. We recommend you view the latest version 1.2.
Realtime Client Library API

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.

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.

var ably = new Ably.Realtime('xVLyHw.lsu5Jw:y0ayDK1JsdSfSrP1nuzDNIiE4CxUtgagCaTOQd0Su8s');
ably.connection.on('connected', function() {
  alert('Connected, that was easy');
})
var Ably = require('ably');
var ably = new Ably.Realtime('xVLyHw.lsu5Jw:y0ayDK1JsdSfSrP1nuzDNIiE4CxUtgagCaTOQd0Su8s');
ably.connection.on('connected', function() {
  console.log('Connected, that was easy');
})
ably = Ably::Realtime.new('xVLyHw.lsu5Jw:y0ayDK1JsdSfSrP1nuzDNIiE4CxUtgagCaTOQd0Su8s')
ably.connection.on(:connected) do
  puts "Connected, that was easy"
end
AblyRealtime ably = new AblyRealtime("xVLyHw.lsu5Jw:y0ayDK1JsdSfSrP1nuzDNIiE4CxUtgagCaTOQd0Su8s");
ably.connection.on('connected', new ConnectionStateListener() {
  @Override
  public void onConnectionStateChanged(ConnectionStateChange change) {
    System.out.println("Connected, that was easy");
  }
});
AblyRealtime ably = new AblyRealtime("xVLyHw.lsu5Jw:y0ayDK1JsdSfSrP1nuzDNIiE4CxUtgagCaTOQd0Su8s");
ably.Connection.On(ConnectionState.Connected, args => {
  Console.WriteLine("Connected, that was easy");
});
ARTRealtime *ably = [[ARTRealtime alloc] initWithKey:@"xVLyHw.lsu5Jw:y0ayDK1JsdSfSrP1nuzDNIiE4CxUtgagCaTOQd0Su8s"];
[ably.connection on:ARTRealtimeConnectionEventConnected callback:^(ARTConnectionStateChange *change) {
    NSLog(@"Connected, that was easy");
}];
let realtime = ARTRealtime(key: "xVLyHw.lsu5Jw:y0ayDK1JsdSfSrP1nuzDNIiE4CxUtgagCaTOQd0Su8s")
realtime.connection.on(.connected) { change in
    print("Connected, that was easy")
}

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()connectConnect():#connect on the Connection 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()connectConnect():#connect on the Connection object, which will result in a new connection.
failed
An indefinite failure condition. This state is entered if a connection error has been received from the Ably service (such as an attempt to connect with invalid credentials). A failed state may also be triggered by the client library directly as a result of some local permanent error.

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()connectConnect():#connect on the Connection 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.An event listener function is passed a ConnectionStateChange object as the first argument for state change events.The event block is passed the new state and an optional ErrorInfo object

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', function(stateChange) {
  console.log('Ably is connected');
});
realtime.connection.on('connected', function(stateChange) {
  console.log('Ably is connected');
});

Alternatively a listener may be registered so that it receives all state change events.

realtime.connection.on(function(stateChange) {
  console.log('New connection state is ' + stateChange.current);
});
realtime.connection.on(function(stateChange) {
  console.log('New connection state is ' + stateChange.current);
});

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();
/* 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();
realtime.connection.on(ConnectionEvent.connected, new ConnectionStateListener() {
  @Override
  public void onConnectionStateChanged(ConnectionStateChange change) {
    System.out.println("New state is connected");
  }
});

Alternatively a listener may be registered so that it receives all state change events.

realtime.connection.on(new ConnectionStateListener() {
  @Override
  public void onConnectionStateChanged(ConnectionStateChange change) {
    System.out.println("New state is " + change.current.name());
  }
});

Previously registered listeners can be removed individually or all together.

/* remove a single listener */
realtime.connection.off(myListener);

/* remove all event listeners */
realtime.connection.off();
realtime.Connection.On(ConnectionState.Connected, args => {
  Console.WriteLine("Connected, that was easy")
});

Alternatively a handler may be registered so that it receives all state change events.

realtime.Connection.On(args => {
  Console.WriteLine("New state is " + args.Current)
});

Previously registered handlers can be removed individually or all together.

/* remove a single handler */
realtime.Connection.Off(action);

/* remove all event handlers */
realtime.Connection.Off();
realtime.connection.on(:connected) do
  puts 'Ably is connected'
end

Alternatively a listener may be registered so that it receives all state change events.

realtime.connection.on do |state_change|
  puts "New connection state is #{state_change.current}"
end

Previously registered listeners can be removed individually or all together.

# remove a listener registered for a single even
realtime.connection.off :connected, &block

# remove a listener registered for all events
realtime.connection.off &block

# remove all event listeners
realtime.connection.off
ARTEventListener *listener = [realtime.connection on:ARTRealtimeConnectionEventConnected callback:^(ARTConnectionStateChange *change) {
    NSLog(@"Ably is connected");
}];

Alternatively a listener may be registered so that it receives all state change events.

ARTEventListener *listener = [realtime.connection on:^(ARTConnectionStateChange *change) {
    NSLog(@"New connection state is %lu", (unsigned long)change.current);
}];

Previously registered listeners can be removed individually or all together.

// remove a listener registered for a single event
[realtime.connection off:ARTRealtimeConnectionEventConnected listener:listener];

// remove a listener registered for all events
[realtime.connection off:listener];

// remove all event listeners
[realtime.connection off];
let listener = realtime.connection.on(.connected) { change in
    print("Ably is connected")
}

Alternatively a listener may be registered so that it receives all state change events.

let listener = realtime.connection.on { change in
    print("New connection state is \(change!.current)")
}

Previously registered listeners can be removed individually or all together.

// remove a listener registered for a single event
realtime.connection.off(.connected, listener: listener)

// remove a listener registered for all events
realtime.connection.off(listener)

// remove all event listeners
realtime.connection.off()

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 recoveryKeyrecovery_keyRecoveryKey value (which includes both the private unique Connection#keyConnection#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
var ably = new Ably.Realtime({
  authUrl: '/obtainToken',
  recover: function(_, cb) { cb(true); }
});
var ably = new Ably.Realtime({
  authUrl: '/obtainToken',
  recover: function(_, cb) { cb(true); }
});
  • Sometimes recover – recover the previous connection state conditionally based on some logic
var ably = new Ably.Realtime({
  authUrl: '/obtainToken',
  recover: function(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 */
    }
  }
});
var ably = new Ably.Realtime({
  authUrl: '/obtainToken',
  recover: function(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 */
    }
  }
});

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 clientIdclient_idClientId. 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.

API Reference

View the Connection API Reference.


Need help?

If you need any help with your implementation or if you have encountered any problems, do get in touch. You can also quickly find answers from our knowledge base, and blog.