API and API Design: How WebSockets Works

Let’s deep dive into WebSockets today and learn the intricacies of Websockets, including a simple program that shows how to implement Websockets into our projects for real-time application.

In partnership with

Hello “👋

Welcome to another week, another opportunity to become a Great Backend Engineer.

Today’s issue is brought to you by Masteringbackend → A great resource for backend engineers. We offer next-level backend engineering training and exclusive resources.

Before we get started, I have a few announcements:

I have a special gift for you: You will love this one.

The ultimate Land Your Dream Job Challenge is here.

We are launching the ultimate guide to land your dream job in any programming language you choose. We are starting with the Python Programming language.

Land your dream Python Job in 90 days by shipping 30 Python projects in 30 days by completing our daily tasks.

It’s a cohort-based and project-focused challenge where you will be challenged to build 30 Python projects in 30 days.

Here are what you will get:

  • Ship 30+ Python backend projects in 30 days.

  • Instant Access to all 30+ videos

  • Access to data structure and algorithm interview kits.

  • Access our Complete Backend Job Preparation kits (Resume, Cover letter reviews, mock interviews, and job placements).

  • Join & learn from a thriving community of helpful students & alumni from top companies.

Limited Access. First 400 students at $54 others at $100 (We have only 113 slots left.)

Reply “Challenge” and I will send you a link to reserve your spot.

Check out our sponsor for this episode:

Start learning AI in 2025

Everyone talks about AI, but no one has the time to learn it. So, we found the easiest way to learn AI in as little time as possible: The Rundown AI.

It's a free AI newsletter that keeps you up-to-date on the latest AI news, and teaches you how to apply it in just 5 minutes a day.

Plus, complete the quiz after signing up and they’ll recommend the best AI tools, guides, and courses – tailored to your needs.

In the last newsletter issue, we discussed Real-time APIs and explained everything you need to know about them. Most importantly, we identified two important types of Real-time APIs: WebSockets and Server-Sent Events (SSE).

Let’s deep dive into WebSockets today and learn the intricacies of Websockets, including a simple program that shows how to implement Websockets into our projects for real-time application.

Overview of Websockets

Web Sockets provide a long-lived connection between a client and a server over which messages can be transmitted bi-directionally in real time.

Websockets are very popular because messages can be sent bidirectionally, which means both the server and the client can send and receive messages in real-time.

WebSockets play a pivotal role in building real-time APIs by providing a faster and more efficient communication channel than traditional HTTP.

They are widely adopted in scenarios that demand instantaneous data transfer—such as chat applications, live sports updates, and real-time analytics—because they enable seamless, bidirectional communication.

This shift from conventional HTTP-based API design to a WebSocket-driven approach creates more responsive, dynamic, and efficient APIs capable of handling real-time data.

What Are WebSockets?

WebSockets are a communication protocol designed to support full-duplex (two-way) communication between client and server over a single, long-lived connection.

Introduced as part of the HTML5 specification, they address the limitations of traditional HTTP by allowing servers to push data to clients without waiting for a client request.

A simple design right? but very powerful when you think of the numerous complex real-time applications that have been built with it.

Let’s take a look at some of the key advantages of Websockets:

Key Advantages of WebSockets

  1. Real-time, Two-Way Communication: Data can travel in both directions (client-to-server and server-to-client) simultaneously, making it ideal for real-time applications.

  2. Reduced Latency: Once the connection is established, messages flow with minimal overhead, leading to faster data exchange.

  3. Efficient Use of Resources: WebSockets eliminates the need for repetitive HTTP handshakes and polling, lowering network usage and server load.

  4. Lightweight Messaging: Messages are often sent in simple text or binary format, adding minimal overhead compared to multiple HTTP requests.

Next, let’s look at how WebSockets differ from traditional HTTP, this will help you understand how WebSockets are designed around HTTP protocol.

How WebSockets Differ from HTTP

  • Connection Lifecycle: HTTP is request-response based, meaning the client initiates every communication. In contrast, a WebSocket connection remains open, allowing the server to push updates at any time.

  • Protocol Upgrade: WebSockets start as an HTTP handshake, then upgrade the connection via the Upgrade header, switching to the WebSocket protocol ws or wss for secure connections).

  • Message Handling: Instead of sending headers with every request and response as in HTTP, WebSockets exchange lightweight packets (frames), which are efficient for real-time use cases.

Here we highlighted three important concepts which are the Connection Lifecycle which indicates that the connection for a WebSocket remains open for further updates when the traditional HTTP closes and new connections are initiated every time.

