Back
Web Fundamentals

Real-time Communication: WebSockets, SSE & Polling

Web Fundamentals
Build & Deployment: Monorepo, CI/CD, Strategies & Release SafetyState Management: Choosing the Right SolutionRedux: Predictable State Container (RTK + RTK Query)React Query (TanStack Query): Server State CachingData Fetching Patterns: REST, GraphQL, tRPC & Real-timeGraphQL Fundamentals for Frontend: Shape, Caching, and TradeoffsgRPC-Web Fundamentals: Browser Constraints and Proxy ModelCaching Strategies: Client, Server & EdgeData Normalization: Organizing State for PerformanceAPI Design Best Practices: Pagination, Errors, Versioning & Type SafetyAPI Versioning Strategies for Frontend CompatibilityPagination: Offset vs Cursor-BasedRate Limiting & API Resilience: Retries, Backoff, Jitter, IdempotencyHow Frontend Developers Can Handle Millions of API Requests Without Crashing EverythingBrowser Storage: Cookies, SessionStorage, LocalStorage, IndexedDBReal-time Communication: WebSockets, SSE & PollingWebRTC: Real-Time Communication in the BrowserCore Web Vitals: LCP, INP & CLSPerformance Optimization Trade-offsCritical Resource Prioritization: Optimize Loading OrderCode Splitting: Optimize Bundle Size with Dynamic ImportsTree Shaking: Eliminate Dead Code from Your BundleLazy Loading: Load Resources On-DemandResource Hints: Preload, Prefetch & PreconnectText Compression: Gzip and BrotliImage & Video Optimization: Modern Formats & TechniquesAdaptive Loading: Optimize for Device & NetworkList Virtualization: Render Large Lists EfficientlyWeb Workers vs Main Thread: Offloading Heavy WorkMemory Leaks in Frontend Apps: Detection & PreventionManaging Third-Party Scripts: Optimization StrategiesHow CDNs Work: Edge Delivery, Caching & PerformanceHTTP Caching Deep Dive: Cache-Control, ETag & RevalidationService Workers & Offline Strategy: Cache First, Network First & Update LifecyclePWA Fundamentals: Manifest, Installability & Offline UXCritical Rendering PathScript Loading: async vs deferEvent Loop: Understanding JavaScript Execution ModelJavaScript Module Systems: CJS vs ESM vs UMDDynamic Module Loading: import() FunctionImport on Interaction: Load When User InteractsImport on Visibility: Lazy Loading with IntersectionObserverBrowser Rendering Pipeline & Layout ThrashingRendering Strategies: CSR vs SSR vs SSG vs ISRStreaming SSR: Progressive HTML StreamingIslands Architecture: Independent Component HydrationReact Server Components: Zero-JS Server RenderingFramework Reactivity: React, Vue, Svelte & SolidHTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC) for Frontend PerformanceDNS Resolution: Path, TTL, Caching & Frontend ImpactCross-Site Scripting (XSS) AttacksCross-Site Request Forgery (CSRF) AttacksCORS Explained: Cross-Origin Resource SharingCORS Preflight in Practice: Credentials, Simple Requests & MisconfigurationsContent Security Policy (CSP)Why is HTTPS Secure? Understanding TLS/SSLAuthorization Best PracticesCookie Security & Session Hardening: SameSite, HttpOnly, Secure
mediumFrontend Architecture

Real-time Communication: WebSockets, SSE & Polling

TL;DRWebSockets for bidirectional low-latency. SSE for simple server-to-client push. Polling as fallback. Always plan for reconnection, ordering, and scaling.
High Signal
Google
Meta
Netflix
Agoda
30-Second Answerstart every interview with this

Real-time features require choosing the right transport based on directionality, latency needs, scaling complexity, and operational cost. WebSockets offer full bidirectional communication but are stateful and harder to scale. Server-Sent Events provide simple unidirectional push with built-in reconnection. Polling is easiest but least efficient.

