Skip to content

About

A ultra low latency, distributed chat application built using GO

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

Enterprise Real-Time Messaging Platform (ERMP)

A production-oriented, horizontally scalable real-time messaging platform for collaboration, customer-support, live-event and enterprise communication workloads.

ERMP focuses on the hard engineering problems behind large-scale chat systems: long-lived connection management, message ordering, delivery guarantees, fanout, offline sync, multi-device sessions, presence, persistence, search, backpressure, observability and multi-region reliability.

Scope note: performance and scale figures in this document are architectural targets unless backed by benchmark results in this repository. They should not be interpreted as measured production claims.


1. Problem Statement

A basic chat application can be built with WebSockets and a database. A production messaging platform is significantly harder because it must remain correct and responsive under:

  • millions of long-lived connections
  • bursty fanout patterns
  • transient client networks
  • process / broker / region failures
  • duplicate delivery
  • out-of-order arrival
  • offline recipients
  • multi-device users
  • hot conversations
  • large message histories
  • enterprise retention / audit requirements

ERMP separates connection handling, durable messaging, fanout and historical storage so each concern can scale independently.


2. Design Goals

Area Goal
Connections Horizontally scalable long-lived WebSocket sessions
Delivery At-least-once delivery with application-level idempotency
Ordering Deterministic per-conversation ordering
Durability Messages acknowledged as durable only after crossing a defined persistence boundary
Latency Low in-region publish-to-deliver latency
Offline sync Reliable catch-up after reconnect / device changes
Fanout Efficient direct, group and broadcast delivery
Backpressure Protect the system from slow clients and overloaded downstreams
Multi-tenancy Tenant-aware auth, quotas, retention and isolation
Operations Metrics, traces, logs, SLOs and failure recovery
Compliance Audit, retention, export, deletion / legal-hold controls

3. Example Capacity Targets

Illustrative architecture targets:

  • 5–10M concurrent connections globally
  • 200k messages/sec sustained
  • burst handling into significantly higher short-lived throughput
  • p95 in-region delivery latency < 150 ms
  • 99.95% core messaging availability

These numbers drive partitioning and capacity planning; real values must be established through benchmarks.


4. High-Level Architecture

flowchart LR
    C[Web / Mobile Clients] --> EDGE[Global / Regional Edge]
    EDGE --> CM[Connection Manager Pool]

    CM <--> R[(Redis Cluster\nSessions / Presence)]
    CM --> ING[Ingress / Message Service]
    ING --> B[(NATS JetStream / Kafka)]

    B --> PERSIST[Persistence Workers]
    PERSIST --> DB[(Cassandra / Scylla / DynamoDB)]

    B --> FAN[Fanout / Delivery Workers]
    FAN --> CM
    FAN --> PUSH[Push Workers]
    PUSH --> FCM[FCM / APNs]

    B --> IDX[Search Indexer]
    IDX --> ES[(OpenSearch / Elasticsearch)]

    B --> MOD[Moderation Pipeline]
    B --> AUDIT[Audit / Compliance Pipeline]

    EDGE --> CTRL[REST / gRPC Control APIs]
    CTRL --> META[(PostgreSQL Metadata)]

    CM --> OTEL[OpenTelemetry]
    FAN --> OTEL
    PERSIST --> OTEL
Loading

Control plane vs data plane

Data plane

  • persistent connections
  • message publish
  • sequencing
  • broker
  • persistence
  • fanout
  • acknowledgements
  • presence

Control plane

  • authentication
  • conversation lifecycle
  • membership
  • tenant policy
  • retention
  • moderation configuration
  • device management
  • compliance / export APIs

Keeping them separate prevents slower administrative operations from affecting the hot messaging path.


5. Client SDKs

Transport

  • Web: WebSocket as the baseline; WebTransport can be evaluated where browser support and HTTP/3 characteristics materially help.
  • Mobile: native WebSocket for real-time sessions.
  • REST / gRPC: control-plane operations, history pagination, upload initialization and internal service communication.

Protocol

