Developing WebSocket API for Mobile Application
WebSocket API for mobile app is designed differently than for web. Main difference — mobile constantly loses connection: network switching, Doze Mode on Android, iOS background. API must be designed so client can reconnect and get everything missed without loss.
Protocol Over WebSocket
Raw WebSocket is transport, not protocol. Define message format on top:
{
"type": "message.new",
"id": "uuid-v4",
"payload": { ... },
"timestamp": 1711234567890
}
type — routing on client. id — idempotence: client ignores duplicates on reconnect. timestamp — state sync.
Popular protocols over WebSocket: STOMP (works well with Spring Boot, rich client ecosystem), Socket.IO (fallback to polling support, rooms out of box, but ties to JS ecosystem), custom protocol (max control, more work everywhere).
Reconnect and State Recovery
Client should reconnect automatically. But reconnection alone isn't enough. Must give client events it missed.
Server side: each event has monotonically increasing sequence or cursor. On reconnect, client sends last received cursor:
{ "type": "subscribe", "channel": "chat.123", "lastSeq": 4521 }
Server responds with events where seq > 4521. Storage window — usually 24–72 hours. If client offline longer — send full state snapshot.
Without this mechanic, every disconnect means missed messages — especially critical on Android with Doze Mode.
Authentication and Authorization
WebSocket connection authenticated at handshake via query parameter or first message:
wss://api.example.com/ws?token=eyJ...
Query parameter simpler, but token ends in logs. Preferable: establish connection, then send auth frame with token, wait auth_ok from server before any subscriptions.
Token expiration during session — real scenario. Server should send token_expiring warning 60 seconds before, client refreshes token and sends new auth frame without connection break.
Server-side Scaling
One server instance can't hold all client connections. On horizontal scaling, message arriving at server A must reach clients on servers B and C. Standard solution — pub/sub via Redis (PUBLISH/SUBSCRIBE). Each server subscribes to channels and forwards messages to its WebSocket clients.
Infrastructure alternatives: Ably (hosted WebSocket), Pusher Channels, AWS API Gateway WebSocket — remove operational burden for cost and less control.
Client Implementation
On Android — OkHttp WebSocket with pingInterval for heartbeat. iOS — URLSessionWebSocketTask. Implementation details in WebSocket chat article. Important: when designing API, agree on max message size (WebSocket frame limit), error format and graceful closing (1000 Normal Closure vs 1011 Internal Error).
What's Included
Design protocol over WebSocket, implement server-side with replay mechanic, authentication and heartbeat, integrate client SDK for needed platforms. Document all event types.
Timeline: 6–12 days including server part and testing on unstable networks.







