How to Create a Messaging App: Architecture and Cost
A messaging app looks like three simple screens and operates like a distributed database underneath. Here is how to engineer WebSocket and MQTT connections, ULID idempotency, Signal Double Ratchet vs RFC 9420 MLS encryption, SQLite FTS5 sync, and 2026 costs.

On this page

How to create a messaging app looks like an easy question, because the interface is small: a conversation list, a thread of bubbles, and a text input bar. Underneath sits a distributed state-synchronization engine. Every message has to cross flaky cellular handoffs and tunnel dropouts, land in the recipient's inbox exactly once, keep its order across multiple devices, and wake a suspended phone without draining the battery.
At Idealogic, our engineers build high-concurrency real-time products across our social and creator economy practice and shipped the Ugreator platform. We treat chat app development as storage, cryptography, and protocol work first, with the screens after. If you're working out how to make a messaging app that holds up on bad networks, this guide covers the 2026 production architecture: persistent connection gateways, ULID idempotency and ordering, Signal Protocol vs IETF RFC 9420 (MLS) end-to-end encryption, on-device SQLite FTS5 search, push wakeups, and development budgets.
The short version
- Delivery guarantees rely on client ULIDs and server sequence numbers: Clients generate a UUIDv7 (RFC 9562) or ULID idempotency key before sending so retries never create duplicate bubbles, while the server assigns a per-conversation monotonic sequence integer to establish canonical order.
- Persistent sockets handle foreground speed; APNs and FCM handle the background: Active apps communicate over IETF RFC 6455 WebSockets or MQTT with exponential backoff and full jitter, while backgrounded apps rely on APNs Notification Service Extensions and FCM high-priority data pushes.
- Match encryption to group size and product requirements: Use TLS plus encryption at rest for B2B apps requiring server-side search and compliance, Signal Protocol (X3DH + Double Ratchet) for 1:1 and small private groups, and IETF RFC 9420 (MLS) for encrypted groups scaling past 1,000 members.
- Large channels flip from fan-out-on-write to fan-out-on-read. Direct messages and small groups push message pointers into each member's inbox at write time, whereas 100,000-member broadcast channels store the message once and read by cursor.
- Media stays out of the socket, and search runs on the device. Photos, voice notes, and videos upload out-of-band via AES-256-GCM encrypted chunks to S3/R2 object storage, while local SQLite WAL databases with FTS5 power instant offline search.
- A focused messaging app MVP typically runs $55k to $110k, or $120k to $220k with E2EE: Cross-platform React Native or Flutter clients paired with a Go, Rust, or Elixir gateway ship in 10 to 16 weeks for standard chat and 16 to 26 weeks with multi-device E2EE.
Transport for chat app development: WebSockets, MQTT, and reconnection
Standard HTTP request-response polling wastes radio power and introduces multi-second delays because the server cannot push frames to a client unprompted. A real-time messaging app holds a stateful, full-duplex transport connection open whenever the app is in the foreground.
Separating durable state from ephemeral signals
Routing every real-time event through the same database pipeline is an easy mistake to make early. Traffic on a messaging socket divides into two categories with opposite storage rules:
- Durable state (Messages, edits, reactions, read watermarks): Must be persisted to disk (PostgreSQL, ScyllaDB, or Cassandra) before the server returns an acknowledgment frame.
- Ephemeral state (
typing_started,online_presence, live waveform indicators): Describes only the current three-second window. Ephemeral events must never touch disk; they route strictly through in-memory gateway state or Redis Pub/Sub with a short TTL (5 seconds is a common starting point).
Reconnection storms: exponential backoff with full jitter
Mobile sockets die constantly in elevators and Wi-Fi-to-5G handoffs. Worse, after a gateway deploy or load-balancer blip, 100,000 phones attempt to reconnect simultaneously. Clients need capped exponential backoff with full jitter, as described in the AWS Architecture Blog. Before each retry, the client sleeps for a random time between zero and the smaller of the maximum delay and the base delay multiplied by two to the power of the attempt number. With T_base = 500 ms and T_max = 30 s, reconnect attempts spread evenly across a widening window instead of spiking in lockstep.
How to make a messaging app deliver each message once: ordering, idempotency, and receipts
Users judge a messaging app by one contract. When I tap send on a subway train with one bar of signal, my message can't vanish, can't appear twice, and has to land in the right chronological slot.
1. Achieving effectively-once delivery via client ULIDs or UUIDv7
Suppose a user sends "See you at 8pm", the server writes the message, and the train enters a tunnel before the ACK packet arrives. The client must retry when signal returns.
If the server assigns message IDs on arrival, that retry creates a duplicate bubble. Instead, the client generates a time-ordered 128-bit identifier before the first network attempt using a ULID or IETF RFC 9562 UUIDv7 (embedding a 48-bit Unix millisecond timestamp plus random bits, so B-tree inserts stay mostly sequential and fragment far less than with random UUIDv4). The server enforces a unique constraint on (conversation_id, client_message_id). When the retry arrives, the database skips the duplicate write (ON CONFLICT DO NOTHING) and re-sends the original SERVER_ACK.
2. Why client timestamps fail for ordering, and how conv_seq fixes it
Never sort a chat thread by the sender's device clock (sent_at). Phone clocks drift by seconds or minutes, so if Alice's clock is 45 seconds behind Bob's, her replies render above the questions Bob just asked.
Canonical ordering requires a per-conversation monotonic sequence integer (conv_seq) assigned atomically by the server (1, 2, 3, ...). While a message waits in the sender's offline outbox, the UI renders it at the bottom in a pending state (conv_seq = null). Once the server ack returns { client_msg_id, conv_seq: 482, server_ts }, the client slots the message into position 482.
3. The four-stage receipt state machine and watermark compression
Every message transitions through four explicit states:
PENDING(Clock icon): Written to the sender's local SQLiteoutboxtable in WAL mode; awaiting socket availability.SENT(Single checkmark): Committed to the server's durable log;conv_seqassigned and returned.DELIVERED(Double gray checkmark): Pushed to at least one recipient device over the socket or background push extension, which emitted aDELIVERY_ACK.READ(Double blue/amber checkmark): The recipient scrolled pastconv_seq: 482, emitting a single conversation read watermark ({ user_id, conversation_id, last_read_seq: 482 }) that marks all messages up to482read in O(1) space.
The difference between a demo chat app and a production messenger shows up inside an elevator. If your client generates a UUIDv7 before touching the network, writes to a local SQLite outbox first, and reconciles order via server sequence cursors on reconnect, the user never notices the network dropped at all.
Messaging app encryption (E2EE): Signal Double Ratchet vs IETF MLS (RFC 9420)
The short answer: use transport encryption when you need server-side search, the Signal Protocol for 1:1 and small private groups, and MLS for large encrypted groups.
Standard transport encryption (TLS 1.3 in flight plus AES-256 at rest) protects data from network attackers while preserving server-side search, AI summarization, and compliance archiving. End-to-end encryption (E2EE) guarantees that only client devices hold decryption keys; your servers relay opaque ciphertext. Private consumer messengers, healthcare, and executive comms need E2EE, but it removes server-side search and requires multi-device key provisioning plus encrypted key backups (PIN-derived HSM vaults or passkeys).
1:1 and small-group E2EE: The Signal Protocol (X3DH + Double Ratchet)
For 1:1 chats and small groups, the usual choice is the Signal Protocol: X3DH session setup, which Signal has since extended with the post-quantum PQXDH, plus the Double Ratchet:
- Asynchronous Session Setup via X3DH: On registration, Bob uploads a Pre-Key Bundle to the key server: his Identity Key (IK_B), Signed Pre-Key (SPK_B), and single-use One-Time Pre-Keys (OPK_B). Alice fetches a bundle and derives a shared root key (SK) immediately even while Bob's phone is off.
- Per-Message Forward Secrecy and Post-Compromise Security via Double Ratchet: Every message advances a symmetric KDF Ratchet (deriving a single-use message key deleted immediately after decryption for forward secrecy), while every round-trip reply carries a new Diffie-Hellman key that advances the DH Ratchet (providing post-compromise healing).
- Small Groups via Sender Keys: With Sender Keys (the approach WhatsApp uses for groups), each sender distributes a symmetric chain key to the group over pairwise E2EE sessions. The catch is that whenever a member leaves or is removed, every remaining member has to rotate and redistribute their Sender Key (O(N) complexity).
Large-group E2EE (1,000+ members): IETF RFC 9420 Messaging Layer Security (MLS)
When an encrypted group scales to 1,000 or 50,000 members with frequent membership churn, O(N) pairwise Sender Key rotation stalls clients. The IETF standardized RFC 9420 (Messaging Layer Security / MLS), built atop IETF RFC 9180 (Hybrid Public Key Encryption / HPKE):
- MLS places every member device at the leaf of a binary cryptographic tree (TreeKEM), where interior nodes hold keys shared by their subtree.
- When a member joins, leaves, or rotates keys in a 4,096-member group, the commit message only encrypts new path secrets along about 12 path levels to the root (log2 of 4,096), versus up to 4,095 pairwise operations.
Multi-device sync, fan-out architecture, and local SQLite FTS5 search
Users expect to start a message on an iPhone, switch to a laptop or browser, and see read states, drafts, and search results stay in lockstep.
Inbox fan-out: write-time vs read-time hybridization
- 1:1 and bounded groups (Fan-out on write): Each user or E2EE device maintains a per-device Sync Log (
device_inbox_events) indexed byuser_sync_seq. Sending to a 15-person group appends the event to all 15 sync logs. Reconnecting after an airplane flight requires one delta query (GET /sync?after_seq=19402) to replay every missed message, edit, reaction, and deletion in order. - Large broadcast channels (Fan-out on read): Posting to a 200,000-member channel cannot write 200,000 inbox rows. Above roughly 500 members (a common starting point), store the message once in the channel partition (
(channel_id, conv_seq)), push a lightweight pub/sub notice to online subscribers, and let offline members fetch the channel tail on demand.
Local storage and on-device full-text search with SQLite FTS5
Production mobile clients treat on-device SQLite as the primary UI data source:
- Enable WAL (Write-Ahead Logging) mode (
PRAGMA journal_mode = WAL;) so background sync writes rarely block 120 fps scrolling. Readers keep running during a write, though SQLite still serializes writers. - Index decrypted text in a virtual SQLite FTS5 table. Keep only the plaintext body in the searchable column, leave the conversation and message IDs unindexed, and use the
unicode61tokenizer with diacritics removed so accented queries still match. - Encrypt the SQLite file with SQLCipher (AES-256), storing the master key in the iOS Keychain (
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly) or Android Keystore, consistent with OWASP MASVS (MASVS-STORAGE).AfterFirstUnlockThisDeviceOnlylets background push extensions decrypt incoming messages while the screen is locked.
Out-of-band encrypted media attachments
Don't push 10 MB photos or voice notes through WebSocket or MQTT brokers. The client encrypts the file locally with an ephemeral 256-bit AES-GCM key (K_file), uploads the ciphertext directly to S3 or Cloudflare R2 via a pre-signed URL, and sends a 300-byte chat message containing { blob_url, file_key, iv, sha256_hash, blurhash_preview, dimensions } inside the Signal/MLS ciphertext. If your app expands into live video rooms or conversational Voice AI calls, that pipeline connects directly into the architectures we cover in how to build a live streaming app and our LiveKit vs Agora WebRTC comparison.
Push wakeups, battery budgets, and UGC compliance
Because iOS and Android suspend background sockets, reaching offline users relies on platform push services (and if your product also orchestrates multi-channel digests, in-app bell feeds, and email fallbacks, see our Knock vs Novu notification infrastructure guide):
- iOS APNs: Send an alert push with
"mutable-content": 1and"apns-priority": "10"to wake the Notification Service Extension. It gets about 30 seconds and a tight memory limit (commonly cited as roughly 24 MB, though Apple doesn't document a figure) to advance the ratchet in the shared App Group SQLCipher database, update FTS5, and display the decrypted banner. A payload without analertdictionary won't trigger the extension. - Android FCM: Send a high-priority data push (
"priority": "high") to wakeFirebaseMessagingService, decrypt locally, and post the result to theMessagingStylenotification channel. High priority is meant for time-sensitive messages the user actually sees, and FCM may deprioritize apps whose high-priority messages don't end in a visible notification.
App store UGC rules, battery-aware presence, and E2EE moderation (Message Franking)
Encryption doesn't exempt a chat app from store review. Apple's App Store Review Guidelines (Section 1.2) require apps with user-generated content to filter objectionable material, offer a report mechanism with timely responses, let users block abusive users, and publish contact information. Google Play's User-Generated Content Policy sets comparable moderation requirements. The EU Digital Services Act (Regulation (EU) 2022/2065) adds notice-and-action duties for hosting services and online platforms, which covers public channels, communities, and profiles. Purely private E2EE chats generally sit outside the online-platform rules, so get a legal read for your specific service.
To verify an abuse report in an E2EE messenger where the server never sees plaintext, production platforms implement cryptographic message franking: when a user taps Report Message, the recipient's client reveals the decrypted plaintext and the franking tag to the moderation queue, and the platform checks that tag against the server's own HMAC. That proves cryptographically that the message was sent as reported, without weakening encryption for any conversation nobody reported. Pair message franking with on-device safety classifiers (Apple's Sensitive Content Analysis framework on iOS, or a bundled TensorFlow Lite model, to blur nudity in unsolicited DM attachments, a pattern we also cover in dating app development) and server-side graph rate limits that throttle accounts trying to open, say, 30 new 1:1 threads per minute.
Presence indicators (online now, last seen 4m ago) have to fit the same mobile battery budget. Holding a background socket open just to paint a green dot wastes it. Clients emit a lightweight heartbeat only while foregrounded (every 30 seconds is a common starting point), and the gateway only broadcasts presence changes to users who currently have that contact's thread or conversation list open on screen (viewport-scoped presence subscriptions).
2026 messaging app development cost and build-vs-rent math
A production messaging app typically costs $55,000 to $110,000 for a focused MVP and $120,000 to $220,000 with end-to-end encryption in 2026. Rates drive most of that spread. For context, Eurostat (lc_lci_lev) puts 2025 average hourly labor costs at €34.9 in the EU and €38.6 in the euro area, with €47.9 in the Netherlands and €51.7 in Denmark. Those are whole-economy averages, before senior engineering overhead and security tooling. In our experience, senior Central and Eastern European teams bill at $50 to $85 per hour in 2026, well below typical US agency rates.
For how chat fits into a broader social network or creator platform budget, see our breakdown of social media app development cost and creator monetization platforms. The broader product picture is in our guide to building a social media app.
Build vs rent: when to build a chat app backend instead of a managed SDK
Renting a managed chat API such as Stream Chat or Sendbird lets you ship auxiliary marketplace, ride-share, or telehealth chat in weeks, not months, for roughly $400 to $2,500 per month based on Monthly Active Users (MAU). For line-item 2026 pricing tiers, Peak Concurrent Connection limits, and 36-month graduation math across those providers, see our Sendbird vs Stream comparison. Building your own messaging core through a custom software development or product development partner makes sense when:
- Messaging is the core product or retention loop, and vendor rate limits, webhook latency, or rigid message schemas block your product roadmap.
- True End-to-End Encryption is required, since standard managed chat APIs terminate plaintext on their servers to index messages and fire server-side webhooks.
- Active scale passes roughly 25,000 to 50,000 MAU. Plans at that size are custom-quoted, and the bill can approach $10,000 a month. A basic dedicated Go, Rust, or Elixir WebSocket cluster can start around $600 to $1,200 in monthly cloud spend at moderate concurrency, before ops time and bandwidth. Concurrency and fan-out drive that number more than MAU does.
Rent Sendbird or Stream if chat is a side feature in a marketplace MVP. Build your own WebSocket and SQLite sync engine if messaging is the reason users open your app, or if end-to-end encryption is part of your trust promise. You cannot bolt zero-knowledge cryptography onto a third-party plaintext SaaS later without a complete rewrite.
Implementation checklist: taking a messaging app to production
Before sprint one of chat app development starts, check that your technical specification answers these six architectural questions:
- Lock the idempotency and ordering contract: Generate RFC 9562 UUIDv7 or ULID keys on the client before queuing to the local SQLite outbox, and sort threads strictly by the server-assigned
conv_seqinteger rather than device clocks. - Isolate ephemeral state from durable storage: Route typing indicators and online heartbeats through in-memory pub/sub with short TTLs; persist only messages, reactions, and
last_read_seqwatermarks to your database. - Pick your encryption model on day one: Choose TLS + encryption at rest if you need server-side search and admin visibility; choose Signal X3DH + Double Ratchet for 1:1 and small private groups; choose IETF RFC 9420 MLS if encrypted groups must scale past 1,000 members.
- Architect the local database for locked-screen wakeups: Run on-device SQLite in WAL mode with FTS5 full-text indexing, encrypted via SQLCipher with the key stored under
AfterFirstUnlockThisDeviceOnlyin iOS Keychain / Android Keystore, consistent with OWASP MASVS. - Keep media bytes off the chat socket: Encrypt photos, voice notes, and videos on the client with ephemeral AES-256-GCM keys and upload directly to S3 or R2 via pre-signed URLs.
- Build App Store UGC moderation before submission: Implement a content filter, single-tap user blocking, message-franking abuse reports, and a published support contact to clear Apple App Store Guideline 1.2. New-thread rate limits aren't a 1.2 requirement, but add them anyway. If you run public channels or communities, check the notice-and-action duties in the EU Digital Services Act too.

CTO and Co-founder at Idealogic. Directing engineering, systems architecture, security, and full-stack delivery across web, mobile, and blockchain.
Frequently asked questions
A production messaging app typically costs $55,000 to $110,000 for a focused 1:1 and small-group MVP with offline sync, push notifications, and transport encryption. Signal Protocol end-to-end encryption, multi-device key provisioning, voice notes, and a moderation console bring the budget to $120,000 to $220,000. Enterprise builds with large MLS encrypted groups and custom media pipelines start at $250,000.
A single-codebase mobile MVP built with React Native or Flutter takes 10 to 16 weeks when it's scoped to 1:1 chat, small groups, read receipts, APNs and FCM push wakeups, and SQLite offline storage. End-to-end encryption with multi-device key sync and encrypted media attachments typically adds 6 to 10 weeks of cryptographic and client storage engineering.
RFC 6455 WebSockets are the best default for consumer and B2B chat app development because they work across web browsers, iOS, Android, and corporate firewalls. Choose MQTT for low-power mobile connections or unstable cellular networks, where small binary headers and built-in QoS 1 delivery acks save battery. Use gRPC or HTTP/3 WebTransport when you multiplex binary streams between microservices.
The client generates a unique, time-sortable ULID or UUIDv7 idempotency key on the device before the first send attempt. It writes the pending message to its local SQLite outbox and reuses that exact ID on every retry. The server enforces a unique constraint on the message ID and drops repeated frames, so an at-least-once network link behaves like effectively-once delivery.
The Signal Protocol sets up sessions with X3DH (now extended by the post-quantum PQXDH) and runs pairwise Double Ratchet chains. That suits 1:1 chats and small groups, but it scales poorly when group membership changes often, because key updates grow linearly with member count. IETF RFC 9420 Messaging Layer Security (MLS) arranges group members in a binary TreeKEM ratchet tree, which cuts key rotation work to logarithmic scale for groups of 1,000+ members.
It runs on the device. The server of an end-to-end encrypted chat app stores only opaque ciphertext, so server-side Elasticsearch or PostgreSQL full-text queries can't work. Each client decrypts incoming messages locally and indexes the plaintext in an on-device SQLite FTS5 virtual table encrypted with SQLCipher. The database master key lives in the iOS Keychain or Android Keystore.
The server never sends plaintext. On Apple APNs it sends an alert push with the mutable-content flag that carries the encrypted ciphertext blob, and on Android FCM a high-priority data message. iOS then wakes a Notification Service Extension for about 30 seconds. The extension loads the ratchet state from shared keychain storage, decrypts the message locally, and renders the plaintext banner. On Android the app decrypts in the background and posts the notification itself.
Rent a managed chat SDK like Stream or Sendbird when chat is a secondary feature inside a marketplace or telehealth app and you have fewer than roughly 25,000 to 50,000 monthly active users. Build a custom messaging backend when messaging is your core product, when you need end-to-end encryption where no vendor holds plaintext, or when your MAU-metered bill approaches $10,000 per month.
More from the journal

How to Build a Live Streaming App: Architecture and Cost
Glass-to-glass latency dictates every decision in live streaming app development: sub-500ms WebRTC for interactive stages, 2 to 4 second LL-HLS for 100k-viewer broadcasts, ABR transcoding ladders, sharded live chat, gifting ledgers, and 2026 infrastructure costs.

Deepgram vs AssemblyAI in 2026: Latency, VAD & ASR TCO
Deepgram vs AssemblyAI and OpenAI Realtime ASR in 2026, compared on engineering and 36-month TCO: Flux native End-of-Turn vs Universal-3.6 Pro Realtime, Nova-3 keyterm prompting, PII audio redaction, silence billing on streaming, Silero VAD, and L4 GPU math.

Knock vs Novu vs Courier in 2026: Notification Infrastructure & TCO
Engineering and 36-month TCO teardown of Knock vs Novu vs Courier in 2026: event vs per-message billing traps, MongoDB self-hosting overhead, PostgreSQL 17 FORCE RLS digest batching, and multi-channel fan-out math.