Skip to main content

Scenario: Slack Message Delivery

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

1. The Interview Question​

"How does Slack deliver messages reliably to millions of concurrent connections while preserving per-channel ordering?"

2. Real-World Context​

DimensionDetail
Company / systemSlack — real-time messaging; migrated from Redis job queues to Kafka
ScaleBillions of messages/day; millions of concurrent WebSocket connections; hot channels during incidents
Why architects careCombines log-based messaging, per-channel ordering, at-least-once delivery, and WebSocket fan-out
Public referencesSlack engineering blog on Kafka migration; Vitess for message store sharding

AWS deployment context​

Typical Slack-style messaging on AWS: API Gateway + ECS Fargate message API; Amazon MSK (Kafka) with channel_id partition key; ECS persistence workers writing to Amazon Aurora or DynamoDB message store; ECS WebSocket gateway fleet behind ALB with sticky sessions; Amazon ElastiCache Redis for presence + connection routing; Amazon SNS for mobile push fallback; CloudWatch for consumer lag and delivery latency.

Step-by-step flow:

StepActionExplanation
1WebSocket connectClient opens persistent connection to realtime gateway via ALB.
2POST messageUser sends message; API validates auth + channel membership.
3ProduceMessage written to MSK with key=channel_id for ordering.
4Durable writePersistence consumer writes to Aurora message store.
5INSERT messagemessage_id unique constraint — idempotent dedup.
6Fan-outRealtime gateway consumer reads same topic.
7PushWebSocket push to all channel subscribers.

3. Step-by-Step Interview Answer​

Minutes 0–5: Requirements​

TypeDetail
OrderingMessages in a channel appear in send order
DeliveryOnline users get real-time push; offline users catch up on reconnect
SemanticsAt-least-once from producer; dedupe at consumer by message_id
ScaleHot channels (incidents, all-hands) without single-partition bottleneck
SessionSender sees own message immediately (read-your-writes within session)

Step-by-step flow:

StepActionExplanation
1Per-channel orderingKafka partition key = channel_id.
2At-least-onceProducer acks=all; consumer dedupes by message_id.
3Real-time pushWebSocket fan-out within 500ms p99 for online users.
4Offline catch-upFetch from last_read_sequence on reconnect.

Minutes 5–15: Architecture​

Step-by-step flow:

StepActionExplanation
1POST messageClient sends message body to API.
2Assign IDsServer assigns message_id (time-ordered) + channel_sequence.
3ProduceWrite to MSK topic with key=channel_id — ordering guarantee.
4AckKafka acks=all — message durable in ISR before API responds.
5201 CreatedClient sees own message — session read-your-writes.
6–7PersistConsumer writes to Aurora; message_id UNIQUE dedupes duplicates.
8–9Fan-outRealtime gateway pushes to all WebSocket subscribers.

Step-by-step flow:

StepActionExplanation
1SendClient posts message via HTTP or WebSocket.
2ProduceMSK log — source of truth for ordering.
3PersistDurable storage for history + offline catch-up.
4Fan-outSeparate consumer group for realtime path.
5PushOnline subscribers receive via WebSocket.
6Catch-upOffline clients fetch gap on reconnect.

Minutes 15–30: Deep dive​

Ordering — partition key = channel_id:

Step-by-step flow:

StepActionExplanation
1hash(channel_id)All messages for channel land on same partition — strict order.
2Ordered consumeConsumers process partition sequentially — preserve order.

Hot channel mitigation:

StrategyWhenMechanism
Dedicated partitionCEO all-hands channelPre-assign hot channel to own partition
Sequence servicePartition saturatedServer-side sequence + merge on read
Rate limit postingAbuse / floodAPI rate limit per channel per user
Read replicasHistory fetch overloadAurora read replicas for catch-up

Dedup and delivery semantics:

LayerMechanism
Producerenable.idempotence=true, acks=all
PersistenceINSERT ... ON CONFLICT (message_id) DO NOTHING
GatewayPer-connection last_delivered_sequence map
ClientClient-side dedup by message_id on receive

Minutes 30–45: Failures​

FailureBehaviorMitigation
MSK broker downISR replication; producer retriesMulti-AZ MSK cluster
Gateway crashClient reconnects; replay from last ack sequenceSticky sessions + Redis connection registry
Duplicate consumeIdempotent write by message_idUNIQUE constraint in store
Message edit conflictVersion field on messageLast-writer-wins or CRDT policy
Consumer lagRealtime delayScale gateway consumers; alert on lag

Step-by-step flow:

StepActionExplanation
1ReconnectClient detects WebSocket disconnect.
2last_ack_sequenceClient sends last successfully received sequence.
3–4Fetch gapGateway queries store for messages after sequence.
5ReplayClient receives missed messages — no loss.

4. Whiteboard Guide​

  1. Left: Client apps (WebSocket + HTTP)
  2. Center: Message API → MSK (label partition key = channel_id)
  3. Branch down: Persistence worker → Aurora
  4. Branch right: Realtime gateway → WebSocket fan-out
  5. Label hot channel problem on single partition
  6. Annotate at-least-once + dedup at persistence layer

