惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
博客园 - 聂微东
L
LangChain Blog
D
Docker
大猫的无限游戏
大猫的无限游戏
人人都是产品经理
人人都是产品经理
D
DataBreaches.Net
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
腾讯CDC
C
Cisco Blogs
L
LINUX DO - 热门话题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
有赞技术团队
有赞技术团队
Forbes - Security
Forbes - Security
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 三生石上(FineUI控件)
S
Secure Thoughts
N
News and Events Feed by Topic
Latest news
Latest news
PCI Perspectives
PCI Perspectives
TaoSecurity Blog
TaoSecurity Blog
博客园 - 司徒正美
量子位
Stack Overflow Blog
Stack Overflow Blog
Know Your Adversary
Know Your Adversary
SecWiki News
SecWiki News
美团技术团队
C
CERT Recently Published Vulnerability Notes
Attack and Defense Labs
Attack and Defense Labs
AWS News Blog
AWS News Blog
C
Check Point Blog
S
Security Affairs
Vercel News
Vercel News
Google DeepMind News
Google DeepMind News
K
Kaspersky official blog
IT之家
IT之家
A
About on SuperTechFans
Help Net Security
Help Net Security
博客园 - 【当耐特】
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Recorded Future
Recorded Future
月光博客
月光博客
博客园_首页
小众软件
小众软件
H
Help Net Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
爱范儿
爱范儿

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Designing a Real-Time Chat System at Scale
Damir Karimov · 2026-06-23 · via DEV Community

Most developers underestimate how hard messaging systems really are.

A basic chat demo with WebSockets is easy to build. A production-grade messaging platform like WhatsApp, Telegram, Discord, or Slack is a completely different engineering problem. The hard part is not rendering messages in the UI. The hard parts are keeping millions of persistent connections alive, delivering messages reliably, preserving ordering, handling offline sync, scaling group chats, surviving partial failures, and keeping latency low around the world.

In this post, we'll design a scalable real-time chat architecture and walk through the trade-offs behind modern messaging systems.


Why chat gets hard

At first glance, chat seems simple:

  • send a message
  • store it
  • show it to the other user

That works for a demo. It falls apart fast in production.

Once you add real users, the system has to handle:

  • persistent connections
  • reconnects
  • message ordering
  • offline delivery
  • read receipts
  • typing indicators
  • multi-device sync
  • large group chats
  • global latency
  • partial failures

This is where chat stops being a UI feature and becomes a distributed systems problem.


Requirements

Before designing the system, we need clear requirements.

Functional requirements

Our chat system should support:

  • One-to-one chats
  • Group chats
  • Real-time message delivery
  • Read receipts
  • Typing indicators
  • Push notifications
  • Media attachments
  • Message history
  • Multi-device synchronization
  • Online and offline presence

Non-functional requirements

The system must also provide:

  • Low latency
  • High availability
  • Horizontal scalability
  • Fault tolerance
  • Reliable delivery
  • Event ordering
  • Efficient storage
  • Global distribution

At small scale, these are manageable. At millions of users, every one of them becomes a distributed systems concern.


High-level architecture

A modern chat platform is usually event-driven and distributed.

Clients
   │
   ▼
Load Balancer
   │
   ▼
WebSocket Gateway Cluster
   │
   ├── Authentication Service
   ├── Presence Service
   ├── Chat Service
   ├── Notification Service
   └── Media Service
          │
          ▼
    Kafka / Redis Streams
          │
          ▼
     Storage Layer

Each component has a separate responsibility. That separation is what makes the system scalable and easier to evolve.


Why polling fails

Many beginner chat apps start with polling:

GET /messages every 2 seconds

This works for a demo. It fails badly at scale.

Polling creates:

  • massive request overhead
  • unnecessary database reads
  • increased latency
  • battery drain on mobile devices
  • poor real-time responsiveness

Now imagine 2 million connected users polling every 2 seconds. That becomes 1 million requests per second even when nobody is sending anything. Real chat systems avoid this by using persistent connections.


