Real-time data sharing is made possible by Backend-as-a-Service (BaaS) platforms through a variety of techniques, such as WebSockets, the Publish/Subscribe (Pub/Sub) pattern, and managed real-time databases, each of which offers distinct trade-offs in complexity, latency, and scalability.
Key Methods for Real-Time Data with BaaS
WebSockets
WebSockets provide a persistent, full-duplex (bidirectional) communication channel over a single TCP connection between a client and a server.
- How it works: Once the initial HTTP handshake is complete, the connection is kept alive, allowing both client and server to send messages at any time without the overhead of repeated HTTP requests.
- Best for: Use cases requiring low-latency, continuous, two-way communication, such as live chat, collaborative editing, multi-player gaming, and highly frequent dashboard updates.
- BaaS Integration: BaaS platforms like Firebase use WebSockets for data synchronization with clients. Other services like Azure Web PubSub provide specialized WebSocket backend infrastructure.
Pub/Sub (Publish/Subscribe) Pattern
Pub/Sub is an architectural pattern where publishers send messages to named “topics” or “channels,” and subscribers receive only the messages for the topics they are interested in. The system decouples the sender from the receiver.
- How it works: A message broker (e.g., Redis, Google Cloud Pub/Sub, AWS SNS/SQS) manages message distribution. Publishers are unaware of who the subscribers are, which improves system decoupling and scalability.
- Best for: Broadcasting messages to many receivers (fan-out), decoupling microservices, event-driven architectures, and handling high volumes of data streams like IoT data or real-time analytics.
- BaaS Integration: Pub/Sub is often used in combination with WebSockets. The Pub/Sub system handles the server-side distribution of messages across multiple server instances, while WebSockets deliver the messages to the final client.
Other BaaS Real-Time Features
- Real-time Databases: BaaS solutions like Google’s Firebase Realtime Database and Cloud Firestore, and Supabase Realtime offer data synchronization, where any change in the database is automatically pushed to all connected clients in near real-time.
- Server-Sent Events (SSE): SSE allows a server to push one-way updates to a client over a standard HTTP connection. It’s simpler than WebSockets but only supports server-to-client communication, making it ideal for live commentary, stock tickers, or news feeds where only status updates are needed.
- Push Notifications: Services like Firebase Cloud Messaging (FCM) allow sending one-way native push notifications to mobile devices or web browsers, notifying users of events even when the app is not actively in the foreground.
Choosing the Right Approach
| Scenario | Recommended Technology | Why? |
|---|---|---|
| Live Chat/Messaging | WebSockets (often with Pub/Sub backend) | Requires low-latency, bidirectional, continuous communication. |
| Live Dashboards/Metrics | WebSockets or SSE (with Pub/Sub backend) | Requires frequent server-pushed updates to many clients. |
| Event-Driven Microservices | Pub/Sub | Decouples services, handles large message volumes, and orchestrates downstream jobs. |
| Collaborative Editing | WebSockets (with Pub/Sub for clustering) | Needs immediate, synchronized updates across multiple user interfaces. |
When choosing a real-time strategy, developers must consider scalability, latency requirements, security, and operational complexity. Dedicated real-time platforms (PaaS) like Ably can also be used to offload the complexity of managing global-scale real-time infrastructure.
The web of today is by default real-time. This implies that end users anticipate receiving data without any discernible delay. Whether it’s for chat messages, sports scores, or social network updates, achieving that need for specialized engineering knowledge, a substantial initial investment, and continuous upkeep of an advanced worldwide network of systems.
Building a real-time platform internally can divert attention from other engineering objectives and result in expensive errors, even when working with tried-and-true technologies like WebSocket. Indeed, according to our research, 65% of engineering leaders said that during the past 12 to 18 months, their in-house real-time solutions had substantial downtime.
What is Pub/Sub?
A design pattern called publish-subscribe, or Pub/Sub, allows publishers and subscribers to exchange messages via a message broker. Publishers send messages to the broker with a topic under this arrangement. Through the broker, subscribers can then subscribe to the subjects that interest them once more.
For example, in a crypto stock ticker-type app, the publisher might periodically publish a message with the topic btc-price, and another with the topic eth-price.
Subscribers can subscribe to one topic, or both (or none!), depending on which they’re interested in (if any) and will receive all messages published to the topics to which they subscribe. In any case, neither the subscriber or publisher are aware the other exists – everything goes through the broker.
To further illustrate the point, suppose for a moment you’re building a community chat application to rival Discord.
To facilitate one-on-one messaging, both participants would publish and subscribe to a topic with a unique name, possibly derived from their combined usernames – for example, userA-userB.
When it comes to channels, anyone participating in in the #welcome channel, for example, would chatter by publishing and subscribing to the welcome-channel topic under the hood.
As you can see, by publishing messages to named logical channels, it becomes clear from a high level how to send messages to a specific user (unicast), group of users (multicast), or every user (broadcast).
Remember, though, Pub/Sub is a pattern – an abstract solution to a commonly occurring problem, a blueprint, nothing specific! When you repeat the pattern, all the details like what transport to use are up to you.
What is the Difference Between WebSockets and Pub/Sub?
If you started this post wondering about WebSockets vs. Pub/Sub, it turns out they’re not at odds at all. Rather, they actually complement each other well, hence it’s common to see them mentioned together (even though they are different).
So, what are the differences?
In summary, WebSockets are fundamentally a transport to get data from A to B (ordinarily, two web browsers but WebSockets can work on mobile too).
On the other hand, Pub/Sub is a design pattern that describes a tried-and-true code pattern you can repeat in your messaging layer so that messages can reach their destination without the risk of you introducing tight coupling or other code smells into your codebase.
By following a pattern, you can work more quickly while ensuring your messaging code is plenty flexible to support your evolving requirements.
You can use WebSockets without Pub/Sub or with another design pattern. Similarly, Pub/Sub is frequently used without WebSockets. They’re not intrinsically linked in any way – they just go well together.
Working with a real-time Platform as a Service (PaaS) provider, such Ably or PubNub, is one option. Which option, nevertheless, is best for your application? Here, we examine the advantages and disadvantages of WebSocket and PubNub as well as some factors to take into account when making your decision.
What is PubNub?
The Publish/Subscribe design pattern is the foundation of PubNub, a real-time PaaS. Engineering teams can quickly develop real-time features like chat, multiplayer collaboration, and real-time dashboards using it. PubNub’s global network, which it claims provides low latency, high dependability, and scalability regardless of end users’ locations, is essential for data distribution.
In addition to the Pub/Sub concept, PubNub provides capabilities like message content transformation, authentication, user presence management, and more that are intended to suit certain use cases.
Key features of PubNub
- Pub/Sub messaging: As a developer working with PubNub, you set up channels that client-side applications subscribe to. That could be one-to-one (such as a private chat between two individuals) or one-to-many (such as broadcasting financial data to subscribers). Messages can be text or binary files up to 5 MB.
- User presence: Track and distribute presence status for connected clients. That’s useful for chat applications, multiplayer games, and pretty much any collaborative realtime environment..
- Push notifications: Alert end users through native iOS and Android push notifications.
- Serverless functions: Transform, filter, and reroute data as it passes through the PubNub platform.
- Event triggers: Send messages to third-party systems for further processing, based on pre-defined criteria.
- Message history and persistence: Store messages for later delivery when a subscriber is unavailable.
- Authentication and encryption: Ensure data is available only to the right subscribers.
Advantages of PubNub
- Fully managed global infrastructure: PubNub operates 15 locations across the globe, which should reduce latency for clients further away from your primary cloud regions.
- Strong uptime: PubNub boasts 99.999% uptime for its realtime PaaS.
- Security and compliance: The platform complies with standards such as SOC2, HIPAA, and ISO 27001.
- Faster time to market than self-build: Working with a realtime PaaS is more cost effective and reliable than building an in-house solution.
Disadvantages of PubNub
- Quality of service is limited: PubNub doesn’t guarantee message delivery, ordering, or predictable results (idempotency). To get those results, you’ll need to build additional application logic.
- Performance is below the industry best: PubNub is built on older technology (long polling) that suffers from higher latencies than alternatives such as WebSocket. PubNub promises latencies below 100ms only for their paid plans- for free plans, they aim for 250ms, which is likely to be noticeable by end users.
- Inefficient message delivery: PubNub doesn’t use delta compression. That means that when it transmits a message stream, it sends the entire payload each time rather than only the differences since the last transmission. That can quickly escalate and it reduces PubNub’s ability to deliver at low latencies.
- Poor recovery from errors: PubNub’s message can handle only 100 messages by default. That means that when the system can’t reach a client, anything over 100 messages will be dropped.
What is WebSocket?
WebSocket serves as both an API and a protocol for client-server communication. Therefore, WebSocket is not a real-time PaaS, which is the primary distinction from PubNub. Rather, it provides the means, but not the infrastructure, to create event-driven, low latency data streaming for your real-time applications.
Read Also: How BaaS Handles Authentication and User Management
But there are also technical distinctions. To transfer messages between its platform and end clients, PubNub uses HTTP long polling, which may be viewed as a technological hack. WebSocket was created from the ground up to provide a dedicated method for enabling real-time communication in place of workarounds like lengthy polling. WebSocket and PubNub have comparable use cases despite their technological differences. Chat, data broadcast, and multiplayer cooperation are a few examples.
Key features of WebSocket
- Bidirectional communication: WebSocket is designed for two-way communication between client and server, which makes it more useful for realtime collaboration use cases than alternatives such as Server-Sent Events.
- Persistent connections: Some protocols need to open a new connection for each message or every few minutes, when the previous connection times out. WebSocket keeps connections open for as long as they’re needed, which reduces overhead and latency. Combined with bidirectional communication, that enables especially time-sensitive applications such as gaming and multiplayer collaborative document editing.
- Both a protocol and an API: WebSocket both defines how messages move between client and server and provides a common API that is implemented in browsers, mobile platforms, and elsewhere.
- Efficient data transfer: Older HTTP-based solutions, such as long polling, rely on repeatedly opening HTTP connections with all the overhead that involves. As WebSocket works with persistent connections, it requires less bandwidth, involves less latency, and puts lower load on the machines at either end.
- Available almost everywhere: As a mature protocol, WebSocket is available in all major browsers, mobile platforms, and in libraries for just about every programming language.
- Application flexibility: WebSocket is concerned only with delivering messages between two points. It doesn’t impose any particular application or use case constraints.
- Not ideal for audio and video: WebSocket works best with text and smaller snippets of binary data. It isn’t optimized for streaming audio and video. This is also true of PubNub, which recommends using a third-party hosted service to stream video and audio.
- Connections don’t recover automatically: If there’s a break in a WebSocket connection, there needs to be additional code somewhere in the infrastructure to take care of reestablishing that connection and resending any messages that were missed during the downtime.
- Connections are stateful: One consequence of persistent connections is that those connections are stateful, meaning that it’s harder to scale WebSocket out across a cluster of servers.
What is the Difference Between PubNub and WebSocket?
WebSocket is a popular option for teams developing real-time platforms due to its extensive support, effectiveness, and dependability. One possible drawback of PubNub is that it does not support WebSocket, despite the fact that it is a real-time PaaS. Rather, it uses an older workaround known as HTTP Long Polling.
PubNub is a PaaS that engineering teams use to outsource the real-time components of the products they create, which is the primary distinction between it and WebSocket. Conversely, WebSocket is a protocol that offers a standard for client-server communication that necessitates either in-house engineering or an alternative real-time PaaS.
Let’s examine the differences between the two.
Build vs buy
As a hosted service, PubNub provides the infrastructure to deliver realtime messages on your behalf. That can save time and money both up-front and when it comes to maintaining the solution. However, that also means you’ll need to be happy with the functionality PubNub offers and continue to pay their fees for the life of your application.
Because WebSocket is only a protocol, it requires that you build and tend to your own solution. That includes architecting, deploying, and maintaining the infrastructure necessary to keep that solution in production. That offers you flexibility on paper but, in practice, you’ll need a long-term plan and a budget for both headcount and infrastructure costs.
PubNub’s reliance on long polling puts it at a disadvantage compared to WebSocket. That’s mostly due to the inefficiencies that come about thanks to how long polling works. Rather than being a dedicated realtime protocol, long polling stretches HTTP beyond its original design.
Usually, HTTP opens a connection, receives some data (such as HTML), and then closes the connection. Long polling opens a connection on the off-chance that there is some data ready for it to receive. It then waits until there is data or, otherwise, the connection times out. As a result of repeatedly opening new HTTP connections, long polling has greater overhead than WebSocket. The practical result is that PubNub suffers from higher latency than solutions built using WebSocket .
A real-time communication protocol is called WebSocket. This means that WebSocket does very little more than establish and maintain the connection and then send messages. That’s all well and good, but it does require your engineering staff to develop additional components of your system. That could be at the upper level, like typing indicators in a chat app, or at the lower level, like the logic to reconnect following an interruption.
PubNub provides a more comprehensive solution, much like other real-time PaaS providers. PubNub provides you with related features in addition to sending messages with comparatively low latency. For instance, user presence, message persistence, mobile push notifications, and serverless functions. It would take custom engineering work to create comparable features using WebSocket.
PubNub or WebSocket?
It can be challenging to decide between WebSocket and PubNub. Every solution functions at a different level, as we’ve seen. While PubNub seeks to provide you with a more comprehensive solution, WebSocket is one technology that you’ll utilize in conjunction with others.
Let’s examine an example situation to see what this actually means. Assume you wish to incorporate chat features into an already-existing program. What are the real-world effects of using WebSocket or PubNub for that?
Time to market
How fast you can deliver functionality to end users impacts how quickly your business can see a return on its investment.
- WebSocket: Choosing WebSocket can mean choosing to build your own solution. That has a big effect on time to market because you’ll need to design, build, and test your custom solution, as well as ensuring you have access to the right cloud infrastructure. Alongside WebSocket, you’ll need to find other tooling to support message persistence, mobile push notifications, and similar functionality expected by chat users. All of that changes if you work with a realtime PaaS that supports WebSocket, such as Ably.
- PubNub: By providing you with the tooling and infrastructure for realtime messaging, PubNub can help you deploy a solution much faster than standalone WebSocket. And PubNub’s additional functionality, such as user presence tracking, saves you time you’d otherwise have to devote to creating that from scratch.
Software rarely stands still. Whether it’s responding to vulnerabilities or meeting new user demands, you’ll need to allocate engineering time and budget to keeping your chat functionality running. How does that differ between PubNub and WebSocket?
- WebSocket: Building your own realtime solution with WebSocket at its heart means that your engineering team will be responsible for all ongoing maintenance. And that’s not just a software engineering problem but also a DevOps issue to take care of the global infrastructure required to deliver low latency chat experiences.
- PubNub: As a PaaS, PubNub maintains both the software and the infrastructure side of the realtime solution. The benefit there is that you don’t need specialist realtime expertise on your engineering team.
For your chat service to feel responsive, you need to minimize latency within all parts of your system. Writing efficient code on your client-side will help but the greatest scope for variation is in the infrastructure delivering messages between your chat users and your application backend. While PubNub boasts a global network, which should reduce the time it takes for messages to travel between their network and your chat users, it’s hard to compare that with whatever you might build instead with WebSocket. So, let’s look at the protocols involved to make a fair comparison.
- WebSocket: As we saw earlier, WebSocket has been designed from the ground up to support realtime communication. That allows it to be much more efficient than older approaches, such as the HTTP long polling used by PubNub. While infrastructure might vary, the protocol overhead introduced by WebSocket is minimal and so your chat users will enjoy a more responsive experience.
- PubNub: Relying on HTTP long polling means that, no matter how extensive PubNub’s global network might be, there will always be an unnecessary overhead in setting up multiple HTTP connections in the hope that there might be a message waiting. This could result in a noticeably laggy experience for chat users.
Whatever other promises they make, one of the most important considerations when comparing the technologies you’ll use in a realtime system is how well you can rely on them. What happens when there’s a failure, for example? Can PubNub and WebSocket handle less than ideal network conditions?
- Recovery from failure: WebSocket doesn’t recover automatically when a connection fails. Instead, you need to create your own application logic to recover connections. PubNub, however, does recover dropped connections but can store only a limited number of messages during a failure.
- Quality of service: Ensuring messages arrive in the right order and the right number of times is vital for your application. PubNub’s own marketing materials say that it is “not a guaranteed message delivery service”. WebSocket also doesn’t offer a message delivery guarantee but Ably, for example, does add message delivery guarantees on top of WebSocket.
- Geographic distribution: PubNub runs a global network, which means that theoretically a network issue in one location shouldn’t impact other parts of the network. For WebSocket, it all comes down to your implementation or that of the WebSocket-compatible realtime PaaS you use, such as our own here at Ably.
In each of these factors, both PubNub and WebSocket have their pros and cons. However, when evaluating your options for realtime infrastructure, it’s worth looking at more than just two solutions.











Comments