Application messages use Protocol Buffers internally for:

  • compact payloads
  • schema evolution
  • cross-language clients
  • lower serialization overhead than verbose JSON on hot paths

JSON can remain available for debugging or public APIs.

Client responsibilities

The SDK handles:

  • connection establishment
  • heartbeat / health
  • exponential-backoff reconnect
  • jittered retry to prevent reconnect storms
  • local outbound queue
  • optimistic UI state
  • message acknowledgement
  • resend of unacknowledged messages
  • duplicate suppression using message_id
  • gap detection using conversation sequence numbers
  • offline catch-up
  • token refresh
  • device / session identity

Local state machine

Typical outbound state:

LOCAL_PENDING
   -> SENT
   -> SERVER_ACCEPTED
   -> DELIVERED
   -> READ

A client-generated message_id is preserved across retries so a reconnect never creates a logically new message.


6. Edge Gateway

Technology

  • Envoy
  • AWS ALB / NLB depending on connection and routing requirements
  • cloud WAF / DDoS controls where applicable

Responsibilities

  • TLS termination
  • connection admission
  • JWT / OIDC validation
  • tenant / user extraction
  • rate limiting
  • IP / abuse controls
  • connection routing
  • health-aware backend selection
  • protocol upgrades
  • regional routing

The edge should avoid storing durable application state.


7. Connection Manager

Implementation

Go or Rust is appropriate because connection managers need:

  • high concurrent socket counts
  • efficient memory use
  • predictable garbage-collection / allocation behavior
  • low per-connection overhead
  • strong networking primitives

The exact framework is secondary to profiling and operational behavior.

Responsibilities

A Connection Manager (CM):

  • owns active WebSocket connections
  • assigns session_id
  • authenticates session context
  • tracks heartbeat / last activity
  • maintains bounded outbound queues
  • accepts inbound client frames
  • validates protocol envelope
  • forwards publish operations
  • receives routed outbound messages
  • tracks delivery ACKs
  • enforces per-connection flow control
  • disconnects unhealthy / abusive clients

State model

CMs are stateless with respect to durable message history.

Ephemeral socket state necessarily lives in the process, but durable routing information is externalized so a client can reconnect to another node.

Redis may contain:

user_id -> active session IDs
session_id -> connection_manager_id
device_id -> session_id
connection_manager_id -> heartbeat / capacity

Scaling

CM pools scale horizontally.

Routing options include:

  • sticky load balancing
  • consistent hashing
  • least-connections / capacity-aware placement

A reconnect does not require transferring the old TCP connection. The new CM reconstructs session state and uses the durable conversation cursor to fetch missed messages.


8. Session and Presence Store

Technology

Redis Cluster is appropriate for ephemeral routing and presence data.

Key examples

presence:{tenant}:{user}
session:{session_id}
user_sessions:{user_id}
cm:{cm_id}:load

Presence

Presence uses TTL-based leases.

heartbeat received
    -> refresh presence TTL

TTL expires
    -> user/device becomes unavailable

This handles ungraceful disconnects without requiring the client to send a final logout message.

Important distinction

Presence is ephemeral state. It should not be treated as the system of record for message delivery.

Redis Pub/Sub alone is not suitable as the durable message path because subscribers can miss messages during disconnects. Durable delivery flows through the broker / persistence layer.


9. Message Ingress and Broker

Responsibilities

Ingress validates:

  • authentication
  • tenant membership
  • conversation membership
  • payload size
  • message type
  • rate limits
  • idempotency key / message_id

It then obtains ordering metadata and publishes a canonical message event to the durable broker.

Broker choices

NATS JetStream

Strengths:

  • low latency
  • pub/sub ergonomics
  • persistence
  • consumer acknowledgements
  • good fit for real-time messaging

Tradeoffs:

  • different operational ecosystem from Kafka
  • analytics / long-retention ecosystem is not as broad

Kafka

Strengths:

  • extremely mature partitioned log
  • high sustained throughput
  • replay
  • consumer groups
  • ecosystem for downstream analytics

Tradeoffs:

  • operational complexity
  • partition management
  • potentially less attractive latency profile for some real-time workloads