AWS whiteboard layout​

Step-by-step flow:

StepActionExplanation
1ProduceSingle write to MSK — fan-out via consumer groups.
2–3DurabilityPersist for history + offline catch-up.
4–5RealtimePush to online WebSocket subscribers.

5. Principal-Level Signals​

  • Partition key = channel_id for per-channel ordering
  • Distinguishes realtime path vs durability path (separate consumer groups)
  • Mentions hot partition problem and mitigation strategies
  • At-least-once + idempotent consumer = effective exactly-once for users
  • Session read-your-writes — API returns 201 before fan-out completes
  • Offline catch-up via last_read_sequence — not relying on Kafka retention alone

6. Red Flags​

  • Global ordering across all channels — unnecessary; kills throughput
  • No message_id dedup — duplicate messages visible to users
  • Single consumer group for persist + fan-out — coupling; can't scale independently
  • Relying on Kafka retention for history — need durable message store
  • WebSocket without reconnect replay — message loss on gateway crash

7. Follow-Up Questions​

QuestionStrong answer
Exactly-once delivery?At-least-once + message_id dedup at store and client
Hot channel 10K msg/min?Dedicated partition + gateway shard fan-out by subscriber
Cross-channel ordering?Not required — only per-channel order matters
Message edit?Version field; broadcast edit event on same partition
EU user reads US channel?EL replication lag — session + monotonic reads per region

9. Practice Drill​

Explain at-least-once vs exactly-once in Slack context in 10 minutes. Whiteboard the send sequence (steps 1–9) from memory.


10. Production High-Level Design​

10.1 Architecture diagram index​

SectionTopic
§2End-to-end AWS deployment
§3Send + fan-out sequence
§10.2C4 logical context
§10.3Full VPC stack
§10.4Topic partitioning + hot channels
§11.4Send handler sequence
§11.5Connection routing + fan-out
§11.6Reconnect replay
§12Multi-AZ MSK + regional cells
§13Metrics and alerts
§148-week rollout
§15Delivery + ordering tests
§16Production readiness

10.2 System context (C4 Level 1)​

Step-by-step flow:

StepActionExplanation
1Message APIAuth, validate, produce to MSK.
2MSKOrdered log per channel partition.
3PersistenceDurable write to Aurora.
4GatewayWebSocket fan-out to subscribers.
5PresenceRedis tracks online users per channel.

10.3 AWS production architecture​

Step-by-step flow:

StepActionExplanation
1REST ingressAPI Gateway → Message API for POST.
2WebSocketALB sticky sessions → Gateway fleet.
3MSK producePartition by channel_id.
4Dual consumePersistence + Gateway independent consumer groups.
5Store + pushAurora durability; Redis presence routing.
AWS componentResponsibility
MSKOrdered message log; 128 partitions; 3-broker HA
ECS Message APIAuth, produce, return 201
ECS PersistenceConsume → Aurora INSERT dedup
ECS GatewayConsume → WebSocket fan-out
AuroraMessage history; sharded by channel_id
ElastiCache Redischannel:{id}:subscribers set; connection routing
ALBWebSocket upgrade; sticky sessions

10.4 MSK topic design​

ParameterValueRationale
Topicchannel-messagesSingle topic; partition by channel
Partitions128~10K channels per partition at scale
Replication factor3ISR durability
Retention7 daysReplay buffer; history in Aurora
Keychannel_idPer-channel ordering
Hot channelDedicated partition mappingPre-map #incidents to partition 0

11. Production Low-Level Design​

11.1 API contract​

Endpoint: POST /v1/channels/{channel_id}/messages

{
"text": "Deploy starting in 5 minutes",
"client_msg_id": "cm_8f3a",
"thread_ts": null
}

Response:

{
"message_id": "msg_1735689600_abc",
"channel_id": "C123",
"channel_sequence": 1043,
"ts": "1735689600.123456",
"text": "Deploy starting in 5 minutes"
}
HTTPMeaning
201Message accepted; durable in MSK before response
409Duplicate client_msg_id — idempotency hit
429Rate limited — hot channel protection
503MSK unavailable — client retry with same client_msg_id

11.2 Message store schema (Aurora)​

CREATE TABLE messages (
message_id VARCHAR(64) PRIMARY KEY,
channel_id VARCHAR(32) NOT NULL,
channel_sequence BIGINT NOT NULL,
user_id VARCHAR(32) NOT NULL,
text TEXT NOT NULL,
version INT NOT NULL DEFAULT 1,
client_msg_id VARCHAR(64),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),

CONSTRAINT uq_channel_sequence UNIQUE (channel_id, channel_sequence),
CONSTRAINT uq_client_msg UNIQUE (channel_id, user_id, client_msg_id)
);

CREATE INDEX idx_messages_channel_seq ON messages (channel_id, channel_sequence DESC);

11.3 MSK producer configuration​

producer_config = {
"bootstrap.servers": MSK_BROKERS,
"enable.idempotence": True,
"acks": "all",
"retries": 5,
"max.in.flight.requests.per.connection": 5,
"compression.type": "lz4",
"key.serializer": channel_id.encode(),
}
SettingValueWhy
enable.idempotenceTrueNo duplicate produces on retry
acksallWait for ISR before API 201
keychannel_idPartition ordering

