WebSockets - friend or foe? How to achieve real-time experience in your web application

WebSockets - friend or foe? How to achieve real-time experience in your web application

Łukasz Kucik - June 10, 2019

What are WebSockets and why we use them?

WebSockets enable the server and the client to send messages to each other at any time. The connection is established only once at the beginning, and after that, there is an open channel for sending and receiving data. This is an entirely different pattern than a standard HTTP connection where to get data, the client has to request it, and then a connection is broken soon.

WebSockets use HTTP protocol only to initiate communication channel, then every frame is sent by their own protocol via TCP connection in the transport layer of the OSI model.

Many of us heard a lot about WebSockets and almost always, when we consider any real-time behavior in our application, we tend to choose them. Why? Are they the only one, or are they the best choice when real-time is required? Maybe it is just that the developers out there are not aware of possible alternatives or blindly follow the examples of others from the plethora of available ones on the web. Let’s have a closer look at WebSockets to see some of their drawbacks and think about possible substitutes.

  1. For me, the most significant disadvantage of using web sockets is that it keeps the connection open on the server for the whole duration of the time the user is interacting with the page. It can consume large amount of server resources.
  2. Such a significant number of possible connections sometimes is considered as an advantage, but when we dive into it, we can see there exist other limitations like a database which can be killed by a high number of concurrent connections.
  3. Web sockets also have no reconnect mechanisms. We have to implement our own comprehensive mechanism or use one provided by WebSocket third-party libraries.
  4. From the end of 2011, we have an official standard for WebSockets RFC 6455, and there would be nothing weird about it, but for many years WebSockets were not standardized. They had unstable spec during their journey, and for that reason, many separate libraries with multiple implementations have been created.
  5. Working with load balancers or proxies and WebSockets is a bit complicated. Additional effort is required during configuration. In the past, there were several issues related to transport over the unsecured connection. Frames were often lost. On the other hand, scaling the application with wrongly configured load balancer can cause connection flood. This can be a case even while restarting the server.
  6. It is worth to mention that WebSockets give us only an illusion of reliability. Unfortunately, the Internet connection itself is not reliable. There are many places when the connection is slow, devices often go offline, and in fact, there is still a need to be backed by a reliable messaging system.

The above being said, I do not mean that WebSockets are bad. It is one of the best ways of real-time communication, and it can be used with success to resolve some specific problems (chat, video streaming, etc.), but I have always said that we should seek out the most straightforward solutions.

Alternatives for specific cases

WebSockets provide us communication in full-duplex mode, that means the client can send and receive messages on the same channel. This is an advantage of course, and it improves performance and user experience a lot, but in case of standard real-time applications, we do not need full-duplex communication. Majority of web applications out there are predominantly read applications. Lots of users benefit from live updates, but very few change information. It is incredibly rare to be in a situation where the HTTP header parsing optimization is warranted, and this work is done after sub-millisecond.

When it comes to data delivery from the server to the client, we are limited to two general approaches: client pull or server push. As a simple example with any web application, the client is the web browser. When the website in your browser is asking the server for data, this is called client pull. The reverse, when the server is proactively pushing updates to your website, it is called server push.

Let’s dive into some of the alternatives:

  • Long polling (client pull)
  • Short polling (client pull)
  • Server-Sent Events (server push)
  • Real-time database from Firebase (with WebSockets under the hood)

Short and Long Polling

Both are HTTP requests. When short polling is used, requests are processed as they come on the server. It creates much traffic (uses resources, but frees them as soon as a response is sent back). In comparison to short polling, long polling sends requests to server and client is waiting for the response to come until timeout. So the traffic is smaller, but resources are blocked for some time.

Comparison of short and long polling techniques.

When should we use them? Short polling is rather dead. We should not use it at all, but long polling is used for some scenarios. Long polling’s most significant advantage is the fact that it works in every environment and every browser. It’s harder to starve the server of TCP connections since they are periodically released, but we have to face with re-authentication and re-authorization mechanisms.