Redis Streams

Useful for smaller deployments and simpler systems, but ERMP does not depend on Redis Streams as its large-scale durable message backbone.

Selection principle

The architecture does not claim that one broker is universally best.

  • Choose NATS JetStream when low-latency messaging and simpler real-time pub/sub semantics dominate.
  • Choose Kafka when retained event history, replay, integration with analytics pipelines and very high sustained throughput dominate.

10. Delivery Semantics

ERMP uses:

At-least-once infrastructure delivery + idempotent application processing

Exactly-once end-to-end delivery across clients, brokers, storage and networks is usually not worth the distributed coordination cost for chat.

Every logical message carries a stable message_id.

A retry therefore means:

same message_id
same logical operation
possibly repeated physical delivery

Consumers and clients deduplicate using the stable identifier.


11. Message Ordering

Messages receive a monotonically increasing seq_no within a conversation.

Why per-conversation sequencing

Global ordering is unnecessary and expensive.

Users care that:

conversation A: 100, 101, 102
conversation B: 54, 55, 56

is ordered independently.

Practical sequencing model

A conversation maps to one ordering partition / logical owner.

The sequencing service or partition owner assigns:

(conversation_id, seq_no)

before publication becomes authoritative.

This allows:

  • deterministic history pagination
  • reconnect gap detection
  • client reordering
  • idempotent persistence

Hot conversations

A single conversation can become a hot partition.

Possible strategies:

  • accept per-conversation throughput limits
  • separate extremely large broadcast channels from ordinary conversations
  • batch reactions / nonessential events
  • use a specialized fanout model for massive channels

Preserving strict order while infinitely scaling one conversation is not a free property; the README makes that tradeoff explicit.


12. Delivery and Fanout Workers

Workers consume broker events and perform recipient delivery.

Responsibilities:

  • resolve current conversation membership
  • route to online sessions
  • enqueue offline notifications
  • update delivery cursors
  • respect blocked / removed users
  • retry transient failures
  • emit delivery telemetry

Direct messages

Fanout is small and can occur immediately.

Group messages

Two broad strategies exist:

Fanout-on-write

Generate recipient delivery work when the message is published.

Good for:

  • small / medium groups
  • fast inbox reads

Cost:

  • write amplification

Fanout-on-read

Store the conversation event once and let clients read based on membership / cursor.

Good for:

  • very large groups

Cost:

  • more complex reads / unread calculations

ERMP can use a hybrid threshold-based strategy.


13. Persistent Message History

Cassandra / ScyllaDB / DynamoDB

The message store is append-heavy and naturally queryable by conversation and sequence.

A wide-column design fits this access pattern.

Cassandra example

CREATE TABLE messages_by_conversation (
    conversation_id UUID,
    bucket INT,
    seq_no BIGINT,
    message_id UUID,
    sender_id UUID,
    message_type TEXT,
    payload BLOB,
    created_at TIMESTAMP,
    edited_at TIMESTAMP,
    reply_to_message_id UUID,
    flags SET<TEXT>,
    PRIMARY KEY ((conversation_id, bucket), seq_no)
) WITH CLUSTERING ORDER BY (seq_no DESC);

Bucketing

An unlimited conversation must not grow as one unlimited Cassandra partition.

bucket can represent:

  • time window
  • sequence range
  • configurable partition size

This avoids oversized partitions while preserving efficient sequential history reads.


14. Core Data Model

Conversation metadata

A relational store such as PostgreSQL is useful for lower-volume strongly consistent metadata.

conversations
-------------
conversation_id
tenant_id
conversation_type
title
created_by
created_at
last_activity_at
retention_policy_id
version

Membership

conversation_members
--------------------
conversation_id
user_id
role
joined_at
left_at
last_read_seq_no
notification_policy

Membership should not be stored as an ever-growing list inside a single Cassandra row for large groups.

Users

users
-----
user_id
tenant_id
display_name
status
created_at

Devices

user_devices
------------
device_id
user_id
platform
push_token
last_seen_at
enabled

Attachments

