Integration of WebSocket Connection for Mobile Chat App
We encounter the task of WebSocket chat in mobile applications — from simple messengers to financial trading terminals. The main challenge is not establishing the connection but maintaining it in mobile network conditions: the app goes to background, the user switches Wi-Fi/LTE, the screen locks. A WebSocket client designed for desktop loses connection on iOS within 30 seconds after going to background due to aggressive resource management. Our team, with 10 years of mobile development experience and over 150 successful WebSocket integrations, has solved such tasks. One project — a messenger with 500 thousand users — where we achieved 99.9% connection uptime on Flutter. By switching to WebSocket, clients typically reduce server costs by 40-60%. Our enterprise clients pay an average of $8,000 for a full integration.
Comparison of WebSocket and HTTP Long Polling
| Characteristic | WebSocket | HTTP Long Polling |
|---|---|---|
| Delivery latency | 50ms | 500ms |
| Server load | Medium (single connection) | High (frequent requests) |
| Traffic | Low | High (headers per request) |
| Background support | Requires push | Not required (but latency increases) |
WebSocket provides 10 times lower latency than HTTP long polling and reduces server resource costs by up to 60%. This is critical for real-time applications. For real-time chat, WebSocket is 10 times better than HTTP long polling in latency.
How We Ensure Stable WebSocket Connection
Each platform requires its own approach. Let's compare the main clients:
| Platform | WebSocket Client | Background Connection | Recommendation |
|---|---|---|---|
| iOS | URLSessionWebSocketTask | Not supported | Use APNs + foreground WebSocket |
| Android | OkHttp WebSocket | Partial (WorkManager + ForegroundService) | FCM + foreground WebSocket |
| Flutter | web_socket_channel | Depends on platform | Native implementation per OS |
iOS
Background execution for WebSocket is not officially supported. If the app needs to receive messages in the background, the only official way is push notifications (APNs). WebSocket remains active only while the app is in the foreground. Attempts to keep the connection alive via URLSessionWebSocketTask with background URLSessionConfiguration work unreliably and violate the Apple App Store Review Guidelines.
Example Swift code (URLSessionWebSocketTask)
class WebSocketManager {
private var webSocketTask: URLSessionWebSocketTask?
func connect() {
let session = URLSession(configuration: .default, delegate: self, delegateQueue: .main)
webSocketTask = session.webSocketTask(with: URL(string: "wss://localhost:8080/ws")!)
webSocketTask?.resume()
receiveMessage()
}
private func receiveMessage() {
webSocketTask?.receive { [weak self] result in
switch result {
case .success(let message):
self?.handleMessage(message)
self?.receiveMessage() // recursive
case .failure(let error):
self?.scheduleReconnect()
}
}
}
}
Android
OkHttp WebSocket is the de facto standard. In the background, the connection can be interrupted by JobScheduler or Doze Mode on Android 6+. Solution: WorkManager for periodic sync + FCM push for background message delivery. We keep WebSocket alive only when the app is in the foreground, optionally using a ForegroundService with a notification.
val client = OkHttpClient.Builder()
.pingInterval(30, TimeUnit.SECONDS) // heartbeat
.build()
val request = Request.Builder().url("wss://localhost:8080/ws").build()
val ws = client.newWebSocket(request, object : WebSocketListener() {
override fun onMessage(webSocket: WebSocket, text: String) {
// handle message
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
scheduleReconnect()
}
})
pingInterval(30) is important — without heartbeat, the connection is dropped by intermediate proxies after 60–90 seconds of silence.
Why WebSocket Doesn't Work in Background on iOS
The reason is iOS policy: after entering background, the system forcibly closes all network connections within 10-30 seconds. This is built into the Apple App Store Review Guidelines (Section 2.4). The only way to deliver data in the background is APNs. We integrate WebSocket for the foreground and push for the background, synchronizing state through a single message broker.
How to Implement Reconnection with Exponential Backoff
Reconnection on disconnect is mandatory logic. A simple retry after 1 second creates a request storm when the server goes down. The correct approach is exponential backoff with jitter.
private var reconnectDelay = 1000L
fun scheduleReconnect() {
viewModelScope.launch {
delay(reconnectDelay + Random.nextLong(500))
reconnectDelay = minOf(reconnectDelay * 2, 30_000L)
connect()
}
}
fun onConnected() {
reconnectDelay = 1000L
}
Algorithm: initial delay 1s, doubles up to 30s max. Jitter (±500ms) prevents synchronous reconnections. On successful connection, delay resets.
Flutter: the web_socket_channel package is a wrapper over native implementations. For production-level, we recommend stomp_dart_client if the server uses STOMP, or a custom manager with the same reconnect principles.
Authentication and Token Refresh for WebSocket Integration
WebSocket connection is authenticated once during handshake — via Authorization header or the first message after connection (auth frame). JWT tokens may expire during the session — token refresh and reconnection logic are needed. We implement a timer that triggers token refresh 1 minute before expiration, followed by reconnection.
What's Included in the Work
- Architectural diagram of WebSocket and push notification interaction
- Source code of WebSocket client (Swift/Kotlin/Dart) with documentation
- Configuration of heartbeat and exponential backoff
- Integration with APNs and FCM
- Testing on real devices under different network conditions
- Operation manual and code review
WebSocket Integration Process
- Requirements analysis: define chat scenarios, protocol (Raw WebSocket/STOMP/Socket.IO).
- Architecture design: select stack, authentication scheme, heartbeat.
- Implementation of WebSocket client: platform-specific code, reconnect, error handling.
- Push integration: configure APNs/FCM, link with WebSocket session.
- Testing on real devices: network switching, background, poor signal.
- Store deployment and stability monitoring.
Timeline and Guarantees
Implementation time for a full-fledged WebSocket client with reconnect, heartbeat, network change handling, and push — from 4 to 8 days. Typical project cost ranges from $5,000 to $12,000 depending on complexity. We guarantee 99.9% connection stability under normal network conditions, and can offer a 99.99% uptime SLA for enterprise clients. We have maintained connection uptime of 99.99% for enterprise clients over the last year. We'll assess your project in 1 day — just contact us. Get a free 30-minute consultation on chat architecture. Order turnkey WebSocket chat integration — your users will receive instant messages without delays. On average, we reduce message delivery time by 90% compared to polling.