Establishing a WebSocket Connection

  1. Initial HTTP Handshake: The client sends an HTTP request with a Upgrade: websocket header. The server responds with 101 Switching Protocols if it supports WebSockets.

  2. Upgrading to WebSocket Protocol: After the server accepts, the connection switches from HTTP to the WebSocket protocol. Both ends maintain this upgraded connection until it’s closed by either party.

  3. Bi-directional Messaging: With the connection established, the client and server can send messages to each other at any time. There’s no need for further handshakes until the connection is terminated.

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('New client connected');

  // Listen for incoming messages
  ws.on('message', (message) => {
    console.log(`Received: ${message}`);
    // Broadcast message to all clients
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  // Handle connection close
  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

Use Cases for WebSockets

  1. Chat Applications: Messaging apps like Slack or WhatsApp rely on immediate data flow, allowing users to receive new messages the moment they’re sent.

  2. Live Sports Updates: Sports fans want to track scores in near real-time. WebSockets push these updates instantly, enhancing the viewing experience.

  3. Financial Trading and Analytics: Stock price fluctuations are time-sensitive. WebSockets provide traders with instantaneous updates, which can be crucial for decision-making.

  4. Online Multiplayer Games: Player actions and game states must be synchronized in real-time. WebSockets handle these rapid-fire events efficiently.

Designing Real-time APIs with WebSockets

Modern applications increasingly adopt WebSockets as a foundation for real-time APIs. This shift from conventional HTTP-based API design to WebSocket-driven architecture helps create APIs that are:

  • More Responsive: The server can immediately notify clients of new events.

  • Dynamic: Both sides can actively send data, fostering interactive experiences.

  • Efficient: Once established, the connection avoids the overhead of repeated HTTP requests, reducing latency and bandwidth usage.

Because of these advantages, WebSockets have become indispensable for any application that demands seamless, bi-directional communication.

Best Practices

  1. Authentication: Ensure proper authentication before establishing a WebSocket connection. Tokens or cookies are commonly used to verify user identity during the initial handshake.

  2. Error Handling: Handle connection errors gracefully, and implement reconnection logic on the client side for scenarios like network interruptions.

  3. Scalability: As the number of concurrent connections grows, you’ll need strategies like load balancing and sticky sessions to direct users to the same server instance that maintains their WebSocket connection.

  4. Security: Use secure WebSockets (wss://) in production. Always validate incoming data to protect against malicious payloads.

  5. Monitoring and Logging: Track metrics like connection count, message throughput, and latency to detect performance issues or bottlenecks in real-time.

WebSockets are at the heart of real-time APIs, offering a faster and more efficient communication channel than traditional HTTP.

By maintaining a continuous, bi-directional connection, they excel in scenarios demanding instantaneous data transfer—such as chat applications, live sports updates, and real-time analytics.

This paradigm shift to a WebSocket-based design helps developers build APIs that are both responsive and capable of handling the high demands of today’s data-driven world.

If you’re building an application where timing and user engagement are paramount, WebSockets may just be the solution you’ve been looking for—empowering you to deliver dynamic, event-driven experiences that feel instantaneous, no matter how many users are online.

Did you learn any new things from this newsletter this week? Please reply to this email and let me know. Feedback like this encourages me to keep going.

See you on Next Week.

Remember to start learning backend engineering from our courses:

Get a 50% discount on any of these courses. Reach out to me (Reply to this mail)

Top 5 Remote Backend Jobs this week

Here are the top 5 Backend Jobs you can apply to now.

👨‍💻 BlueCat
✍️ Backend Engineer
📍Remote, Serbia
💰 Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 Constructor
✍️ Backend Engineer: Experiments Team (Remote)
📍Remote, Worldwide
💰 Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 Homepage
✍️ Backend Developer PHP
📍Remote, Worldwide
💰 Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 Monzo
✍️ Backend Engineer
📍Remote
💰 Click on Apply for salary details
Click here to Apply for this role.

Want more Remote Backend Jobs? Visit GetBackendJobs.com

Backend Engineering Resources

Whenever you're ready

There are 4 ways I can help you become a great backend engineer:

1. The MB Platform: Join 1000+ backend engineers learning backend engineering on the MB platform. Build real-world backend projects, track your learnings and set schedules, learn from expert-vetted courses and roadmaps, and solve backend engineering tasks, exercises, and challenges.

2. The MB Academy:​ The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

3. MB Video-Based Courses: Join 1000+ backend engineers who learn from our meticulously crafted courses designed to empower you with the knowledge and skills you need to excel in backend development.

4. GetBackendJobs: Access 1000+ tailored backend engineering jobs, manage and track all your job applications, create a job streak, and never miss applying. Lastly, you can hire backend engineers anywhere in the world.

LAST WORD 👋 

How am I doing?

I love hearing from readers, and I'm always looking for feedback. How am I doing with The Backend Weekly? Is there anything you'd like to see more or less of? Which aspects of the newsletter do you enjoy the most?

Hit reply and say hello - I'd love to hear from you!

Stay awesome,
Solomon

I moved my newsletter from Substack to Beehiiv, and it's been an amazing journey. Start yours here.

Reply

or to participate.