attachments
-----------
attachment_id
tenant_id
object_key
content_type
size_bytes
checksum
scan_status
created_by
created_at

Message idempotency

A lookup keyed by message_id can be retained for an appropriate deduplication window.


15. API Design

ERMP separates real-time data-plane events from REST/gRPC control-plane APIs.

Create conversation

POST /v1/conversations
Authorization: Bearer <token>
Idempotency-Key: <uuid>
Content-Type: application/json
{
  "type": "group",
  "title": "Platform Engineering",
  "participant_ids": [
    "usr_101",
    "usr_102",
    "usr_103"
  ]
}

Response:

{
  "conversation_id": "conv_123",
  "version": 1,
  "created_at": "2026-09-16T10:00:00Z"
}

Get history

GET /v1/conversations/conv_123/messages?limit=50&before_seq=10501

Cursor / sequence pagination avoids the inconsistency and cost of offset pagination.

Mark read

PUT /v1/conversations/conv_123/read-cursor
{
  "last_read_seq_no": 10492
}

This is more scalable than writing one read_by entry into every message for large conversations.

Add members

POST /v1/conversations/conv_123/members

Remove member

DELETE /v1/conversations/conv_123/members/usr_102

Initialize attachment

POST /v1/attachments
{
  "filename": "architecture.pdf",
  "content_type": "application/pdf",
  "size_bytes": 482910
}

Response:

{
  "attachment_id": "att_123",
  "upload_url": "<short-lived-presigned-url>",
  "expires_at": "..."
}

The binary is uploaded directly to object storage instead of traversing messaging servers.


16. WebSocket Protocol

Envelope

{
  "version": 1,
  "type": "message.send",
  "request_id": "req_123",
  "payload": {}
}

In production, the equivalent structure is serialized using protobuf.

Send message

{
  "version": 1,
  "type": "message.send",
  "request_id": "req_123",
  "payload": {
    "conversation_id": "conv_123",
    "message_id": "0195...",
    "client_timestamp": "2026-09-16T10:10:00Z",
    "content": {
      "type": "text",
      "text": "Deployment completed."
    }
  }
}

Accepted ACK

{
  "version": 1,
  "type": "message.accepted",
  "request_id": "req_123",
  "payload": {
    "conversation_id": "conv_123",
    "message_id": "0195...",
    "seq_no": 10502,
    "server_timestamp": "2026-09-16T10:10:00.043Z"
  }
}

Delivery event

{
  "version": 1,
  "type": "message.deliver",
  "payload": {
    "conversation_id": "conv_123",
    "message_id": "0195...",
    "seq_no": 10502,
    "sender_id": "usr_101",
    "content": {
      "type": "text",
      "text": "Deployment completed."
    },
    "server_timestamp": "2026-09-16T10:10:00.043Z"
  }
}

Delivery receipt

{
  "version": 1,
  "type": "message.delivery_ack",
  "payload": {
    "conversation_id": "conv_123",
    "through_seq_no": 10502
  }
}

Cumulative acknowledgements reduce receipt traffic.

Typing

{
  "version": 1,
  "type": "typing",
  "payload": {
    "conversation_id": "conv_123",
    "state": "started"
  }
}

Typing is best-effort ephemeral traffic and is not persisted to the durable message log.


17. Protobuf Message Structure

syntax = "proto3";

package ermp.v1;

message Envelope {
  uint32 version = 1;
  string type = 2;
  string request_id = 3;
  bytes payload = 4;
}

message ChatMessage {
  string conversation_id = 1;
  string message_id = 2;
  string sender_id = 3;
  uint64 seq_no = 4;

  int64 client_timestamp_ms = 5;
  int64 server_timestamp_ms = 6;

  oneof content {
    TextContent text = 10;
    FileContent file = 11;
    ImageContent image = 12;
    SystemContent system = 13;
  }

  string reply_to_message_id = 20;
  map<string, string> metadata = 21;
}

message TextContent {
  string text = 1;
}

message FileContent {
  string attachment_id = 1;
  string filename = 2;
  string content_type = 3;
  uint64 size_bytes = 4;
}