Server-Sent Events (HTTP streaming)

HTTP provides a mechanism to push data from the server to clients via Server-Sent Events. In comparison to WebSockets, it is also a great way to achieve real-time experience. SSE is a mechanism that allows the server to asynchronously push the data to the client once the client-server connection is established. The server can then decide to send data whenever a new portion of data is available. It can be considered as a one-way publish-subscribe model.

Server-sent events (SSE) as a server push technology enabling a browser to receive automatic updates from a server.

SSE is an excellent alternative to WebSockets. They are limited to the browser’s connection pool limit of ~6 concurrent HTTP connections per server, but they provide a standard way of pushing data from the server to the clients over HTTP, which load balancers and proxies understand out-of-the-box. It is supported by most web browsers, except IE and Edge, but it is still available there through a polyfill.

Firebase

Firebase started as a Backend-as-a-Service (BaaS) and grew into a next-generation development platform. Firebase contains multiple features, but one of them is a real-time database. When you’re connecting your app with Firebase, you’re not connecting through standard HTTP. You’re indeed connecting through WebSockets under the hood. You do not have to configure all that real-time stuff on your own.

If you start a new project, it is worth to consider using it, but it is also worth to check all of the pros and cons. It is more than perfect for small apps, but it also has some limitations, for example - lack of OR operation on a query.

Let’s dive into the HTTP/2 world

The new HTTP/2 protocol comes with great features in the context of a better experience with communication. It can be used with SSE and with WebSockets as well. The possible way of communication was defined in RFC 8441. HTTP/2 provides us some features and worth to emphasize two of them:

  • Multiplexing - a single TCP connection can be used to make multiple HTTP/2 requests and receive multiple responses (to a single origin). It is a great feature and removes the limitation of SSE, which was 6 connections to the origin. Multiplexing also works between different tabs. Thanks to that, we can have 50 tabs and only one multiplexed connection to the origin, but we have to be careful since the browsers, and also web servers can limit the number of concurrent streams by setting SETTINGS_MAX_CONCURRENT_STREAMS.
Capturing multiple streams in flight within the same connection.
  • HTTP/2 Server Push - sending server responses to the client without receiving requests, i.e., initiated by the server. The server can push additional resources to the client, without the client having to request each one explicitly. It can increase the performance of our app, but when the connection is slow, excess of unnecessary data can degrade our app. It is worth to remember that the browser can turn off push notifications by setting SETTINGS_ENABLE_PUSH.
In addition to the response to the original request, the server can push additional resources to the client.

HTTP/2 is not an alternative, but it has given us a lot of great improvements since it was introduced. Let’s try it using any type of real-time mechanisms.

Conclusion

Once again, all the drawbacks of WebSockets do not have to be drawbacks when you use them with caution and careful implementation. When we create a real-time application, we need to find the simplest and best approach. WebSockets can cause some severe problems when they are misused. Think twice if full-duplex communication is really required. Remember that you can approach most of the use cases by using real-time updates of SSE or even Long Polling. If the only thing you need is to update your website, use SSE (preferably together with HTTP/2). If you honestly need full-duplex communication for chat app or video streaming, use WebSockets, as they can be the best choice for you.

About the author

Łukasz Kucik

Łukasz Kucik

Software Engineer

Linkedin profile Twitter

Łukasz is a Software Engineer with industry experience building large-scale web applications. He provides full-stack solutions but mainly focuses on BE with Java, Kotlin, and Spring.
He believes that working in small Agile teams is the key to significant results, as good communication guarantees success. Łukasz's daily routine includes improving his coding skills by introducing clean code standards and refactoring.

Tempted to work
on something
as creative?

That’s all we do.

join nexocode

This article is a part of

Zero Legacy
36 articles

Zero Legacy

What goes on behind the scenes in our engineering team? How do we solve large-scale technical challenges? How do we ensure our applications run smoothly? How do we perform testing and strive for clean code?

