---
title: "The Socket Is Not the Source of Truth"
description: "Why real-time apps lose messages, show them out of order and leak private channels, and the rules that kept Baithak's chat correct: save before you broadcast, number every change, catch up from the database, and give every reader one door."
author: "Syed Ahmer Shah"
date: 2026-11-29
url: https://ahmershah.dev/blogs/the-socket-is-not-the-source-of-truth
tags: ["baithak", "websockets", "real-time", "django", "distributed-systems", "backend", "engineering-logs"]
series: "The Engineering Logs" (part 26)
---

# The Socket Is Not the Source of Truth

_Four habits that keep a real-time app correct when networks drop, tabs sleep and two people act at the same moment_

![Baithak's #dev channel in dark mode, under the title The socket is not the source of truth](https://ahmershah.dev/blog/the-socket-is-not-the-source-of-truth/cover-8ab6ad95.webp)


The first version of almost every chat app works like this. Someone types a message, the browser sends it down a WebSocket, the server pushes it to everyone else's WebSocket, and somewhere along the way it gets written to the database.

It demos beautifully. Then a laptop lid closes on a train, a phone switches from Wi-Fi to mobile data, and two people edit and delete the same message in the same second. Messages go missing, arrive out of order, or come back from the dead. And because the socket was treated as the truth, there's nothing to check it against.

Building [Baithak](/projects/baithak), I started from the opposite end: **the database is the truth, and the socket is only a fast way of hearing about it.** Four habits came out of that.

* * *

## 1. Save first, then broadcast

The order matters more than anything else in this post.

When a message is posted, the API checks access, then opens one transaction. It locks the channel's row, takes the next sequence number, inserts the message and commits. Only after the commit does it tell anyone. In Django that's `transaction.on_commit`, which runs the broadcast only if the transaction actually committed.

If you broadcast first and save second, a failed save leaves people looking at a message that doesn't exist. Worse, the person who sent it believes it was delivered. If you save first, the worst case is a message that's saved but slow to appear, and slow can be fixed. A phantom message can't.

The sender gets the saved message back in the HTTP response, with its number. The socket isn't involved in confirming anything.

## 2. Number every change, not just every message

A sequence number per channel gives you order. Message 41 comes before message 42, everyone agrees, and nobody depends on clocks.

But order of arrival isn't the only thing that changes. Edits, deletes and reactions change messages that were already delivered. So each channel keeps a second counter for events, bumped under the same lock by every send, edit and delete, and stored on the message as the last change made to it.

The two numbers answer different questions. The sequence number says where a message sits in the conversation, and it never changes. The event number says when the message last changed. Unread counts use the first. Catching up uses the second.

```text
GET /channels/26/messages/?after_event=1840
```

That one request returns new messages, edited messages and deleted messages, in the order they changed. Without the event number, an edit made while your laptop was asleep would simply never reach you.

## 3. Catch up from the database, every time

Sockets drop. That's not a bug to fix but a fact to design around. So the client never assumes it heard everything.

When the socket reconnects, every open channel asks the API for changes after the last event it saw. When a tab notices a gap in sequence numbers, say 41 and then 43, it asks for the missing one. Messages carry a client id, so a retry after a timeout doesn't post the same message twice.

In Baithak's end-to-end tests there's one I find reassuring to watch. Two real browsers sit in the same channel. One goes offline, the other posts, and the first comes back online. Nobody refreshes the page. The missed message appears because the client asked the database for it.

![Two people in #dev: a message, a live reply and its thread](/blog/the-socket-is-not-the-source-of-truth/a4ac402c62.webp)

## 4. Give every reader one door

The last habit is about who's allowed to hear things, and it's where real-time apps leak.

The REST API checks access on every request. The socket usually checks once, when it connects. Then the person is removed from a private channel, and their socket, still subscribed, keeps receiving messages until they reload. Search has its own query, notifications have their own rules, and file links have their own check. Each one is a slightly different copy of "can this person read this channel?", and each copy is a chance to get it wrong.

Baithak has one function that answers that question, written in plain Python with no framework imports, plus a database query that a test proves agrees with it for every combination of role, channel type and membership. The API, the socket, search, notifications and file downloads all ask it. When someone's access changes, their open sockets recompute what they're subscribed to right away.

And when the answer is no, it's 404, never 403. "Forbidden" tells an outsider the private channel exists. "Not found" tells them nothing.

## Locks are part of the design

None of this survives two people acting at once without locks, so the locks are written down, not left to chance:

- Sequence and event numbers are taken under the channel row's lock.
- An edit or reaction waiting on that lock checks the message again once it holds it, because the message may have been deleted while it waited.
- Read markers move with a conditional update that only ever goes forward, so a stale tab can't mark old messages unread.
- Issue numbers come from the project row's lock, so two people filing at once get 15 and 16, not two 15s.

The second rule on that list came from a real bug. An edit queued behind a delete wrote its text back into the deleted message. The row-level lock was right. The assumption that the message still existed after waiting for it was wrong.

## Prove it with more than one browser

Unit tests can't tell you a socket delivered something to someone else. So beyond 1,443 backend tests, Baithak has end-to-end tests with two people in one channel, a load check with 300 real sockets, and a swarm of fifteen simulated people. Some chat normally while others flood messages, open more sockets than allowed, race edits against a delete, and try to read a private channel. The race between eight edits and one delete always ends the same way: deleted, with no text.

## The short version

If you build anything real-time, I'd keep four sentences on the wall:

1. Save it, commit it, then tell people.
2. Number every change, so anyone can ask what they missed.
3. Never trust a client to have heard everything. Let it catch up.
4. Ask one function who can read, everywhere, and answer "not found".

The socket makes the app feel alive. The database is what makes it right.

The full build story is in the [Baithak case study](/blogs/baithak-case-study-real-time-team-chat), and the source is on [GitHub](https://github.com/ahmershahdev/baithak).


---

*Originally published at https://ahmershah.dev/blogs/the-socket-is-not-the-source-of-truth — © Syed Ahmer Shah*
