← Back to SQL, page 16

sql-0318 · Medium mid

How would you store chat messages for one-to-one and group conversations?

Use conversations, conversation_members (conversation, user, joined_at, last_read_message_id) and messages (id, conversation_id, sender_id, body, created_at). Treat one-to-one chats as conversations with two members. Index messages on (conversation_id, created_at, id) for paging and track read state per member rather than per message.

Full answer
text
conversations(id PK, kind CHECK IN ('direct','group'), title, created_at)
conversation_members(conversation_id FK, user_id FK, joined_at, last_read_message_id,
                     PRIMARY KEY (conversation_id, user_id))
messages(id PK, conversation_id FK, sender_id FK, body, created_at, edited_at, deleted_at)

Why this shape:

  • One model for direct and group chats keeps queries uniform.
  • last_read_message_id per member gives unread counts (messages with id > last_read) without a row per message per reader.
  • Keyset pagination on (conversation_id, created_at, id) loads history efficiently.
  • Soft delete (deleted_at) shows "message deleted" without breaking replies.

For a direct chat, a unique key on the ordered pair of users (smaller id, larger id) stops duplicate conversations between the same two people. At large scale, messages are often partitioned by conversation or time, but the logical model stays the same.

Key points

  • Model direct chats as two-member conversations
  • Track read state per member, not per message
  • Index (conversation_id, created_at, id) for paging
  • Prevent duplicate direct conversations with a unique pair key

Common mistakes

  • A read-receipt row for every message and reader
  • Separate tables for direct and group messages

Follow-ups

  • How would you compute unread counts per conversation?
  • How would you search message text?

Tips

  • Explain the unread-count design