চ্যাট সিস্টেম ডিজাইন
২ কোটি connection, per-conversation ordering, exactly-once আর presence।
Start with the production incident, then the design decision that fixes it.
রাত ১০টা, চলো-র driver-rider chat-এ একটা মেসেজ ৪০ সেকেন্ড পরে পৌঁছাল, আর আরেকটা দুইবার দেখাচ্ছে। কারণ তখন ২ কোটি WebSocket connection খোলা, আর মেসেজ যাচ্ছে একই Postgres-এ যেখানে ride update চলছে। নুসরাত দেখল, reconnect হলে client আবার same message পাঠাচ্ছে, server-এ কোনো idempotency key নেই; তাই duplicate। আর ordering রক্ষা করতে timestamp ব্যবহার করছে, কিন্তু দুই gateway-র clock আলাদা।
চ্যাট মানে শুধু "message পাঠাও" নয়। চারটা কঠিন প্রশ্ন: connection কোথায় থাকবে, ordering কে ঠিক করবে, delivery exactly-once হবে কি না, আর offline ইউজার ফিরে এলে কী দেখবে। এই টপিকের লক্ষ্য—২ কোটি connection-এর চ্যাট সিস্টেম ডিজাইন করা, যেখানে মেসেজ হারায় না, duplicate হয় না, আর order ঠিক থাকে।
Connection gateway আলাদা। WebSocket connection state পুরো service-এর ভিতরে নয়; dedicated gateway (stateful) connection ধরে, message bus-এ publish করে। Gateway মরে গেলে client reconnect করে; message bus-এ থাকা message হারায় না।
Ordering। প্রতিটা conversation-এর জন্য monotonically increasing sequence number দাও (DB/Redis INCR), timestamp নয়। Client sequence দেখে gap থাকলে history fetch করে। একই conversation-এর message এক partition/queue-তে পাঠালে order রক্ষা হয়।
Exactly-once মানে at-least-once + idempotency। Client client_message_id পাঠায়; server unique constraint দিয়ে dedupe করে, duplicate হলে আগের message id ফেরত দেয়। Delivery ack, retry আর reconnect সব একই key ব্যবহার করে।
Presence। "Online now" মানে gateway heartbeat (৫ সেকেন্ড), Redis TTL (১৫ সেকেন্ড); DB-তে প্রতি heartbeat লিখো না। Presence আলাদা, message delivery আলাদা; presence হারালে chat history নষ্ট হয় না।
Offline push। ইউজার offline হলে message DB-তে থাকে; APNs/FCM push যায়, client ফিরে এলে since=last_seq দিয়ে backlog আনে। Push body-তে sensitive content নয়—শুধু "নতুন মেসেজ"।
Storage। Message body append-only table/partition by conversation/month; index (conversation_id, seq). ২ কোটি connection ≠ ২ কোটি message/sec; write estimate আলাদা করো। Media object storage-এ, message-এ URL।
| প্রশ্ন | সিদ্ধান্ত | কারণ |
|---|---|---|
| Connection | WebSocket gateway pool | stateful connection আলাদা |
| Order | per-conversation seq | clock skew এড়ায় |
| Duplicate | client_message_id unique | retry/reconnect safe |
| Presence | Redis TTL | DB heartbeat ব্যয়বহুল |
| Offline | push + since_seq | message হারায় না |
| History | partitioned table | large conversation |
Gateway-তে message নেওয়া আর idempotent insert:
def on_message(user_id, payload):
conv = payload["conversation_id"]
key = payload["client_message_id"]
seq = redis.incr(f"seq:{conv}")
row = db.execute(
"""
INSERT INTO messages (conversation_id, seq, sender_id, body, client_message_id)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (conversation_id, client_message_id) DO NOTHING
RETURNING id, seq
""",
(conv, seq, user_id, payload["body"], key),
)
if row is None:
row = db.fetch_one(
"SELECT id, seq FROM messages WHERE conversation_id=%s AND client_message_id=%s",
(conv, key),
)
bus.publish(f"chat:{conv}", {"id": row.id, "seq": row.seq, "body": payload["body"]})
return {"id": row.id, "seq": row.seq}
CREATE TABLE messages (
id uuid PRIMARY KEY,
conversation_id uuid NOT NULL,
seq bigint NOT NULL,
sender_id uuid NOT NULL,
body text NOT NULL,
client_message_id text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (conversation_id, seq),
UNIQUE (conversation_id, client_message_id)
);
Unique constraint দুটোই দরকার: seq ordering রক্ষা করে, client_message_id duplicate আটকায়। ON CONFLICT DO NOTHING-এর পরে আগের row পড়ে same response ফেরত দাও।
১. Scale estimate। ২ কোটি concurrent connection, প্রতিটা gateway ৫০ হাজার connection ধরে → ৪০০ gateway; heartbeat ৫s, Redis TTL ১৫s।
২. Connection layer। WebSocket gateway + load balancer (sticky not required if session token); gateway stateless যতটা সম্ভব, connection state ছাড়া।
৩. Message write। Per-conversation seq + idempotency key + DB transaction; media আলাদা object storage।
৪. Fan-out। Conversation bus/queue-তে publish; online recipient gateway-এ push; offline হলে push notification।
৫. Failure drill। Gateway crash → reconnect + since_seq; DB primary fail → retry/idempotent; Redis down → seq fallback DB sequence; duplicate publish → client dedupe।
client_message_id unique না থাকলে একই message দুইবার দেখাবে।since_seq দিয়ে gap-only fetch করো।একটা conversation-এ client client_message_id=m1 দিয়ে message পাঠাল, response হারাল, আবার same id পাঠাল। Server-এ unique constraint থাকলে দ্বিতীয়বার নতুন row হবে না। কাগজে লেখো: প্রথম insert-এর seq ৪১, দ্বিতীয় response-এ কী ফেরত যাবে? এখন client seq ৪১, ৪৩ পেলে কী করবে—কেন ৪২ fetch করবে?
Message body-তে end-to-end encryption থাকলে server search/analytics করতে পারবে না—product decision আগে নাও। Connection gateway-তে backpressure রাখো: slow client-এর জন্য unbounded buffer নয়, drop/close with resume। Presence আর typing indicator ephemeral; DB-তে লিখো না। Reconnect-এ since_seq ছাড়া full history টানো মানে ২ কোটি client একসাথে DB-তে ঝাঁপ দেবে।
See the mental model first — the animation and the steps below it say the same thing.
Concept visual
WebSocket gateway connection ধরে রাখে, queue ক্রম ঠিক রাখে, DB শুধু ইতিহাস রাখে।
Write a short design on paper or in a note, then compare it with the rubric. This is not a judge submission.
Design practice
২ কোটি WebSocket, per-conversation order, exactly-once, presence।
One timed attempt. Solve every problem to earn the module badge.
Final checkpoint
Ready to prove this module?
Ask questions, share an approach or leave a study tip for this lesson.
Was this lesson helpful?
Your reaction helps other learners judge these notes.
0 comments
Sign in to ask a question or share an approach.
Sign in to commentNo comments yet
Be the first to ask a question or leave a study tip.
| প্রশ্ন | উত্তর |
|---|
| Connection? | WebSocket gateway pool |
| Order? | per-conversation seq |
| Duplicate? | client_message_id unique |
| Offline? | push + since_seq |
| Presence? | Redis heartbeat TTL |
| History? | partition by conversation |