Why WebSockets became the default

WebSockets keep a bidirectional connection open between the client and the server.

That gives you:

  • near real-time communication
  • lower overhead
  • reduced latency
  • efficient server push
  • better mobile performance

The client connects once:

Client ───── persistent connection ───── Server

After that, both sides can exchange events instantly. That is the foundation of modern messaging systems.

The hidden WebSocket cost

WebSockets solve one problem and introduce another.

A persistent connection is not free. Every connected user consumes:

  • a TCP socket
  • memory buffers
  • heartbeat state
  • authentication context

At 5 million concurrent users, this is no longer a normal API problem. It becomes a connection management problem.

That is why serious chat systems build specialized gateway infrastructure.


WebSocket gateway layer

The gateway layer is responsible for:

  • maintaining persistent connections
  • authenticating users
  • routing events
  • managing heartbeats
  • detecting disconnects

Gateways should stay as stateless as possible. Stateless gateways are much easier to scale, replace, and recover after failures.

Authentication flow

A common flow looks like this:

  1. User logs in via HTTP.
  2. Backend issues a JWT token.
  3. Client opens a WebSocket connection.
  4. Token is validated during the handshake.
  5. Connection is associated with a user session.

Example:

wss://chat.example.com?token=JWT

After authentication, the gateway knows which user owns the connection.

Sending a message

Now let's look at the real delivery pipeline.

Suppose User A sends:

Hello

A simplified flow is:

  1. Client sends a message event.
  2. Gateway validates authentication.
  3. Chat service validates permissions.
  4. Message is persisted in durable storage.
  5. Event is published into Kafka.
  6. Recipient gateway receives the event.
  7. Message is pushed to the recipient.
  8. Delivery ACK is generated.
  9. Read receipt is generated later.

This looks simple on paper. In reality, every step can fail.

Why persistence comes first

A lot of beginners try this:

deliver → save later

That is dangerous.

If the server crashes before persistence, the recipient saw the message, but the database lost it. Now the system is inconsistent.

Production systems usually do:

persist → publish → deliver

Durability comes first.


Message IDs and ordering

Distributed systems do not guarantee ordering automatically.

Example:

  • Message A
  • Message B

Recipient receives:

  • Message B
  • Message A

Why does this happen? Because messages may travel through different gateway servers, queues, and network paths.

Common ordering strategies

Timestamp ordering

Simple, but unreliable. Clock drift breaks consistency.

Incremental sequence IDs

More reliable.

Example:

conversation_id: 42

messages:
1
2
3
4

This guarantees ordering inside a conversation. Most real systems only guarantee local ordering per chat. Global ordering across the entire platform is usually impossible at scale.


Database design

Messaging systems are write-heavy. A popular group chat can generate thousands of writes per second.

Typical tables:

  • users
  • conversations
  • conversation_members
  • messages
  • message_status
  • attachments

The real challenge is partitioning.

Why a single database eventually fails

A single PostgreSQL instance works at the beginning. Over time, problems show up:

  • write bottlenecks
  • storage growth
  • replication lag
  • index size explosion

At scale, systems introduce sharding.

Sharding strategy

A common strategy is:

shard by conversation_id

Benefits:

  • messages for the same chat stay colocated
  • ordering becomes easier
  • queries stay efficient

Bad shard keys create hotspots. For example, sharding by user_id can spread large group chats across multiple shards and make fan-out expensive.


Kafka and event streaming

Modern messaging systems are heavily event-driven.

Kafka is useful because it provides:

  • durable event logs
  • replayability
  • partitioned scalability
  • consumer groups

Instead of services calling each other directly:

Chat Service → Kafka → Consumers

Consumers may include:

  • delivery service
  • notification service
  • analytics
  • moderation
  • push notifications

This decouples the system and makes failures easier to isolate.


Presence system

Presence is deceptively expensive.

Tracking online, offline, typing, and last_seen for millions of users creates a huge amount of event traffic. That is why most systems isolate presence into a dedicated service.

