Optimizing for Mobile
1. Handling Mobile Network Issues
| Issue | Mitigation |
|---|---|
| High RTT (cell) | Tolerate; batch messages |
| NAT rebinding | Aggressive heartbeat (15-30s) |
| Carrier proxies | Use wss:// (port 443) |
| Network switch | Reconnect with resume |
| Packet loss | App ack + retransmit |
2. Implementing Background Connection
| Platform | Strategy |
|---|---|
| iOS | APNS push wakes app; reconnect on resume |
| Android | FCM push or foreground service |
| Web (mobile) | Hidden tab pauses timers; close on hide |
3. Reducing Battery Consumption
| Tactic | Detail |
|---|---|
| Lower heartbeat when idle | 2 min vs 30s |
| Coalesce updates | Single radio wake-up |
| Disconnect on hide | Reconnect on resume |
| Push for important only | Native push for events that need wake |
4. Handling App Suspension
Example: visibilitychange
document.addEventListener("visibilitychange", () => {
if (document.hidden) ws?.close(4001, "background");
else reconnect();
});
| Event | Action |
|---|---|
| visibilitychange (hidden) | Close or downgrade |
| pageshow (BFCache restore) | Reconnect |
| freeze / resume | Native lifecycle |
5. Optimizing for Slow Networks
| Optim | Detail |
|---|---|
| Small messages | < 1 KB |
| Binary format | msgpack/protobuf |
| Compression | permessage-deflate |
| Skip non-critical | Drop telemetry on 2G |
| Larger backoff | Multiplied on slow net |
6. Implementing Offline Support
| Capability | Detail |
|---|---|
| Local queue | IndexedDB persistence |
| Optimistic UI | Show local, reconcile |
| Idempotent ops | Client-id deduplication |
| Conflict resolution | CRDT or server-wins |
7. Handling Network Type Changes
| API | Use |
|---|---|
navigator.connection.effectiveType | "4g","3g","2g","slow-2g" |
change event | Adapt heartbeat / batch size |
saveData flag | Reduce traffic |
8. Using Page Visibility API
| State | Action |
|---|---|
| hidden | Pause heartbeat, reduce updates |
| visible | Reconnect if needed, fetch missed |
| prerender | Skip connect until visible |
9. Testing on Mobile Devices
| Tool | Use |
|---|---|
| Chrome remote debug | Android USB |
| Safari Web Inspector | iOS USB |
| DevTools throttling | Simulate 3G |
| Real-device labs | BrowserStack, Sauce |
10. Monitoring Mobile Performance
| Metric | Detail |
|---|---|
| Reconnect rate | Mobile baseline higher |
| RTT histogram | By network type |
| Battery (native) | Power profiler in OS |
| Data usage | Bytes per session |