message ImageContent {
  string attachment_id = 1;
  uint32 width = 2;
  uint32 height = 3;
}

message SystemContent {
  string event_type = 1;
  map<string, string> attributes = 2;
}

Protocol evolution rules:

  • never reuse removed field numbers
  • add fields backward-compatibly
  • use explicit protocol versions for behavioral changes
  • tolerate unknown fields

18. Offline Delivery and Reconnect

A reconnecting client sends its durable cursor for each relevant conversation or sync scope.

Conceptually:

last_confirmed_seq = 10300
server_head_seq    = 10502

The client requests / receives the missing range:

10301 ... 10502

This makes the durable message store, rather than the in-memory CM queue, the source of truth for recovery.

Reconnect storms

Mitigations:

  • exponential backoff
  • random jitter
  • edge admission limits
  • per-tenant connection quotas
  • staged reconnect tokens where necessary

19. Multi-Device Semantics

One user may have multiple active sessions.

user_123
 ├── iPhone
 ├── browser
 └── tablet

Fanout routes the message to all eligible active sessions.

Read state is normally maintained at user/conversation level, while transport delivery acknowledgement remains device/session-specific.


20. Push Notifications

Offline devices are handled through FCM / APNs workers.

Push notifications are hints, not the source of truth.

Payloads should avoid unnecessarily sensitive content.

Flow:

message persisted
   -> recipient has no active session
   -> enqueue notification job
   -> collapse / batch where appropriate
   -> APNs / FCM
   -> device reconnects
   -> durable sync fetches actual message

21. Attachments

Large binary payloads never pass through the broker.

client
 -> request upload
 -> receive presigned URL
 -> upload directly to S3
 -> malware / validation pipeline
 -> send chat message referencing attachment_id

Benefits:

  • avoids broker amplification
  • protects connection managers
  • independent storage lifecycle
  • easier CDN delivery

22. Search and eDiscovery

A search indexer consumes message events asynchronously and writes searchable content to OpenSearch / Elasticsearch.

Supports:

  • full-text search
  • sender / date / conversation filters
  • tenant-isolated indexes / filters
  • compliance export
  • eDiscovery
  • administrator investigations subject to policy

Search is eventually consistent and is not part of the synchronous message delivery path.

If end-to-end encryption is enabled, server-side content indexing may be unavailable by design.


23. Moderation and Abuse Protection

Synchronous checks

Only inexpensive rules should block the hot path:

  • payload limits
  • blocked users
  • tenant policies
  • URL / spam heuristics
  • rate limits

Asynchronous moderation

Higher-cost checks can run after acceptance where product policy allows:

  • toxicity classifiers
  • spam classifiers
  • attachment scanning
  • image moderation
  • abuse analytics

Possible action events:

message.quarantined
message.redacted
message.deleted
account.rate_limited

24. Backpressure

Backpressure exists at several layers.

Client

Bound local outbound queue.

Connection Manager

Bound per-connection send buffers.

If a client cannot consume data:

  1. stop accepting unlimited buffer growth
  2. disconnect the slow session when threshold is exceeded
  3. rely on durable resync when it reconnects

Broker

Monitor consumer lag and partition backlog.

Persistence

Batch writes, control consumer concurrency and slow broker consumption when storage is degraded.

Unbounded queues merely transform overload into memory exhaustion.


25. Security

Authentication

  • OIDC / OAuth2
  • short-lived access tokens
  • tenant / user identity propagated as trusted service context

Authorization

Every publish validates:

user belongs to tenant
user belongs to conversation
user has permission to send this event type

Authorization is never inferred merely from knowing a conversation ID.

Encryption

  • TLS in transit
  • KMS-backed encryption at rest
  • signed, short-lived object-storage URLs
  • secret-manager backed credentials

Optional E2EE

End-to-end encryption can be supported for use cases that require it, but it changes product capabilities:

  • server-side content search becomes difficult / unavailable
  • moderation becomes limited
  • compliance / eDiscovery semantics change
  • multi-device key management becomes substantially more complex

E2EE is therefore a product/security decision rather than a default checkbox.