WebSockets = a phone call (both can talk anytime). SSE = a radio broadcast (server talks, you listen). Polling = repeatedly calling to ask 'anything new?' The best choice depends on how often each side needs to speak and how reliably the connection must stay open.

Choose Transport
Bidirectional? → WebSockets
Server Push Only? → SSE
Simple & Reliable? → Polling (fallback)

1WebSockets

Persistent, bidirectional, full-duplex connection. Excellent for chat, collaborative editing, and multiplayer games. Requires careful connection management, reconnection logic, and horizontal scaling (often with Redis Pub/Sub).

useWebSocket.tsts
useEffect(() => {
  const ws = new WebSocket(WS_URL);
  ws.onmessage = (e) => handleMessage(JSON.parse(e.data));
  return () => ws.close();
}, []);

2Server-Sent Events (SSE)

Unidirectional server-to-client streaming over HTTP. Simpler than WebSockets with built-in reconnection and event IDs. Ideal for notifications, live feeds, and progress updates.

3Polling Strategies

Short polling (fixed interval) is simple but wasteful. Long polling holds the connection open until data arrives. Use only when real-time requirements are relaxed.

4Scaling, Reconnection & Consistency

Plan for reconnection with exponential backoff + jitter. Use message ordering, idempotency, and client-side reconciliation to handle missed or out-of-order events.

PropertyWebSocketsSSEPolling
LatencyVery LowLowMedium-High
ScalingComplex (stateful)Easier (HTTP)Simple
Best ForChat, games, collaborationNotifications, live feedsLow-frequency updates
DirectionBidirectionalServer → ClientRequest/Response

WebSockets

Latency

Very Low

Scaling

Complex (stateful)

Best For

Chat, games, collaboration

Direction

Bidirectional

SSE

Latency

Low

Scaling

Easier (HTTP)

Best For

Notifications, live feeds

Direction

Server → Client

Polling

Latency

Medium-High

Scaling

Simple

Best For

Low-frequency updates

Direction

Request/Response

Common questions

  • ›“When would you choose WebSockets over SSE?”
  • ›“How do you handle reconnection in real-time features?”
  • ›“How do you scale WebSockets horizontally?”
  • ›“What are the trade-offs between polling and push-based solutions?”

What interviewers look for

  • Clear understanding of directionality and latency needs
  • Knowledge of reconnection, ordering, and idempotency
  • Scaling awareness (Redis Pub/Sub, sticky sessions)
  • Balanced trade-off reasoning

Short answer (60 sec)

Use WebSockets for bidirectional low-latency needs (chat, games). SSE for simple server push (notifications, feeds). Polling as a simple fallback. Always implement reconnection with backoff + jitter and ensure event ordering/idempotency.

Detailed answer (senior level)

WebSockets provide true bidirectional communication but require stateful scaling and reconnection logic. SSE is simpler for unidirectional push with built-in reconnection. Polling is easiest but inefficient. For production, combine with deduplication, optimistic updates, and client-side reconciliation to handle disconnects and out-of-order events gracefully.

  • Using WebSockets when SSE would suffice
  • No reconnection strategy (users lose updates on disconnect)
  • Ignoring message ordering and idempotency
  • Creating retry storms during outages
  • Scaling WebSockets without proper pub/sub backend
Key Takeaways
  • ✓WebSockets for bidirectional real-time
  • ✓SSE for simple, reliable server push
  • ✓Polling as fallback or for low-frequency updates
  • ✓Always implement reconnection with backoff + jitter
  • ✓Ensure event ordering and idempotency on client
  • ✓Plan for horizontal scaling from day one
  • ✓Choose transport based on direction, latency, and complexity
Previous TopicBrowser Storage: Cookies, SessionStorage, LocalStorage, IndexedDBNext Topic WebRTC: Real-Time Communication in the Browser

On this page