ably.com Open in urlscan Pro
2606:4700:10::6814:59c3  Public Scan

URL: https://ably.com/topic/websockets-react-native
Submission: On December 19 via api from BY — Scanned from DE

Form analysis 3 forms found in the DOM

GET /search

<form class="flex items-start" action="/search" method="get">
  <div class="relative w-full"><svg class="text-cool-black absolute top-12 left-16" style="width: 1.5rem; height: 1.5rem;">
      <use xlink:href="#sprite-icon-gui-search"></use>
    </svg><input type="search" name="q" class="ui-input pl-48 h-48" placeholder="Search" autocomplete="off" data-id="meganav-search-input">
    <div class="absolute w-full mt-8 z-10 hidden shadow-container rounded-lg bg-white border border-mid-grey" data-id="meganav-search-autocomplete-container">
      <ol class="m-16" data-id="meganav-search-autocomplete-list"></ol>
    </div>
  </div><button type="submit" class="ui-btn-secondary flex-shrink-0 ml-8 sm:ml-16 md:ml-24 xl:ml-32">Search</button>
</form>

GET /search

<form class="mb-16" action="/search" method="get">
  <div class="relative w-full"><svg class="text-cool-black absolute top-12 left-16 hover:text-gui-hover" style="width:1.5rem;height:1.5rem">
      <use xlink:href="#sprite-icon-gui-search"></use>
    </svg><button type="button" class="absolute top-12 right-16 p-0 focus:outline-gui-focus m-0 md:hidden invisible" data-id="meganav-search-input-clear"><svg class="text-dark-grey " style="width:1.5rem;height:1.5rem">
        <use xlink:href="#sprite-icon-gui-cross-circled-fill"></use>
      </svg></button><input type="search" name="q" class="ui-input px-48 h-48" style="max-width:none" placeholder="Search" autocomplete="off" data-id="meganav-mobile-search-input">
    <div class="absolute w-full mt-8 z-10 hidden shadow-container rounded-lg bg-white border border-mid-grey" data-id="meganav-search-autocomplete-container">
      <ol class="m-16" data-id="meganav-search-autocomplete-list"></ol>
    </div>
  </div>
</form>

<form class="col-span-full sm:col-span-4 relative z-10">
  <div class="font-sans font-medium  uppercase  tracking-widen-0.1 text-overline2 text-white mb-8">Enter your email</div><input class="ui-input" type="email" name="EMAIL" value=""><button type="submit" class="ui-btn-invert mt-24"
    disabled="">Submit</button>
</form>

