04-backend-knowledge

WebSockets

04-backend-knowledge/websockets

WebSockets

Overview

WebSockets provide persistent, bidirectional communication between client and server.


Why It Matters

They are useful for live updates, collaboration, and real-time notifications, but they add connection complexity.


Core Concepts

  • The connection stays open.
  • Messages are event-driven.
  • Reconnect and state resync behavior matter.

Mental Models

Treat the connection as fragile and design for disconnects, replay, and out-of-order events.


Best Practices

  • Reconnect gracefully.
  • Handle missed messages.
  • Keep message contracts small and explicit.

Common Mistakes

  • Assuming the connection is always alive.
  • Sending oversized or ambiguous payloads.
  • Ignoring reconnect and backoff behavior.

Trade-offs

Real-time UX improves responsiveness, but the system becomes harder to test and operate.


Decision Framework

NeedUse WebSockets?
Live chat or collaborationOften yes
Rare updatesUsually no
Simple data refreshUsually not necessary

Examples

  • Show live presence updates after the connection is established.

Checklists

  • Does the app recover from disconnects?
  • Are messages versioned or predictable?
  • Is stale state resynced after reconnect?

Senior Engineer Notes

Senior engineers use real-time channels only when the benefit is strong enough to justify the complexity.


Further Reading