11.4 Message send handler — step-by-step​

Step-by-step flow:

StepActionExplanation
1POSTClient sends message.
2AuthValidate workspace membership + channel access.
3Assign IDsServer-side message_id + monotonic channel_sequence.
4ProduceWrite to MSK partition for C123.
5acks=allDurability confirmed before 201.
6201 CreatedClient sees own message — session guarantee.
7–8PersistAsync durable write; dedup by message_id.
9–10Fan-outGateway pushes to all channel subscribers.

Handler pseudocode:

def post_message(channel_id: str, user_id: str, body: dict) -> Message:
# Step 1: Idempotency check
if body.get("client_msg_id"):
existing = db.get_by_client_msg(channel_id, user_id, body["client_msg_id"])
if existing:
return existing

# Step 2: Assign server IDs
message_id = generate_message_id()
sequence = sequence_service.next(channel_id)

payload = {
"message_id": message_id,
"channel_id": channel_id,
"channel_sequence": sequence,
"user_id": user_id,
"text": body["text"],
"ts": now_ts(),
}

# Step 3: Produce to MSK (blocks until acks=all)
producer.produce(
topic="channel-messages",
key=channel_id.encode(),
value=json.dumps(payload).encode(),
).get(timeout=5)

return Message(**payload)

11.5 WebSocket gateway​

Step-by-step flow:

StepActionExplanation
1EventGateway consumes message from MSK.
2LookupRedis set of connection IDs subscribed to channel.
3Connection listMay span multiple gateway instances.
4–5PushSend JSON event on each WebSocket.
6Skip senderOptional — client already has 201 response.

Redis structures:

# Channel subscribers (connection IDs)
SADD channel:C123:connections gw-1:conn-abc gw-2:conn-def

# Connection metadata
HSET conn:gw-1:conn-abc user_id U456 gateway gw-1 channels C123,C789

# Presence
SETEX presence:U456 60 online

11.6 Offline catch-up​

Step-by-step flow:

StepActionExplanation
1ConnectClient reconnects with last known sequence.
2Query gapFetch messages after last_read_sequence.
3BatchReturn up to 50 messages per batch.
4ReplayClient renders missed messages in order.
5ACKUpdate cursor for next disconnect.

11.7 Message edit and delete​

# Edit broadcasts on same partition — ordering preserved
edit_payload = {
"type": "message_edited",
"message_id": "msg_abc",
"channel_id": "C123",
"text": "Updated text",
"version": 2,
}
producer.produce(topic="channel-messages", key="C123", value=json.dumps(edit_payload))
Event typeOrderingConflict resolution
message_postedPer channel_sequenceN/A
message_editedSame partitionversion field — last-writer-wins
message_deletedSame partitionTombstone in store

12. HA/DR and Multi-Region​

PrincipleImplementation
Regional cellsUS workspace data in US; EU in EU
EL fan-outCross-region message lag 100–400ms acceptable
Session stickinessUser reads from home region — monotonic reads
Admin revokeStrong metadata store — PC for security

13. Observability and Operations​

MetricAlert threshold
msk_consumer_lag persistence> 10,000 for 5 min
msk_consumer_lag gateway> 1,000 for 2 min
message_delivery_latency_p99> 500ms
websocket_connections_activeCapacity planning
duplicate_message_insert_rateSpike — consumer rebalance issue
hot_channel_message_rate> 100/s per channel

Structured log:

{
"message_id": "msg_abc",
"channel_id": "C123",
"channel_sequence": 1043,
"produce_latency_ms": 12,
"persist_latency_ms": 45,
"fanout_latency_ms": 38,
"subscribers_notified": 847
}

14. Implementation Roadmap (8-Week Rollout)​

WeekDeliverable
1Message API + MSK topic + producer
2Persistence worker + Aurora schema
3WebSocket gateway + Redis presence
4Offline catch-up + reconnect replay
5Idempotency (client_msg_id) + dedup
6Hot channel rate limiting
7Load test 100K concurrent WebSockets
8Multi-AZ hardening + consumer lag dashboards

15. Testing Strategy​

TestPass criteria
Per-channel ordering1000 messages — strict sequence order
Duplicate produceIdempotent producer — single row in Aurora
Gateway crashReconnect replays from last_read_sequence
Hot channel 1K msg/sRate limit engages; no partition stall
Offline 1 hourCatch-up returns all missed messages in order
Edit conflictVersion increment; last edit wins

16. Architecture Review Checklist​

#GateStatus
1MSK partition key = channel_id☐
2Producer enable.idempotence=true, acks=all☐
3Separate consumer groups for persist vs gateway☐
4message_id UNIQUE constraint in store☐
5WebSocket reconnect with gap replay☐
6client_msg_id idempotency on POST☐
7Hot channel rate limiting☐
8Consumer lag dashboards + alerts☐
9Load test 100K concurrent connections☐
10Message edit uses same partition for ordering☐