Presence implementation

A common architecture is:

Gateway → Redis → Presence Service

Gateways periodically send heartbeats.

Example:

PING every 30 seconds

If heartbeats stop, the user is marked offline.

Redis works well here because presence data is ephemeral. Not everything belongs in a relational database.

Typing indicators

Typing indicators look trivial. They are not.

Problems include:

  • high event frequency
  • noisy updates
  • unnecessary fan-out

Most systems heavily throttle typing events.

Example:

User typing → emit once every 3 seconds

Without throttling, typing indicators can overload the infrastructure faster than messages.

Fan-out in group chats

Suppose a group contains 500,000 users.

One message may require 500,000 deliveries. This is called fan-out.

Large fan-out is one of the hardest messaging problems.

Fan-out strategies

Fan-out on write

The server precomputes deliveries immediately.

  • fast reads
  • expensive writes

Fan-out on read

Messages are stored once.

  • cheaper writes
  • more expensive reads

Different platforms choose different trade-offs.


Offline synchronization

Users disconnect constantly:

  • mobile app closed
  • network loss
  • airplane mode
  • battery saver

The system must synchronize missed events efficiently.

Typical approach:

fetch all events after last_sequence_id

Example:

last_seen_message = 10451

Server returns:

10452+

Incremental synchronization is critical. Full synchronization is too expensive.


Push notifications

Offline users still need notifications.

Pipeline:

message event
   ↓
notification service
   ↓
APNs / FCM
   ↓
mobile device

Push systems are eventually consistent. Notifications may arrive late, duplicated, or out of order. Clients need to tolerate that.

Multi-device sync

Modern users expect sync across:

  • phone
  • desktop
  • browser
  • tablet

Each device may keep its own session. The backend tracks:

  • user_id
  • device_id
  • connection_id
  • last_sync_state

Events are usually delivered independently per device.


Reliability guarantees

Messaging systems need clear delivery semantics.

At-most-once

Fastest. Messages may disappear.

At-least-once

Reliable. Duplicates are possible.

Exactly-once

Extremely expensive and difficult in distributed systems.

Most production systems use:

at-least-once + idempotency

That is the practical choice.


Why exactly-once is mostly marketing

Exactly-once delivery across distributed infrastructure is incredibly hard.

Network failures create ambiguity:

  • Did the recipient receive the message?
  • Did the ACK get lost?
  • Did the retry create a duplicate?

Sometimes the sender cannot know for sure.

That is why many systems rely on retries, deduplication, and idempotent consumers instead of true exactly-once guarantees.


Common failure scenarios

Real systems fail all the time.

Examples:

  • gateway crashes
  • Kafka partition unavailable
  • Redis outage
  • slow consumers
  • duplicate events
  • partial synchronization
  • network splits

Reliable systems assume failure is normal.


Scaling strategies

As traffic grows, teams usually add:

  • horizontal scaling for gateway nodes
  • partitioned Kafka topics
  • regional infrastructure
  • CDN for media
  • caching to reduce database pressure

The biggest bottleneck is usually not CPU.

At scale, bottlenecks are often:

  • network throughput
  • memory usage
  • hot partitions
  • connection limits
  • disk I/O
  • replication lag

Chat systems are infrastructure-heavy workloads.


What makes messaging hard

The frontend UI may look simple. Underneath is a distributed system balancing:

  • consistency
  • availability
  • latency
  • reliability
  • scalability

Every architectural decision introduces trade-offs. You can optimize latency, durability, throughput, or cost, but rarely all at once.

That is why messaging systems remain one of the most interesting areas in system design.


Practical takeaway

If you are building chat, do not think only in terms of sockets and message lists. Think in terms of delivery guarantees, storage strategy, ordering, recovery, and fan-out.

A chat product becomes serious very quickly. The moment you need offline sync, presence, multi-device support, and reliable delivery, you are no longer building a UI feature. You are building a distributed messaging platform.