Text Content

 * ProductsProducts
   
   
   THE ABLY PLATFORM
   
   Easily power any realtime experience in your application. No complex
   infrastructure to manage or provision. Just a simple API that handles
   everything realtime, and lets you focus on your code.
   
   Explore how it works
   
   
   PRODUCTS
   
    * Pub/Sub Channels
      
      Build infinitely scalable realtime applications.
   
    * Spaces (Beta)
      
      Create multi-user collaborative environments.
   
    * LiveSync (Early access)
      
      Keep clients in sync with any relational database.
   
   
   TECHNOLOGY
   
    * Predictable performance
      
      A low-latency and high-throughput global network.
   
    * Guaranteed ordering & delivery
      
      Data is delivered - in order - even after disconnections.
   
    * Fault tolerant infrastructure
      
      Redundancy is built in at global and regional levels.
   
    * High scalability & availability
      
      Built for scale with legitimate 99.999% uptime SLAs.
   
    * Global edge network
      
      An edge network of 15 core routing datacenters and 205+ PoPs.
   
   Explore Four Pillars of Dependability
   
 * SolutionsSolutions
   
   
   SOLUTIONS
   
    * Live Chat
      
      Deliver highly reliable chat experiences at scale.
   
    * Multiplayer Collaboration
      
      Bring collaborative multiplayer experiences to your users.
   
    * Data Broadcast
      
      Broadcast realtime event data to millions of devices around the globe.
   
    * Data Synchronization
      
      Keep your frontend and backend in realtime sync, at global scale.
   
    * Notifications
      
      Deliver cross-platform push notifications with a simple unified API.
   
    * Asset Tracking (Beta)
      
      Track assets in realtime with a solution optimised for last mile
      logistics.
   
   
   INDUSTRY
   
    * EdTech
      
      Deliver interactive learning experiences.
   
    * FinTech
      
      Deliver personalised financial data in realtime.
   
    * Automotive, Logistics, & Mobility
      
      Power diagnostics, order tracking and more.
   
    * B2B Platforms
      
      Empower your customers with realtime solutions.
   
    * Healthcare (HIPAA)
      
      Provide trustworthy, HIPAA-compliant realtime apps.
   
    * eCommerce & Retail
      
      Enrich customer experiences with realtime updates.
   
    * Sports, Media & Audience Engagement
      
      Deliver engaging global realtime experiences.
   
    * Gaming
      
      Power ultra fast and reliable gaming experiences.
   
    * IoT & Connected Devices
      
      Monitor and control global IoT deployments in realtime.
   
   
 * CompanyCompany
   
   
   WHY COMPANIES CHOOSE ABLY
   
    * Customers
      
      Ably supports customers across multiple industries.
   
    * Case studies
      
      Discover how customers are benefiting from Ably.
   
    * Compare our tech
      
      Choose the right realtime service.
   
    * Partners
      
      Ably collaborates and integrates with AWS.
   
    * Resources
      
      Learn more about realtime with our handy resources.
   
    * About Ably
      
      Find out more about Ably’s mission.
   
    * Careers
      
      Discover our open roles and core Ably values.
   
    * Events
      
      Join Ably at upcoming events.
   
   
   BLOG
   
    * How To Enhance AG Grid with Avatars: Building a Collaborative Grid with
      React and Ably
      
      Dec 15, 2023
   
    * Enabling productivity: Ably Hackathon Projects
      
      Dec 14, 2023
   
    * Realtime Dashboards: Ably Realtime Hackathon projects
      
      Dec 12, 2023
   
   More from our Blog
   
 * DevelopersDevelopers
   
   
   EXPLORE
   
    * Documentation
      
      Technical guides to help you build with Ably.
   
    * Quickstart guides
      
      Documentation to help you get started quickly.
   
    * Integrations
      
      Find out more about Ably integrations.
   
    * Live examples
      
      Discover our features and their use cases.
   
    * SDKs
      
      Download an SDK to help you build realtime apps faster.
   
    * Tutorials & Demos
      
      Get stuck in with our hands-on resources.
   
    * Chat apps reference guide
      
      Learn how to build chat apps with Ably.
   
    * Multiplayer reference guide
      
      Learn how to build collaborative features with Ably.
   
   
   QUICK LINKS
   
    * Discord
   
    * GitHub
   
    * Changelog
   
    * Status
   
    * Support & FAQs
   
   
 * Pricing

 * Contact us
 * Login
 * 
   Search
   
   Popular pages
   
    * How does Ably work?
    * Quickstart guide
    * Publish/Subscribe Messaging
    * Platform
   
   Support
 * Sign up free

 * Login

 * Popular pages
   
    * How does Ably work?
    * Quickstart guide
    * Publish/Subscribe Messaging
    * Platform
   
    * Products
      Back
      
      
      THE ABLY PLATFORM
      
      Easily power any realtime experience in your application. No complex
      infrastructure to manage or provision. Just a simple API that handles
      everything realtime, and lets you focus on your code.
      
      Explore how it works
      
      
      PRODUCTS
      
       * Pub/Sub Channels
         
         Build infinitely scalable realtime applications.
      
       * Spaces (Beta)
         
         Create multi-user collaborative environments.
      
       * LiveSync (Early access)
         
         Keep clients in sync with any relational database.
      
      
      TECHNOLOGY
      
       * Predictable performance
         
         A low-latency and high-throughput global network.
      
       * Guaranteed ordering & delivery
         
         Data is delivered - in order - even after disconnections.
      
       * Fault tolerant infrastructure
         
         Redundancy is built in at global and regional levels.
      
       * High scalability & availability
         
         Built for scale with legitimate 99.999% uptime SLAs.
      
       * Global edge network
         
         An edge network of 15 core routing datacenters and 205+ PoPs.
      
      Explore Four Pillars of Dependability
      
    * Solutions
      Back
      
      
      SOLUTIONS
      
       * Live Chat
         
         Deliver highly reliable chat experiences at scale.
      
       * Multiplayer Collaboration
         
         Bring collaborative multiplayer experiences to your users.
      
       * Data Broadcast
         
         Broadcast realtime event data to millions of devices around the globe.
      
       * Data Synchronization
         
         Keep your frontend and backend in realtime sync, at global scale.
      
       * Notifications
         
         Deliver cross-platform push notifications with a simple unified API.
      
       * Asset Tracking (Beta)
         
         Track assets in realtime with a solution optimised for last mile
         logistics.
      
      
      INDUSTRY
      
       * EdTech
         
         Deliver interactive learning experiences.
      
       * FinTech
         
         Deliver personalised financial data in realtime.
      
       * Automotive, Logistics, & Mobility
         
         Power diagnostics, order tracking and more.
      
       * B2B Platforms
         
         Empower your customers with realtime solutions.
      
       * Healthcare (HIPAA)
         
         Provide trustworthy, HIPAA-compliant realtime apps.
      
       * eCommerce & Retail
         
         Enrich customer experiences with realtime updates.
      
       * Sports, Media & Audience Engagement
         
         Deliver engaging global realtime experiences.
      
       * Gaming
         
         Power ultra fast and reliable gaming experiences.
      
       * IoT & Connected Devices
         
         Monitor and control global IoT deployments in realtime.
      
      
    * Company
      Back
      
      --------------------------------------------------------------------------------
      
      
      WHY COMPANIES CHOOSE ABLY
      
       * Customers
         
         Ably supports customers across multiple industries.
      
       * Case studies
         
         Discover how customers are benefiting from Ably.
      
       * Compare our tech
         
         Choose the right realtime service.
      
       * Partners
         
         Ably collaborates and integrates with AWS.
      
       * Resources
         
         Learn more about realtime with our handy resources.
      
       * About Ably
         
         Find out more about Ably’s mission.
      
       * Careers
         
         Discover our open roles and core Ably values.
      
       * Events
         
         Join Ably at upcoming events.
      
      
      BLOG
      
       * How To Enhance AG Grid with Avatars: Building a Collaborative Grid with
         React and Ably
         
         Dec 15, 2023
      
       * Enabling productivity: Ably Hackathon Projects
         
         Dec 14, 2023
      
       * Realtime Dashboards: Ably Realtime Hackathon projects
         
         Dec 12, 2023
      
      More from our Blog
      
    * Developers
      Back
      
      --------------------------------------------------------------------------------
      
      
      EXPLORE
      
       * Documentation
         
         Technical guides to help you build with Ably.
      
       * Quickstart guides
         
         Documentation to help you get started quickly.
      
       * Integrations
         
         Find out more about Ably integrations.
      
       * Live examples
         
         Discover our features and their use cases.
      
       * SDKs
         
         Download an SDK to help you build realtime apps faster.
      
       * Tutorials & Demos
         
         Get stuck in with our hands-on resources.
      
       * Chat apps reference guide
         
         Learn how to build chat apps with Ably.
      
       * Multiplayer reference guide
         
         Learn how to build collaborative features with Ably.
      
      
      QUICK LINKS
      
       * Discord
      
       * GitHub
      
       * Changelog
      
       * Status
      
       * Support & FAQs
      
      
    * Pricing
   
   --------------------------------------------------------------------------------
   
   Contact usSign up free


