PAU OJ Online Judge
ProblemsLearnStudy plansContestsSubmissionsRank

Updates

Announcements and upcoming contests

Loading announcements…
Sign in for personal alertsBrowse contests
Log inSign up

PAU OJ

PrimeAsia University Online Judge

A real online judge for programming practice, university contests and coding assessments. Write code in your browser, get sandboxed verdicts, and track your progress.

Platform

  • Problems
  • Contests
  • Submissions
  • Ranking
  • Reviewers

Resources

  • User guide
  • Changelog
  • How judging works
  • System health
  • Create an account

© 2026 PrimeAsia University Online Judge. All rights reserved.

v0.9.0

  1. All tracks
  2. Master class
  3. Design a Chat System

Design a Chat System

চ্যাট সিস্টেম ডিজাইন

Topic 41 of 41Story · visual · design practice

In this lesson

  • Story & concept
    • কেন দরকার
    • মূল ধারণা
    • কোডে দেখি
    • ধাপে ধাপে
    • সাধারণ ভুল
      • ল্যাব: duplicate আর gap ধরো
      • চিট শিট
      • প্রোডাকশন নোট
  • Visual story
  • Design practice
  • Checkpoint
  • Discussion
Back to track

0/0 solved

২ কোটি connection, per-conversation ordering, exactly-once আর presence।

In this lesson

  • Story & concept
  • Visual story
  • Design practice
  • Checkpoint
  • Discussion
01

Step 1: Story & concept

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।

প্রশ্নসিদ্ধান্তকারণ
ConnectionWebSocket gateway poolstateful connection আলাদা
Orderper-conversation seqclock skew এড়ায়
Duplicateclient_message_id uniqueretry/reconnect safe
PresenceRedis TTLDB heartbeat ব্যয়বহুল
Offlinepush + since_seqmessage হারায় না
Historypartitioned tablelarge 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।

সাধারণ ভুল

  • Timestamp দিয়ে ordering। Gateway ঘড়ি আলাদা হলে message উল্টে যাবে; per-conversation seq ব্যবহার করো।
  • Client retry-তে duplicate। client_message_id unique না থাকলে একই message দুইবার দেখাবে।
  • সব connection state app service-এ রাখা। Gateway আলাদা না হলে deploy-এ সব chat বিচ্ছিন্ন হবে।
  • প্রতি heartbeat DB-তে লেখা। ২ কোটি connection-এ DB মরে যাবে; Redis TTL ব্যবহার করো।
  • Reconnect-এ full history টানো। since_seq দিয়ে gap-only fetch করো।
  • Push body-তে message content। Lock screen-এ sensitive data; generic notification পাঠাও।

ল্যাব: duplicate আর gap ধরো

একটা 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-তে ঝাঁপ দেবে।

02

Step 2: Visual story

See the mental model first — the animation and the steps below it say the same thing.

Concept visual

২০ মিলিয়ন সংযোগ

WebSocket gateway connection ধরে রাখে, queue ক্রম ঠিক রাখে, DB শুধু ইতিহাস রাখে।

tier 0

client
ক্লায়েন্ট

মোবাইল socket

tier 1

WS gateway
edge

৫০k connection

tier 2

message queue
কিউ

chat_id key

tier 3

chat worker
ওয়ার্কার

ordering

tier 4

message DB
ডেটাবেস

শুধু ইতিহাস

push service
সার্ভিস

ডিভাইস বন্ধ হলে

20M WS · ordering
  1. 1gateway-তে connectionপ্রতি সার্ভারে ৫০k, ৪০০ সার্ভার
  2. 2presence Redis-এTTL ৩০s, heartbeat
  3. 3message queue দিয়ে ক্রমএক chat এক partition
  4. 4idempotency keyএকই message দুইবার এলেও একবার
  5. 5offline হলে pushAPNs/FCM, পরে sync
5টি ধাপে দেখা হচ্ছেগতি কমালে স্থির
03

Step 3: Design practice

Write a short design on paper or in a note, then compare it with the rubric. This is not a judge submission.

Design practice

Chat 20M connections

40 min

২ কোটি WebSocket, per-conversation order, exactly-once, presence।

তোমার কাজ

  1. 1gateway/connection estimate করো।
  2. 2seq/idempotency/storage design করো।
  3. 3offline push/reconnect drill করো।

ভালো উত্তরে কী থাকবে

  • connection math
  • ordering/idempotency
  • offline/resume
04

Step 4: Checkpoint

One timed attempt. Solve every problem to earn the module badge.

Final checkpoint

Ready to prove this module?

45 minutes3 problemsScale Architect badge
Go to checkpoint
05

Step 5: Discussion

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.

Sign in to react

Discussion

0 comments

Sign in to ask a question or share an approach.

Sign in to comment

No comments yet

Be the first to ask a question or leave a study tip.

Topic 41 of 41

PreviousDesign a News Feedনিউজ ফিড ডিজাইনTopic 40 of 41
NextFinal checkpointSystem Design checkpointসিস্টেম ডিজাইন চেকপয়েন্ট45 min · 3 problems
Back to track: System Design MasterclassAll learning tracks
প্রশ্নউত্তর
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