Follow our article series to get insight into our developers' current work and learn from their experience. Expect to see technical details, architecture discussions, reviews on libraries and tools we use, best practices on software quality, and maybe even some fail stories.

check it out

Zero Legacy

Insights from nexocode team just one click away

Sign up for our newsletter and don't miss out on the updates from our team on engineering and teal culture.

Done!

Thanks for joining the newsletter

Check your inbox for the confirmation email & enjoy the read!

This site uses cookies for analytical purposes.

Accept Privacy Policy

In the interests of your safety and to implement the principle of lawful, reliable and transparent processing of your personal data when using our services, we developed this document called the Privacy Policy. This document regulates the processing and protection of Users’ personal data in connection with their use of the Website and has been prepared by Nexocode.

To ensure the protection of Users' personal data, Nexocode applies appropriate organizational and technical solutions to prevent privacy breaches. Nexocode implements measures to ensure security at the level which ensures compliance with applicable Polish and European laws such as:

  1. Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of natural persons with regard to the processing of personal data and on the free movement of such data, and repealing Directive 95/46/EC (General Data Protection Regulation) (published in the Official Journal of the European Union L 119, p 1); Act of 10 May 2018 on personal data protection (published in the Journal of Laws of 2018, item 1000);
  2. Act of 18 July 2002 on providing services by electronic means;
  3. Telecommunications Law of 16 July 2004.

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet.

1. Definitions

  1. User – a person that uses the Website, i.e. a natural person with full legal capacity, a legal person, or an organizational unit which is not a legal person to which specific provisions grant legal capacity.
  2. Nexocode – NEXOCODE sp. z o.o. with its registered office in Kraków, ul. Wadowicka 7, 30-347 Kraków, entered into the Register of Entrepreneurs of the National Court Register kept by the District Court for Kraków-Śródmieście in Kraków, 11th Commercial Department of the National Court Register, under the KRS number: 0000686992, NIP: 6762533324.
  3. Website – website run by Nexocode, at the URL: nexocode.com whose content is available to authorized persons.
  4. Cookies – small files saved by the server on the User's computer, which the server can read when when the website is accessed from the computer.
  5. SSL protocol – a special standard for transmitting data on the Internet which unlike ordinary methods of data transmission encrypts data transmission.
  6. System log – the information that the User's computer transmits to the server which may contain various data (e.g. the user’s IP number), allowing to determine the approximate location where the connection came from.
  7. IP address – individual number which is usually assigned to every computer connected to the Internet. The IP number can be permanently associated with the computer (static) or assigned to a given connection (dynamic).
  8. GDPR – Regulation 2016/679 of the European Parliament and of the Council of 27 April 2016 on the protection of individuals regarding the processing of personal data and onthe free transmission of such data, repealing Directive 95/46 / EC (General Data Protection Regulation).
  9. Personal data – information about an identified or identifiable natural person ("data subject"). An identifiable natural person is a person who can be directly or indirectly identified, in particular on the basis of identifiers such as name, identification number, location data, online identifiers or one or more specific factors determining the physical, physiological, genetic, mental, economic, cultural or social identity of a natural person.
  10. Processing – any operations performed on personal data, such as collecting, recording, storing, developing, modifying, sharing, and deleting, especially when performed in IT systems.

2. Cookies

The Website is secured by the SSL protocol, which provides secure data transmission on the Internet. The Website, in accordance with art. 173 of the Telecommunications Act of 16 July 2004 of the Republic of Poland, uses Cookies, i.e. data, in particular text files, stored on the User's end device.
Cookies are used to:

  1. improve user experience and facilitate navigation on the site;
  2. help to identify returning Users who access the website using the device on which Cookies were saved;
  3. creating statistics which help to understand how the Users use websites, which allows to improve their structure and content;
  4. adjusting the content of the Website pages to specific User’s preferences and optimizing the websites website experience to the each User's individual needs.

Cookies usually contain the name of the website from which they originate, their storage time on the end device and a unique number. On our Website, we use the following types of Cookies:

  • "Session" – cookie files stored on the User's end device until the Uses logs out, leaves the website or turns off the web browser;
  • "Persistent" – cookie files stored on the User's end device for the time specified in the Cookie file parameters or until they are deleted by the User;
  • "Performance" – cookies used specifically for gathering data on how visitors use a website to measure the performance of a website;
  • "Strictly necessary" – essential for browsing the website and using its features, such as accessing secure areas of the site;
  • "Functional" – cookies enabling remembering the settings selected by the User and personalizing the User interface;
  • "First-party" – cookies stored by the Website;
  • "Third-party" – cookies derived from a website other than the Website;
  • "Facebook cookies" – You should read Facebook cookies policy: www.facebook.com
  • "Other Google cookies" – Refer to Google cookie policy: google.com

3. How System Logs work on the Website

User's activity on the Website, including the User’s Personal Data, is recorded in System Logs. The information collected in the Logs is processed primarily for purposes related to the provision of services, i.e. for the purposes of:

  • analytics – to improve the quality of services provided by us as part of the Website and adapt its functionalities to the needs of the Users. The legal basis for processing in this case is the legitimate interest of Nexocode consisting in analyzing Users' activities and their preferences;
  • fraud detection, identification and countering threats to stability and correct operation of the Website.

4. Cookie mechanism on the Website

Our site uses basic cookies that facilitate the use of its resources. Cookies contain useful information and are stored on the User's computer – our server can read them when connecting to this computer again. Most web browsers allow cookies to be stored on the User's end device by default. Each User can change their Cookie settings in the web browser settings menu: Google ChromeOpen the menu (click the three-dot icon in the upper right corner), Settings > Advanced. In the "Privacy and security" section, click the Content Settings button. In the "Cookies and site date" section you can change the following Cookie settings:

  • Deleting cookies,
  • Blocking cookies by default,
  • Default permission for cookies,
  • Saving Cookies and website data by default and clearing them when the browser is closed,
  • Specifying exceptions for Cookies for specific websites or domains

Internet Explorer 6.0 and 7.0
From the browser menu (upper right corner): Tools > Internet Options > Privacy, click the Sites button. Use the slider to set the desired level, confirm the change with the OK button.

Mozilla Firefox
browser menu: Tools > Options > Privacy and security. Activate the “Custom” field. From there, you can check a relevant field to decide whether or not to accept cookies.

Opera
Open the browser’s settings menu: Go to the Advanced section > Site Settings > Cookies and site data. From there, adjust the setting: Allow sites to save and read cookie data

Safari
In the Safari drop-down menu, select Preferences and click the Security icon.From there, select the desired security level in the "Accept cookies" area.

Disabling Cookies in your browser does not deprive you of access to the resources of the Website. Web browsers, by default, allow storing Cookies on the User's end device. Website Users can freely adjust cookie settings. The web browser allows you to delete cookies. It is also possible to automatically block cookies. Detailed information on this subject is provided in the help or documentation of the specific web browser used by the User. The User can decide not to receive Cookies by changing browser settings. However, disabling Cookies necessary for authentication, security or remembering User preferences may impact user experience, or even make the Website unusable.

5. Additional information

External links may be placed on the Website enabling Users to directly reach other website. Also, while using the Website, cookies may also be placed on the User’s device from other entities, in particular from third parties such as Google, in order to enable the use the functionalities of the Website integrated with these third parties. Each of such providers sets out the rules for the use of cookies in their privacy policy, so for security reasons we recommend that you read the privacy policy document before using these pages. We reserve the right to change this privacy policy at any time by publishing an updated version on our Website. After making the change, the privacy policy will be published on the page with a new date. For more information on the conditions of providing services, in particular the rules of using the Website, contracting, as well as the conditions of accessing content and using the Website, please refer to the the Website’s Terms and Conditions.

Nexocode Team

Close

Want to be a part of our engineering team?

Join our teal organization and work on challenging projects.

CHECK OPEN POSITIONS