Video in progress

Strong Middle 🏗️ System design

In a group chat, how do you maintain message order and the "delivered/read" states?

For order, the server assigns a monotonically increasing number (sequence) within each chat; the client's time isn't trusted. The read state is stored not per message but per member, as the "last read sequence".

📖 Answer

A client's clock can be wrong, and two messages can arrive in the same millisecond — ordering by created_at is unreliable. Give each chat its own counter:

CREATE TABLE messages (
  chat_id   BIGINT NOT NULL,
  seq       BIGINT NOT NULL,
  sender_id BIGINT NOT NULL,
  body      TEXT NOT NULL,
  client_msg_id UUID NOT NULL,       -- created by the client, against duplicates
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (chat_id, seq),
  UNIQUE (chat_id, client_msg_id)
);

Where to get seq: increment last_seq in the chats table with UPDATE ... RETURNING, or INCR chat:42:seq in Redis. Within a single chat this runs sequentially — in a very active group it can become a bottleneck, but for ordinary chats it's not a problem.

Now the states. In a 500-person group, a "read" record per member for every message is 500 times more writes. Instead:

CREATE TABLE chat_members (
  chat_id BIGINT, user_id BIGINT,
  delivered_seq BIGINT NOT NULL DEFAULT 0,
  read_seq      BIGINT NOT NULL DEFAULT 0,
  PRIMARY KEY (chat_id, user_id)
);

"Who read message 1050?" — WHERE read_seq >= 1050. The number of unread messages is last_seq - read_seq, so there's no need to store a separate counter.

Don't write read_seq on every scroll: the client debounces and sends the largest value once every 1–2 seconds, and the server only raises it with GREATEST(read_seq, :new) — so it never goes backward.