26. Multi-Tenancy and Enterprise Controls

Tenant policies can configure:

  • rate limits
  • maximum attachment size
  • retention period
  • moderation policy
  • feature flags
  • geographic / data-residency restrictions
  • export rights
  • legal holds
  • storage quotas

Tenant identity is present in authorization and storage/index partitioning decisions.


27. Audit and Compliance

Audit logs record administrative and security-sensitive actions, such as:

  • conversation creation / deletion
  • membership changes
  • message deletion requests
  • exports
  • legal hold actions
  • moderation actions
  • policy changes

Audit data is logically separated from ephemeral application logs.

Retention

Retention is policy-driven.

Possible behavior:

active retention window
 -> expire message history
 -> remove search index copy
 -> delete attachments
 -> preserve items under legal hold

28. Observability

OpenTelemetry carries a trace context through:

client ingress
 -> sequencing
 -> broker publish
 -> persistence
 -> fanout
 -> connection manager delivery

Core metrics

Connections

  • active connections
  • connection rate
  • reconnect rate
  • disconnect reasons
  • heartbeats missed

Messaging

  • messages/sec
  • publish latency
  • persistence latency
  • delivery latency
  • duplicate rate
  • retry rate
  • fanout size

Broker

  • partition / stream lag
  • consumer lag
  • redeliveries
  • storage utilization

Database

  • write latency
  • read latency
  • timeout rate
  • hot partitions
  • compaction pressure

Business / tenant

  • messages by tenant
  • storage consumption
  • throttled requests
  • active users

Prometheus / Grafana provide metrics and dashboards; structured logs can flow to ELK / OpenSearch.


29. Reliability and Failure Scenarios

Connection Manager crashes

Clients reconnect to another CM.

No durable messages are lost because CMs are not the durable source of truth.

Redis unavailable

Existing sockets can continue for a bounded period, while new presence/routing operations degrade. Circuit breakers prevent Redis failures from cascading through every component.

Persistence worker fails

Broker retains unacknowledged messages and another worker can continue.

Duplicate broker delivery

Idempotency prevents duplicate logical messages.

Client ACK lost

Client retries with the same message_id; server returns the existing accepted result rather than creating a new message.

Region unavailable

Multi-region deployments use regional failover, but failover semantics depend on consistency requirements. Cross-region replication is not assumed to be magically synchronous.


30. Multi-Region Architecture

A practical design keeps users primarily attached to a nearby home / active region.

Global DNS / traffic manager
       |
  +----+----+
  |         |
Region A  Region B

Each region owns:

  • edge
  • connection managers
  • regional presence
  • broker capacity
  • delivery workers

Durable data is replicated according to the chosen data store and RPO/RTO requirements.

Cross-region conversations

Possible strategies:

  • conversation has a home region
  • writes route to the home region
  • remote recipients receive replicated / forwarded events

This avoids attempting globally synchronous ordering across arbitrary writers.


31. Capacity Planning

Capacity must be measured rather than asserted.

Connection memory

Estimate:

total memory ≈ active_connections × memory_per_connection

Then add:

  • runtime overhead
  • kernel socket buffers
  • TLS state
  • outbound buffers
  • application metadata

File descriptors

Hosts must be configured for sufficient:

  • file descriptors
  • TCP backlog
  • ephemeral resources
  • network bandwidth

Broker partitions / streams

Partition count should account for:

  • peak throughput
  • consumer concurrency
  • expected hot-key distribution
  • replication factor
  • failover capacity

32. Testing Strategy

Unit tests

  • protocol validation
  • ACL rules
  • idempotency
  • sequence logic
  • retry state machine

Integration tests

client -> ingress -> broker -> store -> fanout -> client

Failure tests

  • kill connection manager
  • duplicate broker events
  • Redis timeout
  • broker leader failover
  • DB throttling
  • delayed persistence
  • reconnect storms

Load tests

Use k6 plus custom WebSocket load generators for:

  • connection ramp
  • reconnect rate
  • direct-message load
  • group fanout
  • hot conversation
  • history reads

