HomeBlogHow to Build a Real-Time Chat...

Engineering Guide · 9 min read · September 9, 2026

How to Build a Real-Time Chat Application for Android and iOS

Building a mobile chat prototype with WebSockets takes hours, but shipping reliable messaging across iOS and Android background states requires sequence-ordered storage, Redis pub/sub fan-out, local SQLite caches, and smart push fallbacks. Here is the production blueprint.

Author
Smit Desai
Published
September 9, 2026
Read time
9 min read
Topic
Mobile Apps
Services
Custom Web · Mobile Apps · All Services

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:

  1. UNIQUE (conversation_id, sender_id, client_msg_id) makes retries safe. If the client loses signal before receiving an ACK and resends the payload, PostgreSQL returns the existing row instead of duplicating the bubble.
  2. last_read_seq_id replaces 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 server ACK arrives with seq_id, update the row to status = '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 hit GET /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:

  1. Maintain an ephemeral Redis presence key (presence:user:{id}, TTL 45 seconds, refreshed via WebSocket ping/pong).
  2. When a message arrives, the background queue checks recipient presence.
  3. Only users without an active foreground socket receive an APNs / FCM push notification containing conversation_id, seq_id, and a notification preview.
  4. 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.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Cross-Platform & Native

Mobile App Development Services

Production iOS and Android apps built with Flutter, React Native, Swift, and Kotlin alongside scalable Laravel/Node backends.

Interactive Tool · Estimate Scope

Mobile App Cost Estimator

Calculate week-by-week scope for customer apps, offline sync, push notifications, and App Store / Google Play launches.

01 — Frequently asked questions

mobile apps

Why do mobile WebSockets drop when the app goes to the background?

Both iOS and Android aggressively suspend background sockets within seconds to preserve battery. Production chat apps keep WebSockets open only while foregrounded and switch to FCM/APNs push notifications plus delta sync on app resume.

Should businesses build custom chat or buy a hosted SDK?

Buy a hosted SDK when chat is a minor support widget and you do not mind per-MAU pricing scaling with user growth. Build custom when messaging ties tightly into transactions, compliance auditing, HIPAA/GDPR data residency, or custom workflow cards.

How do you prevent duplicate messages or out-of-order chats?

Attach a client-generated UUID (`client_msg_id`) for idempotent server deduplication, and assign a monotonically increasing per-conversation `seq_id` on the server so clients detect gaps and backfill reliably.

What does it cost to build custom mobile chat with SmitDev?

Dedicated senior engineering is available at $55/day for 8–9 hours of daily work or $1,999/month for full-cycle delivery, letting businesses own their messaging infrastructure without recurring per-seat SDK fees.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.