The Complete Realtime Guide
Learn how modern applications deliver instant experiences through realtime communication, synchronization, streaming, and messaging - from beginner to architect.
Without Realtime
With Realtime
Always in sync ⚡
Explained for Everyone
Pick your level - we'll explain realtime in terms you already understand.
Phone Call vs. Sending Letters
Imagine your friend lives far away. You could write them a letter and wait days for a reply - or you could call them on the phone and talk RIGHT NOW. The internet used to be like sending letters: you ask a question, wait, get an answer. Realtime internet is like a phone call - you see things the moment they happen, no waiting!
Instant Delivery
Data reaches users the moment it's available - no polling loop, no refresh button.
Bidirectional Flow
Both server and client can initiate communication at any time over a persistent channel.
Shared State
All connected users see the same live view - powering collaboration, presence, and sync.
Build realtime without managing infrastructure
PieSocket provides managed WebSocket channels, pub/sub, and presence - ready in minutes.
Realtime Changes Everything
The difference between a stale page and a live experience is measured in seconds - and in users lost.
Without Realtime
Users refresh to see new messages. Conversations feel broken and slow.
With Realtime
Messages arrive in <50ms. Typing indicators, read receipts, online presence.
The Evolution of Realtime
How the web went from page refreshes to persistent bidirectional channels.
Realtime Technologies Explained
Every transport technology - what it is, when to use it, and how it compares.
WebSocket
Full-duplex TCP connection established via HTTP upgrade. Both sides send frames at any time. The standard for realtime web applications.
Pros
- Full bidirectional
- Binary + text support
- <10 byte frame overhead
- Sub-5ms latency
Cons
- Stateful (sticky sessions needed)
- More complex to scale
- Some proxy issues
Best For
- Chat
- Gaming
- Trading
- Collaboration
- IoT
- Live analytics
Latency
Very Low (<5ms)
Direction
Bidirectional
Overhead
Very Low
PieSocket uses WebSocket under the hood
With pub/sub, presence, and serverless webhooks - all on managed global infrastructure.
Realtime Transport Playground
See how Polling, SSE, and WebSocket actually behave. Switch transports and watch the difference live.
Transport
At a glance
✓ Both sides send at any time.
One connection, sub-5ms latency, minimal overhead.
Press Start to simulate websocket
Want a real WebSocket playground?
Connect to live PieSocket or echo servers and send real frames.
How Realtime Systems Work
Click any component to understand its role in the realtime data flow.
Click a component above to learn about its role
Message Flow: Client → Server
- 1Client sends frame over persistent connection
- 2WS Gateway receives and parses the frame
- 3Gateway routes to correct backend handler
- 4Backend processes and optionally replies
- 5Reply published to pub/sub bus
- 6All subscribed gateways fan-out to clients
Message Flow: Server → All Clients
- 1Backend event fires (DB change, job complete, timer)
- 2Backend publishes to pub/sub channel
- 3All WS Gateway instances receive the event
- 4Each gateway pushes to locally-connected subscribers
- 5Clients receive the push with no request needed
- 6UI updates instantly across all sessions
Where Realtime Powers the World
Every experience you love in modern software runs on realtime infrastructure.
Realtime AI Applications
Modern AI is inseparable from realtime infrastructure. Every token streamed, every agent traced, every copilot update - all realtime.
Instead of waiting 10–30 seconds for a full LLM completion, tokens are streamed to the client as they're generated. This creates the familiar ChatGPT "typing" effect. SSE or WebSocket streams tokens from the inference server to the browser.
Architecture
Browser → HTTP/WS → API → LLM → Token stream → Browser renders word-by-word
PieSocket for AI
- Stream LLM tokens to users over WebSocket channels
- Broadcast agent step events to multiple clients
- Pub/Sub for multi-user AI collaboration
- Presence: see who's interacting with your AI
// Streaming AI responses with SSE
const response = await fetch('/api/chat', {
method: 'POST',
body: JSON.stringify({ message }),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const token = decoder.decode(value);
appendToUI(token); // Renders word-by-word
}Realtime Infrastructure at Scale
How to run realtime for millions of concurrent connections - or let PieSocket handle it.
Sticky Sessions & Load Balancing
WebSocket connections are stateful - all frames from one client must reach the same server. Configure your load balancer (NGINX, HAProxy, AWS ALB) to use IP hash or cookie-based routing.
PieSocket handles this automatically
- Sticky sessions with global load balancing
- Redis-backed pub/sub fan-out built in
- Presence API - no Redis to manage
- Auto-scaling across 7+ global regions
# NGINX sticky session for WebSocket
upstream ws_cluster {
ip_hash; # Same client → same server
server ws1.example.com:8080;
server ws2.example.com:8080;
server ws3.example.com:8080;
}
server {
location /ws/ {
proxy_pass http://ws_cluster;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_read_timeout 3600s;
}
}Realtime Security
Persistent connections introduce unique attack surfaces. Here's how to lock them down.
Always Use WSS (TLS)
Never use ws:// in production. WSS encrypts the entire connection using TLS, preventing eavesdropping and man-in-the-middle attacks. Modern browsers block ws:// on HTTPS pages.
// Always wss:// in production
const ws = new WebSocket("wss://api.example.com/ws");Authenticate on Connect
The WebSocket upgrade is an HTTP request - pass your JWT or session token. Validate server-side before upgrading the connection. Reject unauthenticated connections immediately.
const ws = new WebSocket(
`wss://api.example.com/ws?token=${jwt}`
);
// Server validates JWT before 101 responseValidate Origin Header
Check the Origin header during the upgrade to prevent cross-site WebSocket hijacking. Reject connections from unexpected origins - do not trust cookies alone.
server.on("upgrade", (req, socket) => {
if (!allowedOrigins.includes(req.headers.origin))
return socket.destroy();
});Rate Limit Connections & Messages
Limit connections per IP and messages per second. Disconnect abusive clients. Without rate limiting, a single attacker can exhaust your server memory with thousands of connections.
let msgCount = 0;
ws.on("message", () => {
if (++msgCount > 100)
ws.close(1008, "Rate limited");
});Realtime Infrastructure Cost
Estimate self-hosted cost vs. managed platform. Adjust the sliders to match your scale.
5,000
50
1
Self-Hosted Estimate
PieSocket Managed
Save ~$-19/mo
Start Free - No Credit CardWhich Realtime Technology Should You Use?
Answer 3 questions and get a personalised recommendation.
Does the client need to send data back to the server in realtime?
Realtime Systems Interview Questions
Common questions from junior to staff engineer - with detailed answers.
Common Realtime Mistakes
Bugs that trip up developers at every level - and how to fix them.
Wrong
// Polling every 2 seconds - even if nothing changed
setInterval(async () => {
const data = await fetch("/api/messages");
updateUI(await data.json());
}, 2000);Correct
// WebSocket - server pushes only when data changes
const ws = new WebSocket("wss://api.example.com/ws");
ws.onmessage = (e) => updateUI(JSON.parse(e.data));Polling wastes bandwidth proportional to clients × frequency. WebSocket delivers data only when it exists.
Realtime Frequently Asked Questions
The most common realtime questions, answered clearly.
Realtime Glossary
Key terms every realtime developer should know - from A to Z.
Backpressure
When a producer sends data faster than a consumer can process it. Managed with queues, rate limiting, and flow control.
Channel
A named pub/sub topic. Publishers send to a channel; all subscribers receive messages on that channel.
CRDT
Conflict-free Replicated Data Type - a data structure that automatically resolves concurrent write conflicts. Used in collaborative editors.
Event-Driven
Architecture where components communicate by emitting and reacting to events rather than direct calls.
Fan-out
Broadcasting one event to many subscribers. Example: one chat message delivered to 1000 room members.
Full-Duplex
Both sides can send and receive simultaneously on the same connection.
Heartbeat
Periodic messages (ping/pong) sent to keep a connection alive and detect failures.
MQTT
Message Queuing Telemetry Transport - a lightweight pub/sub protocol designed for constrained IoT devices.
Operational Transform
Algorithm for merging concurrent edits in collaborative editors (early Google Docs approach).
Polling
Client repeatedly requests data on a timer. Simple but wasteful - makes requests even when no data changed.
Presence
Tracking which users are currently online/active in a realtime system.
Pub/Sub
Publish-Subscribe pattern. Publishers emit to channels; subscribers receive matching events. Decouples senders from receivers.
Reconnection
Automatically re-establishing a dropped connection, typically with exponential backoff.
SSE
Server-Sent Events - persistent HTTP stream for server→client event push. Uses text/event-stream content type.
Sticky Session
Load balancer routing that sends all requests from one client to the same backend server. Required for stateful WebSocket.
Throughput
Number of messages delivered per second. Distinct from latency (time per message).
WebRTC
Web Real-Time Communication - browser standard for peer-to-peer audio, video, and data.
WebSocket
Full-duplex TCP protocol established via HTTP Upgrade. The standard for realtime web communication (RFC 6455).
WSS
WebSocket Secure - WebSocket over TLS. Always use WSS in production.
Realtime Challenges
Complete hands-on challenges to solidify your understanding. Track your progress.
0 / 210 points earned
Connect to a WebSocket
10 ptsOpen a connection to wss://echo.websocket.in and log a success message.
Send and Receive JSON
20 ptsSend {"type":"hello","name":"World"} and parse the JSON echo response.
Build a Live Chat
50 ptsConnect two browser tabs to the same server and exchange messages between them.
Add Reconnection
30 ptsImplement exponential backoff - the connection auto-restores within 5 seconds of a drop.
Implement Presence
40 ptsTrack online users - show who joins and leaves a channel in realtime.
Build a Live Dashboard
60 ptsStream mock metric data every second and render it as an updating chart.
Try the challenges in the Transport Playground above or the WebSocket Playground.
Without Managing Realtime Infrastructure
You've learned how realtime works. Now ship it - without sticky sessions, Redis clusters, WebSocket servers, or devops overhead. PieSocket is the managed realtime platform built for developers.
WebSocket Channels
Persistent, managed WebSocket connections with pub/sub built in. No server setup.
Global Edge Network
7+ regions. Clients connect to the nearest cluster. Sub-50ms worldwide.
Presence API
Track who's online in any channel. Join/leave events. No Redis to manage.
SDKs for Every Platform
JavaScript, React, React Native, Flutter, Python, PHP, Go, and more.
Enterprise Security
JWT auth, origin validation, rate limiting, and DDoS protection built in.
Serverless Webhooks
Trigger your backend on any realtime event. Works with Vercel, AWS Lambda, Cloudflare Workers.
Start free - no credit card required
200 connections free forever. Upgrade when you need more.
