Almost every messaging prototype looks great on office Wi-Fi. Two test phones sit on a desk, a Socket.IO or WebSocket server echoes JSON payloads back and forth, and the demo feels done. Then real users install it: someone steps into an elevator in London, switches from Wi-Fi to 4G in Dubai, backgrounds the app for forty minutes, and opens the thread to find missing messages, duplicated replies, and a frozen unread badge.
Mobile operating systems are hostile to persistent TCP connections. Designing real-time chat for Android and iOS means engineering for disconnection as the normal state, not an edge case.
Build vs. Buy Economics for Business Messaging
Before writing a socket server, decide whether owning the chat stack creates real leverage:
| Approach | Upfront Cost | Scaling Economics | Data & Workflow Control | Best Fit |
|---|---|---|---|---|
| Managed Chat SDK | Low (days to integrate) | Per-MAU + concurrent socket tiers climb sharply | Limited to vendor webhooks and UI hooks | Simple customer support or non-core chat |
| Custom Mobile + Backend | Moderate (2–4 week core build) | Predictable infra cost (Redis + Postgres + workers) | Full control over compliance, custom cards, and retention | Marketplaces, telehealth, logistics, fintech |
If messaging is the operational backbone—dispatch updates, clinical notes, escrow approvals, or multi-party workflows—owning the schema and delivery pipeline pays for itself quickly.
Core Data Model: Sequence IDs and Idempotency
Never rely on device wall-clock timestamps (Date.now()) to order chat history. Phone clocks drift, and two users sending messages within milliseconds create non-deterministic ordering.
Instead, assign a server-generated per-conversation sequence number (seq_id) paired with a client-generated UUID (client_msg_id):
CREATE TABLE conversations (
id UUID PRIMARY KEY,
last_seq_id BIGINT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE messages (
id UUID PRIMARY KEY,
conversation_id UUID NOT NULL REFERENCES conversations(id),
sender_id UUID NOT NULL,
client_msg_id UUID NOT NULL,
seq_id BIGINT NOT NULL,
message_type VARCHAR(24) NOT NULL DEFAULT 'text',
body TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (conversation_id, sender_id, client_msg_id),
UNIQUE (conversation_id, seq_id)
);
CREATE TABLE conversation_participants (
conversation_id UUID NOT NULL REFERENCES conversations(id),
user_id UUID NOT NULL,
last_read_seq_id BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (conversation_id, user_id)
);
Notice two critical efficiencies here:
UNIQUE (conversation_id, sender_id, client_msg_id)makes retries safe. If the client loses signal before receiving anACKand resends the payload, PostgreSQL returns the existing row instead of duplicating the bubble.last_read_seq_idreplaces storing millions of per-message read-receipt rows. Calculating unread counts becomes a single integer subtraction:conversation.last_seq_id - participant.last_read_seq_id.
Multi-Instance Socket Fan-Out with Redis Pub/Sub
A single WebSocket server hits file-descriptor or deployment limits quickly—restarting the process drops every connected user. Place stateless WebSocket gateway nodes behind a load balancer and connect them with Redis Pub/Sub (or Redis Streams for durable worker handoff).
// Message send handler (Node.js / Fastify WebSocket + PostgreSQL + Redis)
async function handleIncomingMessage(senderId: string, payload: IncomingMsg) {
const saved = await db.transaction(async (trx) => {
const conv = await trx('conversations')
.where({ id: payload.conversationId })
.increment('last_seq_id', 1)
.returning('last_seq_id')
.first();
const [msg] = await trx('messages')
.insert({
id: crypto.randomUUID(),
conversation_id: payload.conversationId,
sender_id: senderId,
client_msg_id: payload.clientMsgId,
seq_id: conv.last_seq_id,
body: payload.body,
})
.onConflict(['conversation_id', 'sender_id', 'client_msg_id'])
.merge({ body: payload.body }) // no-op return existing row
.returning('*');
return msg;
});
// 1. Broadcast to any online socket node holding participants
await redisPub.publish(
`conv:${payload.conversationId}`,
JSON.stringify({ event: 'message.created', data: saved })
);
// 2. Enqueue push notification check for offline/backgrounded recipients
await pushQueue.add('notify-offline-participants', {
conversationId: payload.conversationId,
messageId: saved.id,
seqId: saved.seq_id,
});
return saved;
}
Wait—spot a subtle concurrency risk in high-volume group chats? If increment('last_seq_id', 1) locks the conversations row briefly inside the transaction, it guarantees gapless sequential IDs per room without race conditions, while onConflict preserves strict idempotency on client retries.
Client-Side State: SQLite Cache + Gap Detection
Whether you build the mobile client in Flutter (Drift + Impeller) or React Native (op-sqlite + New Architecture), follow these rules on the phone:
- Optimistic UI with status states: Write outgoing messages to local SQLite immediately with
status = 'sending'and render them instantly. Once the serverACKarrives withseq_id, update the row tostatus = 'sent'. - Foreground delta sync: When the app returns from background or reconnects its WebSocket, look up
MAX(seq_id)in local SQLite for active threads and hitGET /api/v1/conversations/:id/messages?after_seq=412. Never refetch the entire chat history on every reconnect. - Avoid rendering bottlenecks: Chat lists invert vertically and contain mixed media heights. Follow Flutter performance best practices or inspect the React Native architecture overview for synchronous layout sizing so scrolling through thousands of historical bubbles never janks.
Background Delivery: Bridging Sockets to FCM & APNs
iOS suspends background sockets almost immediately after the user presses home; Android Doze mode throttles persistent connections within minutes. Your offline push worker bridges the gap:
- Maintain an ephemeral Redis presence key (
presence:user:{id}, TTL 45 seconds, refreshed via WebSocket ping/pong). - When a message arrives, the background queue checks recipient presence.
- Only users without an active foreground socket receive an APNs / FCM push notification containing
conversation_id,seq_id, and a notification preview. - Keep sensitive payloads encrypted or minimal in push notifications if you operate in regulated industries—fetch the full body over TLS when the Notification Service Extension (iOS) or FirebaseMessagingService (Android) wakes up.
If your product pairs mobile chat with a web dashboard or subscription tier, see our case study on web subscriptions for mobile SaaS or explore our mobile app development services.
Build Custom Mobile Messaging with SmitDev
At SmitDev, I help startups and growing businesses engineer real-time mobile features—from WebSocket gateways and local SQLite sync engines to compliant media storage and push pipelines—without locking your roadmap into expensive third-party messaging seats.
You can validate your real-time architecture in a launch consulting sprint, or embed dedicated full-stack mobile engineering at $55/day (8–9 focused hours) or $1,999/month. Need UK or European overlap? Review our UK developer hiring model or contact us to walk through your messaging requirements.