Metrics reported from benchmarks should include hardware and configuration so results are reproducible.


33. CI/CD and Infrastructure

A practical stack can include:

  • Docker
  • Kubernetes
  • Terraform
  • Helm
  • GitHub Actions
  • AWS / Azure / GCP
  • managed Cassandra-compatible / Kafka / Redis services where operationally appropriate

Deployment behavior

Connection-manager deployments use graceful draining:

mark node unavailable
 -> stop accepting new sessions
 -> allow existing connections to drain
 -> ask remaining clients to reconnect
 -> terminate node

This prevents ordinary deployments from becoming reconnect storms.


34. Key Engineering Tradeoffs

WebSocket vs WebTransport

WebSockets are mature and universally practical. WebTransport provides HTTP/3 capabilities but should be adopted based on actual client/platform requirements rather than novelty.

Kafka vs NATS JetStream

Kafka provides a powerful durable log and broad ecosystem. NATS JetStream can provide attractive low-latency messaging semantics. Selection depends on workload, retention and operational requirements.

Cassandra / Scylla vs relational DB

A relational database is excellent for control-plane metadata. Wide-column stores are more natural for extremely high-volume append-oriented message history.

At-least-once vs exactly-once

At-least-once with idempotency is operationally realistic. End-to-end exactly-once across network boundaries would create significant coordination complexity for limited product value.

Fanout-on-write vs fanout-on-read

Write fanout gives fast recipient reads but amplifies writes. Read fanout avoids extreme write amplification for huge groups but makes reads and unread state more complex.

Strict order vs scale

Per-conversation order is valuable. Global order is unnecessary. Extremely hot conversations remain constrained by their ordering boundary.

E2EE vs enterprise search / compliance

The stronger the server is prevented from reading content, the fewer server-side search, moderation and compliance features are possible. The correct choice depends on the product's threat model.


35. Example End-to-End Message Flow

Alice sends a message to a group.

  1. Alice's SDK creates a UUID/ULID message_id.
  2. Client optimistically renders the message as pending.
  3. WebSocket frame reaches the regional Connection Manager.
  4. CM authenticates the session and forwards the command to ingress.
  5. Ingress verifies conversation membership and rate limits.
  6. Ordering owner assigns the next conversation seq_no.
  7. Canonical event is appended to the durable broker.
  8. Persistence worker stores the message idempotently.
  9. Server emits the acceptance acknowledgement to Alice.
  10. Fanout worker resolves recipients.
  11. Online sessions receive message.deliver.
  12. Offline devices receive a push hint.
  13. Clients acknowledge delivered sequence ranges.
  14. Search / analytics consumers process the event asynchronously.
  15. Reconnecting clients can recover any missing sequence range from durable history.

36. Technology Summary

Layer Technologies / patterns
Client WebSocket, optional WebTransport, Protobuf
Edge Envoy, ALB/NLB, WAF
Connection service Go / Rust
Presence Redis Cluster
Durable eventing NATS JetStream or Kafka
Message history Cassandra / Scylla / DynamoDB
Metadata PostgreSQL
Attachments S3 / compatible object storage
Search OpenSearch / Elasticsearch
Push APNs / FCM
Observability OpenTelemetry, Prometheus, Grafana, ELK/OpenSearch
Infrastructure Docker, Kubernetes, Terraform, Helm, GitHub Actions

37. Why This Is More Than a Chat Demo

A toy chat application is typically:

WebSocket -> application server -> database

ERMP treats messaging as a distributed-systems problem:

  • independently scalable connection layer
  • durable broker
  • explicit delivery semantics
  • idempotency
  • per-conversation sequencing
  • hot-partition awareness
  • multi-device sessions
  • offline sync
  • direct-to-object-store attachments
  • hybrid fanout strategies
  • flow control / backpressure
  • full observability
  • retention / compliance
  • multi-region failure semantics
  • benchmark-driven capacity planning

The central engineering principle is that real-time delivery may be ephemeral, but correctness and recovery must be based on durable state.

About

A ultra low latency, distributed chat application built using GO

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages