Implementing Fallback Strategies
1. Detecting WebSocket Support
Example: Capability check
const hasWS = typeof WebSocket !== "undefined";
const transport = hasWS ? "ws" : "longpoll";
| Check | Detail |
|---|---|
| API exists | typeof WebSocket |
| Successful connect | Probe handshake |
| Sustained open | Maintains for > N sec |
| Proxy passthrough | Echo round-trip works |
2. Implementing Long Polling Fallback
| Step | Detail |
|---|---|
| Client GET /poll?cursor=N | Server holds until event |
| Server response | Returns events + new cursor |
| Client re-polls | Immediately with new cursor |
| POST /send | Outbound separately |
3. Implementing SSE Fallback
Example: EventSource
const es = new EventSource("/sse?token=" + jwt);
es.onmessage = (e) => handle(JSON.parse(e.data));
es.addEventListener("notification", (e) => toast(e.data));
| Aspect | SSE |
|---|---|
| Direction | Server → Client only |
| Auto-reconnect | Built-in |
| Outbound | HTTP POST separately |
| Proxy | Pure HTTP, traverses easily |
4. Using Socket.IO Transports
| Transport | Use |
|---|---|
| websocket | Default if available |
| polling | HTTP long-poll fallback |
| webtransport | HTTP/3 (Socket.IO v4.7+) |
Example: Socket.IO client
import { io } from "socket.io-client";
const s = io("https://api.example.com", { transports: ["websocket","polling"] });
s.on("connect", () => console.log("via", s.io.engine.transport.name));
5. Implementing Graceful Degradation
| Capability | Fallback |
|---|---|
| Bidirectional | SSE + POST |
| Binary | base64 over text |
| Low latency | Aggressive polling |
| Reliable order | Server-assigned seq |
6. Handling Mixed Connections
| Concern | Detail |
|---|---|
| Unified API | Adapter pattern hides transport |
| Feature parity | Lowest-common-denominator API |
| Metrics | Tag by transport |
7. Testing Fallback Mechanisms
| Test | How |
|---|---|
| Force fallback | Block ws in proxy |
| Toggle mid-session | Network mode change |
| Behavior parity | Same test suite both transports |
8. Implementing Progressive Enhancement
| Tier | Use |
|---|---|
| No JS | Plain HTML / Refresh |
| JS + fetch | Poll periodically |
| JS + SSE | Stream from server |
| JS + WS | Full bidirectional |
9. Communicating Fallback Status
| UI Hint | Detail |
|---|---|
| "Limited connection" | Polling mode active |
| Reduced features | Disable typing indicators, etc. |
| Reconnect prompt | Manual retry button |
10. Monitoring Fallback Usage
| Metric | Use |
|---|---|
| % conns on fallback | Network-quality signal |
| Fallback by region | Identify problematic ISPs |
| Upgrade success rate | WS handshake stats |