Skip to main content

Real-Time Communication

Overview

Real-Time Communication (RTC) enables systems to exchange data instantly or near-instantly between clients, servers, services, or devices.

Modern applications use real-time communication for:

  • Chat systems, Live notifications
  • Multiplayer games
  • Financial trading systems
  • IoT telemetry
  • Live dashboards
  • Video conferencing
  • Collaborative editing
  • Streaming platforms

Why Real-Time Communication Matters

Traditional HTTP communication is request-response based — inefficient for:

  • Instant updates
  • Continuous streams
  • Low-latency systems
  • Bidirectional communication

Communication Models

Polling

Client repeatedly asks the server for updates.

Disadvantages: High latency, wastes bandwidth, expensive at scale.


Long Polling

Client waits until server has new data.


WebSockets

Persistent bidirectional communication channel.


Server-Sent Events (SSE)

One-way server-to-client streaming. Use cases: notifications, live feeds, monitoring dashboards.


Core Concepts

Latency Types

TypeDescription
Network LatencyPacket travel delay
Processing LatencyServer processing time
Serialization LatencyEncoding/decoding overhead

Message Delivery Models

ModelDescription
At Most OnceMay lose messages
At Least OncePossible duplicates
Exactly OnceNo duplicates, no loss

Backpressure

Occurs when receivers cannot process data fast enough.

Solutions: Rate limiting, buffering, message dropping, flow control.


Architecture Patterns

Publish-Subscribe (Pub/Sub)

Publishers send messages without knowing subscribers.

Technologies: Redis Pub/Sub, Apache Kafka, RabbitMQ, NATS.


Event-Driven Architecture


WebSocket Architecture (Scaled)

ComponentPurpose
Load BalancerDistributes connections
WebSocket ServerMaintains persistent sessions
RedisShared pub/sub
Message BrokerCross-node messaging

Real-Time Protocols

WebSocket

  • Full duplex, persistent connection, TCP-based, low overhead
  • Handshake: GET /chat HTTP/1.1 → Upgrade: websocket

gRPC Streaming Types

TypeDescription
UnaryRequest-response
Server StreamingServer pushes stream
Client StreamingClient uploads stream
BidirectionalTwo-way stream

WebRTC

Peer-to-peer real-time media communication. Use cases: video calls, voice calls, screen sharing.


Message Brokers

BrokerCharacteristics
Apache KafkaHigh throughput, durable logs, partitioning, replay capability
RabbitMQReliable delivery, routing support, flexible messaging
Redis Pub/SubExtremely fast, lightweight, non-persistent

SignalR in ASP.NET Core

SignalR simplifies real-time communication with WebSocket abstraction, automatic reconnect, group messaging, and transport fallback.

Creating a Hub

using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync(
"ReceiveMessage",
user,
message
);
}
}

Registering SignalR

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSignalR();

var app = builder.Build();

app.MapHub<ChatHub>("/chatHub");

app.Run();

JavaScript Client

const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();

connection.on("ReceiveMessage", (user, message) => {
console.log(`${user}: ${message}`);
});

await connection.start();

await connection.invoke("SendMessage", "Alice", "Hello World");

Scaling Real-Time Systems

Horizontal Scaling

Distributed backplanes for cross-server messaging: Redis Backplane, Azure SignalR Service.


Security

[Authorize]
public class NotificationHub : Hub
{
}

Best practices:

  • JWT / OAuth2 authentication
  • TLS/HTTPS encryption
  • Rate limiting to protect against DDoS, message floods, connection exhaustion

Performance Optimization

Serialization Formats

FormatCharacteristics
JSONHuman readable
MessagePackCompact binary
Protocol BuffersHigh performance

Best practices:

  • Compress payloads
  • Use binary serialization
  • Implement idle timeout and heartbeats
  • Batch multiple events into one payload

Reliability Patterns

Circuit Breaker

Solutions for message duplication: idempotency, unique event IDs.

Solutions for connection storms: exponential backoff, randomized reconnect delay.


Monitoring Metrics

MetricDescription
Active ConnectionsCurrent sessions
Message ThroughputMessages/sec
LatencyResponse delay
Error RateFailed operations
Queue DepthBackpressure indicator

Common Pitfalls

ProblemCauseSolution
Memory LeaksUnreleased subscriptions / unclosed socketsProperly dispose connections
Connection StormsMass reconnect attemptsExponential backoff
Message DuplicationRetry logic without idempotencyUnique event IDs

Cheat Sheet

ConceptSummary
WebSocketPersistent bidirectional communication
SSEOne-way server streaming
SignalRASP.NET Core real-time framework
KafkaDistributed event streaming
Pub/SubDecoupled messaging pattern
BackpressureConsumer overload protection
Sticky SessionsSame-client server affinity
CQRSSeparate reads/writes
Event SourcingStore events as source of truth

Learning Roadmap


CategoryTechnologies
Real-Time FrameworkSignalR, Socket.IO
Message BrokerKafka, RabbitMQ, NATS
Cache/BackplaneRedis
StreamingFlink, Spark Streaming
MonitoringPrometheus, Grafana
TracingOpenTelemetry

Interview Questions

Beginner

  1. What is WebSocket?
  2. Difference between polling and WebSocket?
  3. What is SignalR?
  4. What is pub/sub?
  5. What is latency?

Intermediate

  1. How do you scale WebSocket servers?
  2. What are sticky sessions?
  3. Explain backpressure.
  4. Difference between Kafka and RabbitMQ?
  5. Explain eventual consistency.

Advanced

  1. Design a real-time chat system.
  2. How would you handle millions of WebSocket connections?
  3. Explain distributed event ordering.
  4. Design a multiplayer game backend.
  5. How do you prevent connection storms?