- Topics
- /
- Realtime technologies
- /
- Firebase vs WebSocket: Differences and how they work together
Firebase vs WebSocket: Differences and how they work together
This article is a comparison between Firebase and WebSocket, two of the most commonly used technologies for building realtime features such as chat and live multiplayer gaming. We’ll cover the following points:
What is WebSocket?
WebSocket is a realtime protocol that provides a persistent, bi directional communication channel between a web client (e.g., a browser) and a web server over a single TCP connection.
The standardized WebSocket API, which is supported by the vast majority of browsers, extends the WebSocket protocol to web clients. The WebSocket API allows you to perform actions like creating the WebSocket object, managing the WebSocket connection, sending and receiving messages, and listening for events triggered by the WebSocket server.
For more information on WebSockets and how the protocol works, you can read our piece The WebSocket API and protocol explained.
Key characteristics of WebSocket
Two-way Communication: WebSocket connections are full duplex, enabling messages to be sent and received simultaneously without blocking each other.
Persistent Connections: WebSocket maintains an open connection as long as needed or until disrupted by network issues, changing the approach to message handling.
Widespread Support: As a web standard, WebSocket is supported across major web browsers, backend languages, and IoT devices.
Discrete Message Delivery: WebSocket deals with self-contained messages, ensuring either full delivery or none, contrasting with streaming protocols like WebRTC.
Advantages of WebSocket
Low Latency: WebSocket minimizes latency by using a single connection, reducing the overhead associated with repeated HTTP connections. The protocol’s small headers (as small as 2 bytes) further reduce latency.
Implementation Flexibility: Because WebSocket is a protocol rather than a library, it imposes few restrictions on how you build your application. Different parts of your application could be written in different languages, as long as they use compliant WebSocket libraries.
Supports Different Message Formats: WebSocket’s flexibility in encoding messages allows for optimization based on application needs, whether using compact binary formats or human-readable JSON.
Disadvantages of WebSocket
It’s just a protocol: WebSocket is a standard, not an implementation. That means you’ll need to choose a library, like ws, Python’s websockets, or a richer messaging library like Socket.IO, to build with. If you choose a pure WebSocket implementation, you’ll need to implement functionality such as connection monitoring and messaging guarantees that aren’t covered by the WebSocket specification.
You have to manage your own infrastructure: One of the biggest challenges in implementing realtime communication using WebSocket is building out and maintaining the infrastructure to ensure your users experience minimal latency, high uptime, and consistent message delivery.
No automatic reconnections: WebSocket itself doesn’t monitor connection status nor does it automatically reconnect when something goes wrong. That’s logic you’d have to write yourself, if you choose a pure WebSocket implementation.
Blocked connections: Even though WebSockets generally benefit from widespread support, certain environments (such as corporate networks with proxy servers) will block WebSocket connections.
Limited message guarantees: WebSocket’s data integrity guarantees are quite weak. It doesn’t guarantee message delivery or that a message will be delivered exactly once. This is something you’d need to build yourself.
Scaling can be hard: As a stateful protocol, horizontally scaling WebSocket to multiple servers can be complex. You’ll need additional logic, and potentially a single point of failure in the form of a database, to enable sticky sessions between individual servers and clients.
What is Firebase?
Firebase is a Backend as a Service (BaaS) platform that helps you build, test, release, and monitor web and mobile apps for end-users. While it initially started as a realtime database, Firebase now provides a host of services and features. Here’s a non-exhaustive list:
Realtime database. At its core, Firebase is a cloud service that allows you to store data related to your application and service. Firebase offers two different non-relational database options: the Firebase Realtime Database, and Cloud Firestore, the newer database for mobile app development, providing a more intuitive data model and enhanced capabilities for querying data.
Cloud and in-app messaging. Both Firebase Realtime Database and Cloud Firestore can push realtime updates to client devices following any changes to the database. There’s also Firebase Cloud Messaging, a service that allows you to send native push notifications and notification messages across platforms (iOS, Android, web).
Hosting. Firebase provides secure hosting on Google Cloud.
Integrations. Given that Firebase is powered by Google, this naturally extends its functionality via integrations with services such as Google Pub/Sub, Google Cloud Functions, and Google Analytics.
App analytics. Firebase comes with a nice dashboard for visualizing your app’s activity, so you can make critical business decisions based on this data.
Firebase advantages
Firebase helps app developers move quickly: you don’t have to worry about hosting, provisioning, and managing backend processes and components like databases, data storage, and authentication. Firebase’s collection of services makes the entire development cycle shorter and more straightforward.
Firebase has good technical documentation, and detailed SDK and API reference, making it easy to get started and use the platform. Going beyond docs, there are about 1.5 million apps built with Firebase, so there’s a pretty big community of experts who can help you with questions and issues.
Most of the Firebase services are free to start with, which is great if you are new to Firebase and simply want to test the platform, assessing if it’s the right choice for your project.
Firebase disadvantages
An instance of the Firebase Realtime Database has a limit of 200.000 concurrent connections and 1.000 write operations per second. To scale beyond these limits, you have to use sharding, which is a notoriously difficult process.
Vendor lock-in is an issue when you use Firebase. For example, if one day you conclude that the Realtime Database / Cloud Firestore is unsuitable for your use case, it’s hard to migrate to another (NoSQL) database. This is because of the way data is stored: Firebase Realtime Database uses a JSON tree structure, while Cloud Firestore uses collections of documents, similar to JSON.
There are plenty of horror stories of costs escalating out of control, especially if you are new to Firebase, and don’t yet have a good grasp on the pricing mode and how to engineer your apps in a cost-effective manner. See How not to get a $30k bill from Firebase for details, or read more about the challenges of scaling Firebase.
Firebase and WebSocket realtime use cases
We’ll now briefly cover the kind of realtime features you can build with WebSocket and Firebase.
WebSocket use cases
We can broadly group WebSocket use cases into two distinct categories:
Realtime updates, where the communication is unidirectional, and the server is streaming low-latency (and often frequent) updates to the client. Think of live score updates, GPS location tracking, live dashboards, or realtime alerts and notifications, to name just a few use cases.
Bidirectional communication, where both the client and the server send and receive messages. Examples include chat, multiplayer gaming, virtual events, and virtual classrooms (the last two usually involve features like live polls, quizzes, and Q&As). WebSockets can also be used to underpin multi-user synchronized collaborative applications - think of Figma.
Firebase realtime use cases
Firebase databases
Both the Firebase Realtime Database and Cloud Firestore can push updates in realtime to connected clients every time data changes. This is especially useful for use cases like chat and live multiplayer games.
Firebase Cloud Messaging
In addition to the two databases, there’s Firebase Cloud Messaging (FCM), a cross-platform messaging solution that enables you to send realtime messages and notifications across platforms (Web, iOS, Android, C++, Flutter, and Unity).
Firebase vs WebSocket: Why a direct comparison doesn’t work
As mentioned earlier in the article, Firebase is primarily a realtime database solution, while WebSocket is a standalone protocol meant to facilitate persistent bi-directional communication. Firebase Cloud Messaging, when used, can push notifications to users without an open connection to the server; FCM relies on a store-and-forward mechanism which then delivers the notifications to the user, useful when an app is closed. This does not replace WebSockets, which are still required for maintaining a constant open connection.
In short, Firebase is the database; FCM is for push notifications; and WebSocket is for instant realtime communication. In fact, Firebase already uses WebSockets for data synchronization with clients.
For this reason, it makes sense to consider Firebase and WebSocket technologies that work alongside each other, rather than in competition with one another.
Firebase realtime databases limitations
Firebase provides two different NoSQL databases: the Firebase Realtime Database, and the more recent Cloud Firestore. Data stored can be synchronized across all clients in realtime, with low latencies - every time there is a change in the DB, connected devices will receive an update. These databases use WebSockets for data synchronization.
There are several limitations to the way Firebase databases use WebSockets. First of all, the database is the central concept, with realtime synchronization (messaging) as an add-on feature. Only the updates to your database are published to connected clients. This forces you to permanently store even the transient events that need to be streamed to your users, leading to an unnecessary increase in storage costs. An example of transient messages in a chat app scenario would be indicators that others are typing – events that occur frequently but have zero need for permanent storage.
Another downside of this tight coupling of database + realtime messaging is that it leaves no room for flexibility. For example, you can’t use Firebase to push updates to client devices from a non-Firebase database. One could argue that coupling a realtime messaging service and a core database is peculiar, because the two vary in semantics and levels of scalability.
Speaking of scalability, you can scale the Firebase databases up to a point. We’ve previously mentioned that an instance of the Firebase Realtime Database has a limit of 200.000 concurrent WebSocket connections. You can scale beyond this limit by sharding your data across multiple instances. However, it’s worth bearing in mind that sharding can become a significant challenge that leads to increased complexity and management overhead.
Rather than having to deal with sharding, you’re probably better off using Cloud Firestore, which auto-scales up to a more generous limit: roughly 1 million concurrent connections. However, if you need to scale beyond 1 million users, Cloud Firestore can’t help you. In addition, unlike the Realtime Database, Cloud Firestore does not support presence natively, which is a key feature for use cases like chat apps.
Decoupling the Firebase realtime database from messaging over WebSockets
In the previous section, we’ve seen the downside of using the Firebase databases for synchronizing updates to client devices. With that in mind, it might be worth exploring specialized solutions for last-mile, WebSocket-based realtime messaging that you can connect to your Firebase backend, as opposed to using Firebase native capabilities for synchronizing data to client devices.
With a realtime messaging solution between Firebase and client devices, you can stream transient messages directly to clients, and only send messages that require permanent storage to the DB. This helps reduce the load on the database and prevents increased costs for storing data that you don’t want to store to begin with.
Ably: managed, resilient, scalable realtime infrastructure
Ably provides realtime experience infrastructure to power multiplayer, chat, data synchronization, and notifications at internet scale. Our globally-distributed network and hosted APIs (WebSocket-based) help developers engineer realtime features for millions of users. Ably often acts as a last-mile middleware for synchronization between client devices and various backend solutions, including Firebase, ensuring seamless integration and efficient realtime communication.
Ably’s realtime PaaS gives you:
A global edge network: Deliver low latency to your users wherever they are in the world.
WebSocket and more: Ably chooses the appropriate protocol, such as WebSocket, Server Sent Events, and MQTT, depending on network conditions and application needs.
<50 ms latency: Our expert realtime DevOps engineers manage our global network to ensure low latency right across our network.
Resilient delivery: Ably guarantees that messages arrive in order and on time.
99.999% uptime: Ably’s network routes around failure to ensure your application keeps on delivering.
Elastic scaling: As demand grows, Ably scales from thousands to billions of messages.
Works in your language: With SDKs for more than 25 languages and frameworks, integrations with common tooling, and industry leading documentation, Ably’s developer experience gives you the tools to become productive quickly.
Discover how Ably empowers developers like you to integrate global, scalable, and efficient realtime experiences in your apps with a free account.
Recommended Articles
PubNub vs. Firebase: feature comparison, use cases, pros and cons
Head-to-head comparison between PubNub and Firebase, two event-driven technologies for building realtime features like chat and collaborative apps.
SignalR vs. Firebase: Learn about their differences, similarities, and use cases
We compare Firebase and SignalR, two popular realtime technologies. Discover their advantages and disadvantages, and compare their features.