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, 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.
GET /channels/26/messages/?after_event=1840That 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.

Also readThe Shop That Ran on a Notebook
Karobar ERP: Books That Balance for the Corner Shop
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:
- Save it, commit it, then tell people.
- Number every change, so anyone can ask what they missed.
- Never trust a client to have heard everything. Let it catch up.
- 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, and the source is on GitHub.
Up next
Keep reading.
01Baithak: Building Real-Time Team Chat with an Issue Tracker
How I built Baithak on my own in two weeks: Django Channels and React team chat with threads, direct messages, encrypted and virus-scanned files, search and an issue tracker linked to the conversation, tested by 1,443 backend tests, two browsers in one channel and fifteen simulated attackers.
10 minThe Engineering Logs
02The Day the Money Moves
When you buy a share, you don't own it the moment you click. A plain-language story of trade settlement, T+1 and T+2, why holidays in two countries can push a payment back a day, and what building MarketClock taught me about dates that have a history.
4 minThe Engineering Logs
03The Weekend Is Not a Constant
Why 'is this a working day?' breaks so much software: weekends that differ by country and change over time, holidays that follow the moon, time zones that disagree about today, and the habits that kept my own date logic honest while building HolidayOps.
5 minThe Engineering Logs
04The Discount That Knew You Were Hesitating: Rule-Based Personalisation in an Online Pharmacy
How Zovita+ turns browsing into personal discounts without a machine-learning model: one visitor key for guests and customers, interaction counters, six offer rules, one pricing function for the bag and the charge, offers locked and redeemed once at checkout, guest-to-account merging, A/B tests, and the edge cases that shaped it.
10 minThe Engineering Logs
05One Seat, Two Buyers: Race Conditions, IDOR and Keys in a Cinema Booking System
How BookMyMovie makes sure one cinema seat is never sold twice, a guessed booking number shows nothing, and a leaked or missing key can't quietly break tickets: row locks, lock order, a NULL-tolerant unique key, status compare-and-set, idempotency, IDOR scoping, HMAC tickets, captcha step-up, and the bugs that still got through.
11 minThe Engineering Logs
06The Last Mango Problem: Race Conditions in a Real Marketplace
What happens when fifty people try to buy the last item, use a single-use coupon or book a nearly full pickup window at the same instant, the MySQL snapshot detail that almost overbooked a stall, and the quieter races that hide in stock forms, restocks and payments.
10 minThe Engineering Logs
