Open Source IM System Selection and Architecture: A Practical Guide

    This article breaks down the core engineering challenges of building or selecting an open source instant messaging (IM) system: long-lived connection scale, message reliability, and multi-device consistency. It compares custom binary protocols with text-based protocols, covers heartbeat and reconnection strategies, explains the store-and-pull delivery model with idempotency and acknowledgments, and outlines storage separation, multi-device sync, group fan-out trade-offs, security, observability, and a phased evaluation framework for choosing an open source solution.

    1. Why Instant Messaging Needs Its Own Architecture

    Instant messaging (IM) may look like nothing more than sending and receiving messages, but from an engineering perspective it is a system with high concurrency, strong real-time requirements, and tolerance for weak consistency. Compared with typical business systems, it differs in three significant ways:

    1. Massive long-lived connection scale: The server must maintain a huge number of TCP/WebSocket connections, with memory and file descriptors as the primary bottlenecks.
    2. High message reliability requirements: Messages must not be lost, must not be displayed twice, and must be recoverable after a disconnect.
    3. Complex multi-device consistency: The same account can be logged in on mobile, desktop, and web simultaneously, which requires handling message sync, read receipts, and conversation ordering.

    The open source implementations mentioned in the original text are essentially different trade-offs around these three points. Setting specific projects aside, this article abstracts the problem into a general technical question: how to evaluate and build a maintainable instant messaging system.

    2. Protocol Layer: Custom Binary Protocol vs. General Text Protocol

    The first dividing line in a self-built IM system is usually the communication protocol.

    • Custom binary protocol: A fixed-length header carries fields such as packet length, version, command ID, sequence number, and checksum, while the body uses structured serialization. The advantages are small bandwidth, fast parsing, and easy extension; the drawback is high debugging cost, which requires companion packet capture and parsing tools.
    • General text protocol (such as WebSocket + JSON): Fast to get started and friendly across platforms, suitable for quick validation; the drawback is significant redundancy, with noticeable CPU and bandwidth overhead under high concurrency.

    A simplified header design example:

    1. struct MsgHeader {
    2. uint32_t magic; // Magic number for fast validation
    3. uint32_t length; // Total packet length
    4. uint16_t version; // Protocol version, enables gradual upgrades
    5. uint16_t cmd; // Command: login/heartbeat/one-to-one/group/receipt
    6. uint32_t seq; // Client sequence number, used for dedup and ordering
    7. uint32_t reserved; // Reserved for extension
    8. };

    Key practice: the protocol must carry a version number. Clients cannot be forced to upgrade all at once, so the server must stay compatible with multiple versions at the same time; otherwise a single release can cause widespread outages.

    3. Connections and Heartbeats: The Foundation of Long-Lived Connection Stability

    The biggest enemy of a long-lived connection is the “fake online” state. NAT timeouts, carrier gateway recycling, and mobile background power saving can all leave a connection that appears to exist but is actually unusable.

    The common approach is a two-layer heartbeat:

    1. Application-layer heartbeat: The client sends a ping at a fixed interval and the server replies with a pong; after N consecutive failures the connection is treated as dropped and reconnected.
    2. Transport-layer keepalive: OS-level keepalive serves as a fallback.

    Reconnection must be paired with exponential backoff plus jitter to avoid an avalanche where all clients flood the server at once after it restarts:

    1. delay = min(base * 2^attempt, max_delay) + random(0, jitter)

    4. Message Delivery Model: Reliable, Ordered, Idempotent

    This is the core of IM. The industry generally adopts a hybrid model of “server-side storage + client pull + long-lived connection push“:

    • Persist on write: The message is written to storage first and assigned a globally unique msg_id before entering the delivery flow.
    • Push only a signal: The long-lived connection only sends a “new message” signal, and the client pulls increments per conversation.
    • Client-side idempotency: Use msg_id or (conversation, seq) as the idempotency key so repeated pushes do not render duplicates.
    • Ack loop: The client sends an ack after successful consumption, and the server maintains an unacknowledged queue and re-delivers based on it.

    Pseudocode:

    1. def on_message(msg):
    2. store.append(msg) # 1. Persist and assign msg_id
    3. seq = bump_session_seq(msg.to) # 2. Monotonically increasing within the conversation
    4. notify(msg.to, msg_id, seq) # 3. Push only the signal
    5. wait_ack(msg.to, msg_id, timeout=5s) # 4. Re-deliver on timeout

    Ordering is usually guaranteed at the conversation level: strictly increasing within a single conversation, with no promise of global ordering across conversations. This satisfies the user experience while still allowing horizontal scaling.

    5. Storage Design: Store Three Kinds of Data Separately

    Mixing data with different characteristics in one table is the most common beginner mistake. A reasonable split:

    Data type Characteristics Suggested storage
    Message body Write-heavy, read-heavy, large volume Sharded database / object storage + index
    Conversations and recent contacts Frequently updated, small fields High-performance KV or cache
    Users and relationship chains Read-heavy, write-light, strongly consistent Relational database

    Hot and cold separation matters just as much: recent messages go to hot storage for low latency, historical messages are archived to lower-cost storage, and a unified query layer hides the difference.

    6. Multi-Device Sync and Read Receipts

    In multi-device scenarios, the server must maintain an independent sync point for each device. When a device comes online it carries its local sync point, and the server returns the increments after that point. A read receipt is the reverse: a position report. Once a device advances the sync point for a conversation, it broadcasts to the other devices, achieving “read on one device, synced across all devices”.

    Note: the sync point must be monotonic within a conversation; otherwise concurrent reports can cause a rollback and produce the experience bug of “a read message becomes unread again”.

    7. Group and Broadcast Fan-Out Trade-Offs

    Fan-out for a one-to-one chat is 1; fan-out for a group chat is N. In large-group scenarios, pushing message by message amplifies write pressure. Two common approaches:

    • Write fan-out: An incoming group message is stored once per member; fast reads, slow writes, suitable for small and medium groups.
    • Read fan-out: Only one copy is stored and members pull per group; fast writes, slow reads, suitable for very large groups.

    In practice this is usually hybrid: normal groups use write fan-out, very large groups use read fan-out, with separate flag bits controlling @mentions and message do-not-disturb.

    8. Security, Operations, and Observability

    • Transport and storage encryption: Link encryption plus encryption of sensitive fields at rest, with keys managed separately from data.
    • Rate limiting and circuit breaking: Rate limit connection establishment and message sending on both user and IP dimensions to prevent a single point from being flooded.
    • Observability: Connection count, online rate, message latency percentiles, re-delivery rate, and ack timeout rate must be turned into a metrics dashboard, paired with a logging service and monitoring alerts.
    • Elastic deployment: A stateless access layer that scales horizontally with a container platform, with session state externalized to cache, is what makes smooth scale-out and scale-in possible.

    9. Evaluation Framework and Implementation Path

    When evaluating an open source option, score it across six dimensions: protocol openness, multi-device coverage, deployment complexity, extensibility, community activity, and documentation and maintainability. Do not look only at the feature list; more importantly, check whether it lets you replace the storage and access layers.

    A three-stage rollout is recommended:

    1. Usable: One-to-one chat + login + history messages + reconnect, with the ack loop working end to end.
    2. Good to use: Groups, multi-device sync, read receipts, offline push, automatic upgrades.
    3. At scale: Sharded databases, hot and cold separation, hybrid read and write fan-out, full-link monitoring and load testing.

    10. Conclusion

    There is no silver bullet for instant messaging. The value of open source implementations is that they provide a validated architectural skeleton, not a finished product you can drop in. What really determines success is three pieces of foundational work: protocol version compatibility, message idempotency and ordering, and observability. Make those solid, then layer on group and multi-device capabilities step by step — that is the low-risk, evolvable path.