SSE Retry Mechanism — Complete Guide to Auto-Reconnection
In this tutorial, you will learn about SSE Retry Mechanism. We cover key concepts, practical examples, and best practices to help you master this topic.
SSE retry mechanism controls how long the browser waits before reconnecting after a dropped connection, allowing servers to suggest a retry interval and clients to implement exponential backoff for resilient real-time streaming.
What You'll Learn
- How the retry field works in SSE
- Implementing exponential backoff on the client
- Server-side strategies for managing reconnections
Why It Matters
Network connections drop. Without a proper retry mechanism, clients either reconnect too aggressively (overloading the server) or too slowly (missing updates). SSE's built-in retry gives servers control over reconnection timing.
Real-World Use
A live stock ticker using SSE sets a retry of 2000ms. When a client disconnects during a network blip, it waits 2 seconds before reconnecting. The server uses the Last-Event-ID to resume from the last received event.
flowchart LR
A["Client Connected"] --> B["Connection Lost"]
B --> C["Wait retry ms"]
C --> D["Reconnect"]
D --> E["Send Last-Event-ID"]
E --> F["Resume Stream"]
F --> A
style C fill:#dbeafe,stroke:#2563eb
Code Examples
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/events') {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
res.write('retry: 3000\n\n');
let eventId = 0;
const interval = setInterval(() => {
eventId++;
res.write(`id: ${eventId}\n`);
res.write(`data: {"tick": ${eventId}}\n\n`);
}, 1000);
req.on('close', () => clearInterval(interval));
}
});
server.listen(3000);
Expected output: Server sends retry: 3000 instructing clients to wait 3 seconds before reconnecting.
// Client with manual exponential backoff
function connectWithBackoff(url, retryCount = 0) {
const source = new EventSource(url);
const delay = Math.min(1000 * Math.pow(2, retryCount), 30000);
source.onerror = () => {
source.close();
console.log(`Reconnecting in ${delay}ms (attempt ${retryCount + 1})`);
setTimeout(() => connectWithBackoff(url, retryCount + 1), delay);
};
source.onmessage = (event) => {
console.log('Received:', event.data);
};
}
connectWithBackoff('/events');
Expected output: Client waits 1s, 2s, 4s, 8s between retries, capped at 30s.
import http.server
import json
import time
class SSEHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/events':
self.send_response(200)
self.send_header('Content-Type', 'text/event-stream')
self.send_header('Cache-Control', 'no-cache')
self.end_headers()
self.wfile.write(b'retry: 5000\n\n')
counter = 0
while True:
counter += 1
data = json.dumps({"count": counter}).encode()
self.wfile.write(f"id: {counter}\ndata: {data.decode()}\n\n".encode())
time.sleep(2)
Expected output: Python SSE server sends retry: 5000 telling clients to wait 5 seconds before reconnecting.
Common Mistakes
1. Setting Retry Too Low
A retry of 100ms causes a reconnect storm during an outage, amplifying server load.
2. Ignoring the Retry Field Client-Side
The default browser retry is 2-3 seconds. Override with the retry field only when you need different timing.
3. No Exponential Backup on Client
Even with a server retry, implement client-side backoff to handle sustained outages gracefully.
4. Resetting Event ID After Reconnect
If the client reconnects without sending Last-Event-ID, the server cannot resume and sends duplicate data.
5. Not Closing the Old Connection
When manually reconnecting, always close the old EventSource before creating a new one to avoid resource leaks.
Practice Questions
- What does the retry field do in an SSE stream?
- How does exponential backoff improve reconnection behavior?
- What is the default browser retry interval for SSE?
- Why should you send Last-Event-ID on reconnection?
- What happens if retry is set to 0?
Answers:
- It tells the browser how many milliseconds to wait before reconnecting after a connection drop.
- It prevents reconnect storms by increasing delay after each failure, capped at a maximum.
- 2-3 seconds, varying by browser.
- The server uses it to resume the stream from the last sent event, avoiding duplicates.
- The browser reconnects immediately, which can cause a reconnect storm during outages.
Challenge: Build an SSE server that simulates random disconnections. The client should implement exponential backoff (1s, 2s, 4s, 8s, max 30s) and track reconnection attempts in a status display.
FAQ
Mini Project
Build a resilient SSE client that connects to a stock ticker stream, implements exponential backoff with configurable initial delay and max delay, displays connection status, and resumes from the last received event ID after reconnection.
What's Next
Read about SSE multiplexing strategies to manage multiple event streams, or explore SSE browser support and polyfills for cross-browser compatibility.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro