Self-Destructing Chat Messages: System Architecture
System DesignModel answerLast updated
Build a messaging platform where messages automatically vanish after being read, supporting multiple devices, offline scenarios, and abuse prevention.
Problem Context
You're building a privacy-focused messaging platform where users can send one-on-one messages that automatically delete themselves after the recipient reads them. The platform needs to work seamlessly across phones, tablets, and computers, handle spotty internet connections gracefully, and still allow users to flag harmful content.
Core Requirements
What the System Must Do
- Auto-deletion modes: Messages should either vanish the moment they're closed, or remain visible for a countdown period (configurable between 5-60 seconds) that starts when first opened
- Device synchronization: When someone reads a message on their phone, it should disappear from their laptop and tablet too—and the sender should see it's been read everywhere
- Network resilience: Devices going offline and coming back online should catch up correctly without showing already-deleted messages or missing read status
- Content reporting: Recipients need a mechanism to flag abusive messages even though the content is designed to self-destruct
- Silent notifications: New message alerts shouldn't expose content through Apple or Google's notification infrastructure
Performance & Reliability Targets
- Response time: Under 200 milliseconds for message delivery when recipients are online
- Uptime: The system should maintain 99.99% availability
- Deletion integrity: Once marked as read and expired, message content must be permanently removed from servers
- Realistic limitations: Acknowledge what the system cannot prevent (screenshots, camera photos, hacked clients)
Usage Scale
Assume the platform serves:
- 50 million people using it daily
- Each person sends roughly 40 messages per day (approximately 2 billion messages daily, peaking at 75,000 messages per second)
- Typical user has 2-3 active devices connected to their account
Design Considerations
Your architecture should address:
- System layout: Which components handle sending, storage, delivery, and deletion? How do clients maintain persistent connections?
- Authority and timing: Who decides when the countdown starts—the client or server? How do you synchronize this across devices?
- Storage strategy: How do you model message states? Which database technology supports automatic expiration? How do you guarantee permanent deletion?
- Edge case handling: What happens when messages arrive out of order? When a device reconnects mid-countdown? How can you enable abuse reports without keeping plaintext?
Hints
Hint 1
Think about who should own the timer—pure client-side won't sync devices, pure server-side adds latency. A hybrid approach might combine both strengths.
Hint 2
End-to-end encryption means servers only see encrypted blobs. For abuse reporting, research 'message franking' techniques that let recipients prove what was sent without servers storing plaintext.
Hint 3
Consider databases with native TTL features (like Cassandra or ScyllaDB) and look into crypto-shredding—deleting encryption keys rather than waiting for data to physically purge from all replicas.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Self-Destructing Chat Architecture
1. Requirements Clarification
Start by confirming critical assumptions:
- Encryption model: All message content is end-to-end encrypted—servers process only ciphertext and routing metadata
- Deletion modes: Either "view-once" (gone when closed) or "timed" (5-60 second countdown from first view)
- Server retention cap: Undelivered messages expire after a maximum window (e.g., 7 days) to prevent indefinite storage
- Honest-client assumption: The guarantee applies to servers and unmodified clients; acknowledge that screenshots, modified apps, and physical cameras are outside the threat model
Capacity Planning
Quick estimation:
- Message throughput: 2B daily ÷ 86,400 sec ≈ 23k/sec average, 75k/sec peak
- Device fan-out: Each message creates ~4 encrypted copies (2.5 recipient devices + 1.5 sender's other devices) → ~300k envelope writes/sec at peak
- Storage footprint: 8TB/day of short-lived data (1KB per envelope × 8B envelopes)
- Concurrent connections: ~50M devices online (40% of 125M total) → ~500 gateway servers at 100k connections each
2. High-Level Architecture
Core Components
Gateway Layer
- Terminates TLS and maintains persistent WebSocket connections
- Registers device presence in a distributed cache (Redis cluster):
device_id → gateway_host - Handles bidirectional message flow with minimal latency
Message Service
- Receives send requests, assigns server
msg_idand authoritative timestamp - Persists encrypted envelopes and metadata
- Publishes delivery events to a partitioned event stream (Kafka, partitioned by
device_id)
Delivery Workers
- Consume events from the stream
- Check presence: push to online devices via their gateway; for offline devices, queue a push notification
- Track delivery status per device
Notification Service
- Sends content-less wake-up notifications via APNs/FCM:
{"type": "new_message"} - App fetches actual content over authenticated WebSocket, decrypts locally, and displays
- This keeps message content away from third-party notification providers
Expiry Service
- Maintains time-indexed deletion queue (sharded delay queue or time-bucketed tables scanned every second)
- Triggers purge operations when timers fire
- Broadcasts purge events to all relevant devices
Report Verification Service
- Validates abuse reports using cryptographic proofs (explained below)
3. State Management and Timer Authority
The hybrid ownership model balances responsiveness with synchronization:
Client responsibility:
- Starts local countdown immediately when user opens a message (zero-latency UX)
- Enforces deletion at the computed deadline
- Sends a
view_eventwith client timestamp to server
Server responsibility:
- Receives first view notification from any device
- Computes authoritative
expiry_time = min(client_timestamp, server_now) + configured_duration - Uses conditional write to ensure only the first view is accepted
- Broadcasts
viewedevent withexpiry_timeto all sender and recipient devices
Synchronization flow:
- Device A opens message, starts 10-second local timer, sends view event
- Server accepts it (first view), sets
expiry_time, broadcasts to all devices - Device B (offline) reconnects, sees
viewedevent, deletes immediately if deadline passed - All devices converge on the same deadline
This ensures: honest devices delete no later than server deadline, offline devices catch up correctly, and tampered clients can't indefinitely stall deletion.
4. Data Model and Storage
Database choice: ScyllaDB or Cassandra for:
- High write throughput and horizontal scalability
- Native TTL on rows (automatic expiration)
- TimeWindowCompactionStrategy (drops expired data efficiently without accumulating tombstones)
- Multi-datacenter replication for high availability
Schema design:
envelopes:
PRIMARY KEY (recipient_device_id, msg_id)
columns: ciphertext, wrapped_key, created_at
TTL: 7 days
message_metadata:
PRIMARY KEY (conversation_id, msg_id)
columns: sender_id, mode, timer_duration, sent_at,
first_viewed_at, expiry_time, state
TTL: 7 days + buffer
device_event_log:
PRIMARY KEY (device_id, sequence_number)
columns: event_type, msg_id, expiry_time, payload
TTL: 30 days
device_sync_cursor:
PRIMARY KEY (device_id)
columns: last_acknowledged_sequence
Crypto-shredding for deletion guarantee: Encrypt each message envelope with a unique data-encryption key (DEK). Store the DEK separately in a key management service. On purge, delete the DEK—this instantly makes all ciphertext (including backups and replicas) permanently unrecoverable. Physical deletion follows asynchronously during compaction. This provides strong deletion semantics on log-structured storage.
5. Critical Edge Cases
Offline Device Reconciliation
- Purge events are persisted in
device_event_log(retained 30 days vs. 7 days for payloads) - On reconnect, device calls sync endpoint with its last cursor position
- Applies events in sequence: if
PURGEarrives beforeDELIVER, device records local tombstone to ignore late-arriving delivery
Out-of-Order Delivery
- Sequence numbers enforce ordering per device
- Clients buffer gaps and request resync if gaps persist
- State transitions are idempotent and monotonic:
SENT → DELIVERED → VIEWED → EXPIRED
Mid-Countdown Disconnect
- Local timer continues running and deletes on schedule
- View event queued for send on reconnect (with original client timestamp)
- Server clamps timestamp and returns authoritative
expiry_time - If another device already viewed, device deletes immediately if deadline passed
Abuse Reporting: Message Franking
The challenge: enable reporting without storing plaintext on servers.
Solution:
- Sender generates random
franking_key, includes it in encrypted plaintext - Sender computes
tag = HMAC(franking_key, ciphertext)and sendstagto server - Server stores
tagwith message metadata (unencrypted) - To report, recipient reveals:
ciphertext + franking_key + server_tag - Server verifies: recompute HMAC with provided key; if it matches
tag, this proves the sender created that ciphertext - Moderators decrypt with provided key to review content
This works because the server's stored tag is a binding commitment—only the sender could have created a matching (ciphertext, key) pair. The recipient can't forge a different message.
6. API Design
Client → Server (WebSocket):
send_message(conv_id, [{device_id, ciphertext, tag}], mode, timer_sec)acknowledge_delivery(device_id, msg_id)view_message(msg_id, client_timestamp)→ returnsexpiry_timereport_abuse(msg_id, plaintext, franking_key, server_tag)
Server → Client:
deliver_message(msg_id, ciphertext, ...)message_viewed(msg_id, expiry_time)purge_message(msg_id)
REST endpoint:
GET /sync?device_id=X&cursor=N→ event log replay
Common Pitfalls
- Client-only timers: Won't sync across devices or prevent tampering
- Server-only timers: Add latency and break offline usage
- Trusting client timestamps blindly: Allows time manipulation; always clamp to server time window
- Exposing content via push notifications: Must use content-less wake-up notifications
- Insufficient deletion: Simply deleting records doesn't account for backups, replicas, or LSM storage; use crypto-shredding
- Ignoring catch-up complexity: Offline devices need careful event log reconciliation with tombstone semantics
This architecture balances real-time responsiveness (hybrid timers, persistent connections), reliability (event logs, idempotent operations), and privacy guarantees (E2EE, crypto-shredding, franking for reports).