- Backend Weekly
- Posts
- API and API Design: How Do Server-Sent Events (SSE) Work
API and API Design: How Do Server-Sent Events (SSE) Work
This issue will explore how SSE works, its advantages over other real-time communication methods, and best practices for designing SSE-powered APIs.

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 94 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 How WebSockets Works 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 Server-Sent Events (SSE) today and learn the intricacies of SSE, including a simple program that shows how to implement SSE into our projects for real-time application.
Overview of Server-Sent Events (SSE)
Server-sent events (SSE) have emerged as a powerful and efficient mechanism for unidirectional data streaming.
Unlike traditional request-response architectures, where a client continuously polls for updates, SSE enables the server to push data to clients whenever new information becomes available.
This makes SSE particularly valuable for real-time applications such as live news updates, real-time gaming, stock market feeds, and live-streaming services.
This issue will explore how SSE works, its advantages over other real-time communication methods, and best practices for designing SSE-powered APIs.
What Are Server-Sent Events (SSE)?
Server-sent events (SSE) are a real-time API technology built on standard HTTP that allows servers to continuously push updates to clients over a single connection. It uses the EventSource API, which is natively supported by most modern browsers, making it an accessible and efficient solution for real-time communication.
Unlike WebSockets, which support full-duplex communication (bi-directional data exchange), SSE follows a one-way data flow:
The server continuously sends updates to the client.
The client passively listens for updates without needing to request them explicitly.
This push-based architecture reduces network overhead and ensures clients receive real-time updates without repeated polling.
Now we understand what SSE is and how it differs from WebSockets as we discussed in the previous issue. Next, let’s explore how SSE works.
How Does SSE Work?
SSE operates using a long-lived HTTP connection where the server streams events to the client. The interaction follows these key steps:
Client Initiates the Connection: The client opens an HTTP connection to the server using the
EventSource
API. The server keeps this connection open and sends updates as events occur.Server Pushes Data: Instead of waiting for a new client request, the server automatically pushes data to all connected clients when an update is available.
Client Receives Events in Real-Time: The client listens for incoming messages and processes them as they arrive. The connection remains open until the server closes it or the client disconnects.
SSE Request and Response Flow
Next, let’s look at the request and response flow of a server-sent event and create a simple implementation using Node.js.
Client-Side: Opening an SSE Connection
Using JavaScript’s EventSource
API, a client can easily subscribe to an SSE stream:
const eventSource = new EventSource('http://example.com/stream');
eventSource.onmessage = function(event) {
console.log('New event received:', event.data);
};
eventSource.onerror = function() {
console.log('Connection lost, attempting to reconnect...');
};
In the code snippet above, you see that we use the JavaScript’s EventSource
API to create a new event and listen to incoming messages from the server using the onmessage
event.
Also, we use the onerror
event to catch any errors during connection and other errors that might occur during interactions. If the connection is lost, most browsers will automatically retry the connection.
Server-Side: Streaming Events in Node.js
Next, let’s look at the server-side implementation of SSE in Node.js:
const express = require('express');
const app = express();
app.get('/stream', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
let counter = 0;
const interval = setInterval(() => {
counter++;
res.write(`data: {"message": "Update #${counter}", "timestamp": ${Date.now()}}\n\n`);
}, 3000);
req.on('close', () => {
clearInterval(interval);
});
});
app.listen(3000, () => console.log('SSE server running on http://localhost:3000/stream'));
In the code snippet above, The server sets text/event-stream
as the response type to indicate an SSE connection. res.write()
is used to continuously push new updates. The connection remains open until the client disconnects or the server closes it.
Use Cases for SSE
SSE is ideal for applications where real-time updates flow in a single direction from server to client:
Live News and Social Media Feeds: Users receive instant updates on breaking news or trending posts.
Stock Market and Cryptocurrency Price Updates: Investors see real-time fluctuations without refreshing their dashboards.
Live Sports Scores: Fans get live score updates as matches progress.
IoT Sensor Data Monitoring: Devices stream sensor data to dashboards in real-time.
Customer Support Notifications: Agents receive instant alerts when new customer inquiries arrive.
SSE vs. WebSockets vs. Polling
Let’s see a clear distinction between SSE, Websockets, and polling.
Feature | SSE (Server-Sent Events) | WebSockets | Polling |
---|---|---|---|
Direction | One-way (Server → Client) | Bi-directional | Client repeatedly requests updates |
Efficiency | Efficient for server push | Ideal for real-time interaction | High overhead |
Use Case | Live updates (news, stocks) | Chat apps, gaming, real-time collaboration | Basic data sync |
Transport | Standard HTTP | TCP-based WebSocket protocol | Standard HTTP |
Browser Support | Native in most browsers | Requires WebSocket support | Works everywhere |
Auto-Reconnect | Yes (handled by browser) | Requires manual handling | Requires manual handling |
When to use SSE: When only the server needs to send updates (e.g., live feeds, notifications). When simplicity and efficiency are priorities.
When to use WebSockets: When the client also needs to send data continuously (e.g., chat applications, online gaming).
When to use Polling: When real-time is not critical, but updates are needed periodically (e.g., checking for new emails every 5 minutes).
Best Practices for Implementing SSE
Use Proper Headers: Always set
Content-Type: text/event-stream
,Cache-Control: no-cache
, andConnection: keep-alive
to ensure smooth streaming.Handle Connection Loss Gracefully: Clients should automatically reconnect when the connection is lost. SSE supports built-in reconnection, but you can use
eventSource.onerror
to handle failures.Keep Messages Lightweight: Only send necessary data to minimize bandwidth usage. Use JSON serialization for structured messages.
Optimize Server Performance: Limit the number of active connections to prevent excessive resource consumption. Consider load balancing for large-scale applications.
Secure the Connection: Use HTTPS (wss://) for encrypted communication. Implement authentication tokens to control access.
Server-sent events (SSE) provide a powerful, efficient, and lightweight way for servers to push real-time updates to clients. By leveraging persistent connections, SSE reduces the need for unnecessary polling, leading to better performance and scalability.
While it may not be suitable for every use case (especially those requiring bi-directional communication), SSE excels in scenarios where the server continuously streams real-time updates—such as live news, stock market tracking, or IoT monitoring.
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.
👨‍💻 FaceUp
✍️ Node.js Backend Developer for FaceUp
đź“ŤRemote, Prague, Brno
đź’° Click on Apply for salary details
Click here to Apply for this role.
👨‍💻 ROIVENUE
✍️ Full-stack Software Developer
đź“ŤRemote, Prague
đź’° 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