On this page


 1. Topics
 2. /
 3. Protocols
 4. &Client-side frameworks
 5. /
 6. Realtime apps with React Native and WebSockets: client-side challenges

13 min read


REALTIME APPS WITH REACT NATIVE AND WEBSOCKETS: CLIENT-SIDE CHALLENGES

Written by:
Alex Diaconu


At a global level, there is an ever-increasing appetite for data delivered in
real time, with WebSockets being probably the most popular transport protocol
for such use cases. Before WebSockets came along, the “realtime” web existed,
but it was difficult to achieve, typically slower, and was delivered by hacking
existing web technologies which were not designed for realtime applications. The
WebSocket protocol paved the way to a truly realtime web.

React Native is an open-source mobile development framework built on top of
React. It enables developers to use React components along with native platform
capabilities and it’s used to develop applications across various operating
systems, such as Android, iOS, macOS, and Windows. Similar to JavaScript and
many other programming languages and frameworks, React Native supports the
standard WebSocket interface.

Since demand for realtime data is growing steadily, and with React Native being
an established and widely used development framework, I think it’s worth looking
at some of the many challenges of implementing a dependable client-side
WebSocket solution for React Native apps.    

Copy link to clipboard


STATE OF PLAY — A BRIEF OVERVIEW

Rarely is a basic or raw WebSocket implementation enough for the needs of a
realtime app that services an unknown (but potentially very high) number of
users. Most of the time, you need to think about extending the capabilities of
your React Native client-side WebSocket implementation. 

For this purpose, you could resort to an open-source library like
react-native-websocket, which provides a WebSocket API wrapped as a component
for React Native. This is how you use react-native-websocket:

import React, { Component } from 'react'
import { AppRegistry, View } from 'react-native'
import WS from 'react-native-websocket'

export default class Example extends Component {

  render () {
    return (
      <View style={{flex: 1}}>
        <WS
          ref={ref => {this.ws = ref}}
          url="wss://echo.websocket.org/"
          onOpen={() => {
            console.log('Open!')
            this.ws.send('Hello')
          }}
          onMessage={console.log}
          onError={console.log}
          onClose={console.log}
          reconnect // Will try to reconnect onClose
        />
      </View>
    )
  }
}

However, while it’s true that libraries like react-native-websocket offer some
benefits, they are essentially just wrappers around a WebSocket client; they
provide no functionality on top.

To get the most out of WebSockets, a protocol that’s built on top is often used,
which enables richer functionality, such as pub/sub. You could choose to develop
your own WebSocket-based protocol that is tailored specifically to your needs.
However, that is a very complex and time-consuming undertaking. Most of the
time, you are better off using an established WebSocket-based solution that is
well prepared to handle an entire set of engineering complexities. 

Here at Ably, we have a protocol for pub/sub that is used on top of WebSockets.
It allows you to communicate over WebSockets by using a higher-level set of
capabilities. To demonstrate how simple it is, here’s an example of how data is
published to Ably:

var ably = new Ably.Realtime('ABLY_API_KEY');
var channel = ably.channels.get('test');

// Publish a message to the test channel
channel.publish('greeting', 'hello');

And here’s how clients connect to Ably to consume data:

var ably = new Ably.Realtime('ABLY_API_KEY');
var channel = ably.channels.get('test');

// Subscribe to messages on channel
channel.subscribe('greeting', function(message) {
  alert(message.data);
});

As you can see from the code snippets above, although the communication is done
over WebSockets, the underlying WebSocket protocol is ‘’hidden’’ from
developers.

You can decide to use any WebSocket-based protocol that supports React Native.
Regardless of your choice, though, you need to consider the entire spectrum of
challenges you’ll face when it comes to WebSockets. 

Copy link to clipboard


WEBSOCKETS AND REACT NATIVE: WHAT YOU NEED TO CONSIDER

Before we get started, I must emphasize that this article only focuses on the
client-side challenges of building a dependable WebSocket-based solution for
React Native apps. I assume you have already decided what solution you want to
use on the server-side. If you haven’t yet, you can go with an open-source
library like Socket.IO, or a cloud-based solution like Ably.

It’s also worth mentioning that Ably has produced a report based the responses
of 500+ engineering leaders about the challenges of building realtime
communication solutions.



I’m now going to dive into the key things you need to think about, such as
authentication, network compatibility, or handling reconnections with
continuity. Your client-side WebSocket implementation must be equipped to
efficiently handle all these complexities if you are to build a reliable system.

Copy link to clipboard


DO YOU ACTUALLY NEED WEBSOCKETS?

WebSocket is the most popular and portable realtime protocol. It provides
full-duplex communication over a single TCP connection. WebSockets are a great
choice for many use cases, such as financial tickers, chat solutions, or
location-based apps, to name just a few. But it’s not the only available option.
Before jumping on the WebSocket bandwagon, you should look at the existing
alternatives, to make sure they are not a better fit for your use case.

For example, MQTT, which also supports bidirectional communication, is the go-to
protocol for IoT devices with limited battery life, and for networks with
expensive or low bandwidth, unpredictable stability, or high latency. Another
example is Server-Sent Events, a lightweight protocol from both an
implementation and usage standpoint. It’s a superior alternative for most
browser-based scenarios where unidirectional communication is enough, such as
users subscribing to a basic news feed. 

WebSockets, MQTT, and SSE are all TCP-based protocols. TCP is designed to be a
reliable transport layer protocol, which provides message delivery and ordering
guarantees. This is great for many realtime use cases. But for other use cases,
a lightweight, speedier protocol is a better option. For example, if your
purpose is to stream video data, you’re better off using UDP as your transport
layer protocol.

Even if WebSocket is a good choice for your needs, depending on the complexity
of your architecture and what you are trying to achieve with your system, you
might want to have the flexibility of using multiple protocols, one for each
specific use case. 

Ably and protocol interoperability

At Ably, we embrace open standards and interoperability, and we believe that you
should have the flexibility to choose the right protocol for the job at any
given moment. That’s why we support WebSockets, SSE, and MQTT, among other
options.

Learn more about the protocols Ably supports

Copy link to clipboard


AUTHENTICATION

Generally, it’s a good idea to only allow authenticated users to use a WebSocket
connection. However, a raw WebSocket request has no header, so you’re unable to
provide authentication in the way you might with an HTTP request. That’s why you
need to use another component or service for authentication. 

A client-side WebSocket library might be an option, but be careful when
selecting one, as not all of them provide authentication mechanisms (or if they
do, they can be quite limited). Alternatively, you can build your own
authentication service. Most of the time, though, you are better off using a
mature, feature-rich solution, such as a realtime messaging platform, that
handles not only authentication, but an entire set of engineering complexities
related to streaming data over WebSockets.

Let’s now look at the most common authentication mechanisms you can use over
WebSockets. The first one, basic authentication, is the simplest option
available (and also the least secure) and it involves the use of API keys. The
credentials are usually passed as a query parameter in a URL, which looks
something like this:

wss://realtime.ably.com/?key=MY_API_KEY&format=json&heartbeats=true&v=1.1&lib=js-web-1.2.1

From a security perspective, it’s recommended to only use basic authentication
server-side, because exposing an API key to multiple clients is highly insecure.
In theory, if you use ephemeral API keys that expire after a given amount of
time on the client-side, you minimize the risk of them being compromised.
However, in practice, a URL containing an ephemeral API key would be broken as
soon as the key expires. In addition, request logging services would capture the
API key in server logs. Therefore, you would have to open a new WebSocket
connection each time the API key is refreshed. This is not a scalable approach.

Token-based authentication is another widely-used authentication mechanism. One
of the most popular methods of token-based authentication is called JSON Web
Token (JWT). It’s an open and flexible format that has become an industry
standard. At a basic level, JWTs work as illustrated in this diagram:



 1. The client sends an authorization request to the authorization server.

 2. The authorization server returns an access token to the client.

 3. The client uses the access token to access a protected resource.

JWT is the recommended strategy on the client-side as it provides more
fine-grained access control than basic authentication and limits the risk of
exposed or compromised credentials. Furthermore, in addition to JWTs being
ephemeral by design, they can also be revoked. 

While JWTs are obviously more reliable and secure than basic authentication,
they come with some engineering challenges that you will have to manage if you
decide to develop your own JWT-based authentication solution:

 * How do you handle token privileges and permissions?

 * How do you set TTL (Time To Live)?

 * How do you renew tokens?

 * How are tokens sent? If it’s via URL, you need a mechanism that allows you to
   renew tokens when they expire, without starting a new WebSocket connection.

See how Ably handles authentication

At Ably, we provide two types of authentication mechanisms: basic auth (API
keys), which we recommend to be used exclusively on the server-side, and
token-based authentication, which supports both Ably tokens and JWTs, and is
ideal for the client-side. We handle all the complexity around renewing tokens
and permission management through our client SDKs. 

Learn more about Ably’s authentication mechanisms

Copy link to clipboard


NETWORK COMPATIBILITY AND FALLBACK TRANSPORTS

Despite widespread platform support, WebSockets suffer from some networking
issues. The main one is proxy traversal. For example, some servers and corporate
firewalls block WebSocket connections.

Ports 80 and 443 are the standard ports for web access and they support
WebSockets. Note that port 80 is used for insecure connections. With that in
mind, it’s recommended to use port 443 for WebSockets whenever possible, because
it’s secure, and prevents proxies from inspecting the connections. If you have
to (or wish to) run WebSockets on different ports, network configuration is
usually needed. 

That said, if you can’t use port 443 and you foresee clients connecting from
within corporate firewalls or otherwise tricky sources, you might need to
support fallback transports such as XHR streaming, XHR polling, or JSONP
polling. That’s why you need to use a client-side WebSocket-based solution that
supports fallbacks. This solution can take various forms; you can opt for an
open-source library designed specifically to provide lots of fallback
capabilities, such as SockJS. 

Alternatively, you can build your own complex fallback capability, but the
scenarios where you actually have to are very rare. Developing a custom solution
is a complex process that takes a lot of time and effort. In most cases, to keep
engineering complexity to a minimum, you are better off using an existing
WebSocket-based solution that provides fallback options.

Ably’s WebSocket-based protocol

Ably’s aim has always been to provide a reliable, scalable, and
highly-performant realtime pub/sub messaging service. Because of our service
aims, we wanted to provide guarantees around message ordering and delivery. The
raw WebSocket transport doesn’t solve this out-of-the-box. That’s why we made
the decision to build our own protocol on top of WebSockets, which also include
fallbacks, among other features and benefits.

Learn more about:

 * the Ably protocol

 * the fallbacks we support via our Javascript browser library



Copy link to clipboard


DEVICE POWER MANAGEMENT AND HEARTBEATS

By its very nature, a WebSocket connection is persistent. Which also means it’s
consuming battery life for as long as it’s active. With WebSockets enjoying
support across various development platforms, programming languages, and
frameworks, including React Native, device power management is something
essential to consider. Unfortunately, it’s not handled by many React Native
WebSocket libraries.

There are several ways you can approach battery management and heartbeats. The
WebSocket protocol natively supports control frames known as Ping and Pong. This
is an application-level heartbeat mechanism that allows you to detect whether a
WebSocket connection is alive. Usually, the server-side sends a Ping frame and,
on receipt, the client-side sends a Pong frame back to the server.

You could theoretically also use protocol-level heartbeats —  TCP keepalives.
However, this is a less than ideal option, as TCP keepalives don’t get past web
proxies. In other words, with TCP keepalives, you can’t always verify a
connection end-to-end. 

Be aware that the more heartbeats you send, the faster battery is depleted. This
can be quite problematic, especially when mobile devices are involved. In these
scenarios, to preserve battery life, you may want to use OS-native push
notifications where possible. With this approach, there’s no need to maintain a
WebSocket connection active, because the server can wake up an inactive instance
of your app whenever you send a push notification. 

While push notifications are a great choice for waking up an app, they are not a
replacement for a WebSocket or streaming protocol layer, because they do not
provide quality of service guarantees. Push notifications are typically
ephemeral, have variable latencies, and aren’t ordered. Furthermore, there is
usually a limited number of push notifications that can be queued up for
delivery at any given moment.

Before deciding whether to use heartbeats, push notifications, or both, you must
carefully analyze your system requirements and use cases. For example, if you’re
developing a chat solution or a multiplayer game, you want to send frequent
heartbeats, even if that means battery life is depleted faster. On the other
hand, if you are developing an online shop and want to infrequently notify
customers about new products, you might want to use push notifications for this
specific purpose. Push notifications will better preserve battery life, even if
it means that your connection status detection will not be as accurate.

Ably, heartbeats and push notifications

At Ably, we believe that you should always have the flexibility to decide
whether you want to use heartbeats, push notifications, or both, depending on
the specifics of your use case(s). That’s why we provide a heartbeat
functionality, as well as native push notifications. 

Learn more about:

 * Ably’s native push notifications

 * Heartbeats and battery usage



Copy link to clipboard


HANDLING RECONNECTIONS WITH CONTINUITY

It’s common for devices to experience changing network conditions. Devices might
switch from a mobile data network to a Wi-Fi network, go through a tunnel, or
perhaps experience intermittent network issues. Abrupt disconnection scenarios
like these require a WebSocket connection to be re-established.

For some realtime use cases, resuming a stream after disruption precisely where
it left off is essential. Think about features like live chat, where missing
messages during disconnection cause confusion and frustration. You need to
ensure that your client-side WebSocket implementation is equipped to handle
complexities around reconnections. The implementation should also provide the
means to resume a stream and offer exactly-once delivery guarantees.

If resuming a stream exactly where it left off after brief disconnections is
important to your use case, you need to implement history / persisted data.
Getting into the detail of this is out of the scope of this article (see this
blog post for more), but these are some things you’ll need to consider:

 * Caching messages in front-end memory. How many messages do you store and for
   how long?

 * Moving data to persistent storage. Do you need to move data to disk? If so,
   how long do you store it for? Where do you store it? And how will clients
   access that data when they reconnect?

 * Resuming a stream. When a client reconnects, how do you know which stream to
   resume and where exactly to resume it from? Do you need to use a connection
   ID to establish where a connection broke off? Who needs to keep track of the
   connection breaking down - the client, or the server?

 * Backoff mechanism. What is your incremental backoff strategy? How do you
   prevent your servers from being overloaded in scenarios where you have a high
   number of clients that keep trying (and failing) to reestablish a connection?

You might even consider whether WebSockets is what you truly need. If your use
case doesn’t require bidirectional messaging, but subscribe-only, then a
protocol like SSE with stream resume baked in might be a better choice. 

See how Ably handles reconnections with continuity

The Ably platform enables clients to resume a stream exactly where it left off.
We’ve developed this resume capability in such a way that it provides an
exactly-once message delivery guarantee, rather than the inferior at-least-once
or at-most-once guarantees. To achieve this, all our client SDKs are equipped to
keep track of the last message that was received by a client. If a disconnection
occurs, when the client is back and the connection is restored, it notifies our
servers of the last message it has received. 

Our resume capability allows clients that experience transient network failures
to reconnect and resume a stream within two minutes. However, messages can still
be retrieved even in the case of long-term disconnections (e.g. a day). For this
purpose, we provide a history API. 

Learn more about:

 * history/persisted data 

 * handling connections with continuity



Copy link to clipboard


FINAL THOUGHTS

Hopefully, this article has shown you what to expect when implementing a
client-side WebSocket-based solution for React Native apps. Raw WebSockets will
rarely be enough, even for simple use cases. If you want to scale your system
and provide optimum experiences for end-users, you will most likely have to use
a feature-rich WebSocket solution.

At Ably, we’ve developed an enterprise-ready pub/sub messaging platform that
makes it easy to efficiently design, quickly ship, and seamlessly scale critical
realtime functionality delivered directly to end-users. We have also developed
our very own WebSocket-based protocol, but we also support raw WebSockets, and
other protocols, like SSE or MQTT. 

Our platform is designed in a manner that enables React Native developers to
offload hard engineering and infrastructure problems to Ably, so they can focus
entirely on building their products. That’s why we offer 25+ client-side SDKs,
React Native included.

If you want to talk more about WebSockets or if you’d like to find out more
about Ably and how we can help you in your React Native and WebSockets journey,
get in touch or sign up for a free account.

We’ve written a lot over the years about realtime messaging and topics such as
WebSockets. Here are some useful links, for further exploration:

 * The WebSocket Handbook: learn about the technology behind the realtime web

 * WebSockets — A Conceptual Deep-Dive

 * Ably blog

 * Ably resources & datasheets

 * Ably's 25+ client library SDKs



On this page
 1. State of play — a brief overview
 2. WebSockets and React Native: what you need to consider
    1. Do you actually need WebSockets?
    2. Authentication
    3. Network compatibility and fallback transports
    4. Device power management and heartbeats
    5. Handling reconnections with continuity
 3. Final thoughts

Build dependable realtime apps

Ably offers versatile, easy-to-use APIs to develop powerful realtime apps.
Guaranteed to deliver at scale.

Start with a free account


RECOMMENDED ARTICLES

16 min read


SIGNALR VS. WEBSOCKET: KEY DIFFERENCES AND WHICH TO USE

We compare SignalR and WebSocket, two popular realtime technologies. Discover
their advantages and disadvantages, use cases, and key differences.

Featured link

14 min read


SIGNALR VS. SOCKET.IO: WHICH ONE IS BEST FOR YOU?

Discover the differences between SignalR and Socket.IO, their pros and cons, and
use cases to see which is right for you.

Featured link
9 min read


WHAT YOU NEED TO KNOW ABOUT WEBSOCKETS AND PUB/SUB

WebSockets and pub/sub are often mentioned in the same sentence so they must be
related in some way. But what is their relationship, exactly?

Featured link


JOIN THE ABLY NEWSLETTER TODAY

1000s of industry pioneers trust Ably for monthly insights on the realtime data
economy.

Enter your email
Submit


How we use cookies to improve your experience.

Accept and close


THE ABLY PLATFORM

Easily power any realtime experience in your application via a simple API that
handles everything realtime.

 * Pub/sub messaging
 * Push notifications
 * Third-party integrations
 * Multiple protocol messaging


ABLY IS FOR

 * Ably Asset Tracking
 * Extend Kafka to the edge
 * EdTech
 * Automotive, Logistics, & Mobility
 * B2B Platforms
 * Healthcare
 * eCommerce & Retail
 * Sports & Media
 * Gaming
 * IoT & Connected Devices


DEVELOPERS

 * Start in 5 minutes
 * Documentation
 * Tutorials
 * Changelog
 * Support & FAQs
 * SDKs
 * System status


WHY ABLY

 * Customers
 * Case Studies
 * Four Pillars of Dependability
 * Compare our tech
 * Multi protocol support
 * Third-party integrations


ABOUT

 * About Ably
 * Pricing
 * Blog
 * Careers
 * Open protocol policy
 * Press & Media
 * Contact us

--------------------------------------------------------------------------------

We're hiring!Learn more at Glassdoor
We're hiring!Learn more at Glassdoor


--------------------------------------------------------------------------------

CookiesLegalsData ProtectionPrivacy

SOC 2 Type 2

Certified

HIPAA

Compliant

EU GDPR

Certified

256-bit AES

Encryption




sprite-discord sprite-facebook sprite-github sprite-glassdoor sprite-google
sprite-icon-display-48hrs sprite-icon-display-about-ably-col
sprite-icon-display-api-keys sprite-icon-display-api
sprite-icon-display-asset-tracking-col sprite-icon-display-browser
sprite-icon-display-calendar sprite-icon-display-call-mobile
sprite-icon-display-careers-col sprite-icon-display-case-studies-col
sprite-icon-display-chat-col sprite-icon-display-chat-stack-col
sprite-icon-display-chat-stack sprite-icon-display-cloud-servers
sprite-icon-display-compare-tech-col sprite-icon-display-customers-col
sprite-icon-display-data-broadcast-col
sprite-icon-display-data-synchronization-col sprite-icon-display-docs-col
sprite-icon-display-documentation sprite-icon-display-events-col
sprite-icon-display-examples-col sprite-icon-display-gdpr
sprite-icon-display-general-comms sprite-icon-display-hipaa
sprite-icon-display-integrations-col sprite-icon-display-it-support-access
sprite-icon-display-it-support-helpdesk
sprite-icon-display-kafka-at-the-edge-col sprite-icon-display-laptop
sprite-icon-display-lightbulb-col sprite-icon-display-live-chat
sprite-icon-display-map-pin sprite-icon-display-message
sprite-icon-display-padlock-closed sprite-icon-display-platform
sprite-icon-display-play sprite-icon-display-privacy-shield-framework
sprite-icon-display-push-notifications-col
sprite-icon-display-quickstart-guides-col sprite-icon-display-resources-col
sprite-icon-display-sdks-col sprite-icon-display-servers
sprite-icon-display-shopping-cart sprite-icon-display-sla
sprite-icon-display-soc2-type2 sprite-icon-display-tech-account-comms
sprite-icon-display-tutorials-demos-col sprite-icon-display-virtual-events-col
sprite-icon-display-virtual-events sprite-icon-gui-ably-badge
sprite-icon-gui-arrow-bidirectional-horizontal
sprite-icon-gui-arrow-bidirectional-vertical sprite-icon-gui-arrow-down
sprite-icon-gui-arrow-left sprite-icon-gui-arrow-right sprite-icon-gui-arrow-up
sprite-icon-gui-burger-menu sprite-icon-gui-check-circled-fill-black
sprite-icon-gui-check-circled-fill sprite-icon-gui-check-circled
sprite-icon-gui-checklist-checked sprite-icon-gui-clock sprite-icon-gui-close
sprite-icon-gui-copy sprite-icon-gui-cross-circled-fill
sprite-icon-gui-cross-circled sprite-icon-gui-dash-circled
sprite-icon-gui-disclosure-arrow sprite-icon-gui-document-generic
sprite-icon-gui-enlarge sprite-icon-gui-external-link
sprite-icon-gui-filter-flow-step-1 sprite-icon-gui-filter-flow-step-2
sprite-icon-gui-filter-flow-step-3 sprite-icon-gui-history sprite-icon-gui-info
sprite-icon-gui-link-arrow sprite-icon-gui-link sprite-icon-gui-live-chat
sprite-icon-gui-minus sprite-icon-gui-plus sprite-icon-gui-quote-marks-solid
sprite-icon-gui-refresh sprite-icon-gui-resources sprite-icon-gui-search
sprite-icon-gui-tick sprite-icon-gui-warning
sprite-icon-live-updates-results-metrics-col sprite-icon-multi-user-spaces-col
sprite-icon-social-x sprite-icon-tech-apachekafka sprite-linkedin sprite-quote
sprite-stackoverflow sprite-twitter sprite-youtube