Syed Ahmer ShahSyed Ahmer ShahSyed Ahmer ShahSyed Ahmer ShahSyed Ahmer Shah — home
  1. …
  2. Engineering Logs
  3. The Engineering Logs
  4. The Socket Is Not the Source of Truth
Part 26 of 27

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

Written by

Syed Ahmer Shah

Software Engineer

Nov 29, 20265 min read1,099 words—reading now▼
Baithak's #dev channel in dark mode, under the title The socket is not the source of truth
Read this articlevoice
Markdown

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.

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
Two people in #dev: a message, a live reply and its thread

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:

  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, and the source is on GitHub.

Find me across the web.

33 profiles · same person, every platform

Code08

  • GitHub@ahmershahdevCommerza and open repos
  • GitLab@ahmershahdevMirror of every public repo
  • BitbucketahmershahdevMirror of every repo
  • Codeberg@ahmershahdevArchive of the eight case-study projects
  • KDE Invent@ahmershahdevKDE community GitLab
  • Google Developerg.dev/syedahmershahGoogle Developer Program profile
  • LeetCodeu/syedahmershahDSA practice
  • Google PlayahmershahdevPublished Android apps

Work07

  • ASPortfolioahmershah.dev
  • LinkedInin/syedahmershah
  • Peerlistsyedahmershah
  • The Orgorg/syed-ahmer-shah
  • AWSAWS Builder Center@syedahmershah
  • Crunchbasesyed-ahmer-shah
  • LinkedIn · Companycompany/syedahmershah

Writing06

  • Dev.tosyedahmershah
  • Medium@syedahmershah
  • Hashnode@syedahmershah
  • Substack@syedahmershah
  • HackerNoonu/syedahmershah
  • CLCoderLegionuser/syedahmershah

Reviews & listings07

  • Google Knowledge PanelSyed Ahmer Shah
  • Google Business Profileg.page
  • amabout.mesyedahmershah
  • ClClutch
  • TpTrustpilot
  • DRDesignRush
  • TBTechBehemoths

Social05

  • YouTube@ahmershahdev
  • Instagram@ahmershahdev
  • TikTok@ahmershahdev
  • Facebookahmershahdev
  • X@ahmershahdev
#baithak#websockets#realtime#django#distributedsystems#backend#engineeringlogs
ShareXLinkedInRedditWhatsApp

← Previous in series

Baithak: Building Real-Time Team Chat with an Issue Tracker

On this page

  • 1. Save first, then broadcast
  • 2. Number every change, not just every message
  • 3. Catch up from the database, every time
  • 4. Give every reader one door
  • Locks are part of the design
  • Prove it with more than one browser
  • The short version

The Engineering Logs

  1. 01The Edge Latency Lie: Solving Global Consistency
  2. 02Top 10 AI Tools Every Frontend Developer Should Know (2026 Guide)
  3. 03Change One Number. Take Everything.
  4. 04How Databases Work: From Tables to Query Execution
  5. 05The New Era of Software Engineering
  6. 06The Art of Object-Oriented Programming
  7. 07GleanGrid: Building a Pre-Order Marketplace for Farmers Markets
  8. 08The Last Mango Problem: Race Conditions in a Real Marketplace
  9. 09BookMyMovie: Building a Cinema Ticketing Platform
  10. 10One Seat, Two Buyers: Race Conditions, IDOR and Keys in a Cinema Booking System
  11. 11Zovita+: Building an Online Pharmacy That Adapts to Each Shopper
  12. 12The Discount That Knew You Were Hesitating: Rule-Based Personalisation in an Online Pharmacy
  13. 13RAG Retrieval Strategies on a 50k-Document Dataset: BM25 vs Dense vs Hybrid
  14. 14Inside the Database Stack
  15. 15HolidayOps: Building a Working Days API for 250 Countries
  16. 16The Weekend Is Not a Constant
  17. 17MarketClock: A Trading Calendar That Shows Its Work
  18. 17Cybersecurity Trends: Protecting Data in the Digital Age
  19. 18The Day the Money Moves
  20. 19AIT: Building a University Admissions Portal From Scratch
  21. 20I Invented 14 People to Break My University Website
  22. 21OfflineShelf: Choosing Which Wikipedia Goes Offline
  23. 22A Library That Fits on a USB Stick
  24. 23Karobar ERP: Books That Balance for the Corner Shop
  25. 24The Shop That Ran on a Notebook
  26. 25Baithak: Building Real-Time Team Chat with an Issue Tracker
  27. 26The Socket Is Not the Source of Truth

Up next

Keep reading.

All 65 articles→
  1. 01

    Baithak: 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.

    Nov 29, 202610 minThe Engineering Logs

  2. 02

    The 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.

    Oct 24, 20264 minThe Engineering Logs

  3. 03

    The 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.

    Oct 18, 20265 minThe Engineering Logs

  4. 04

    The 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.

    Oct 2, 202610 minThe Engineering Logs

  5. 05

    One 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.

    Sep 29, 202611 minThe Engineering Logs

  6. 06

    The 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.

    Sep 27, 202610 minThe Engineering Logs

Available for new work · --:--:-- PKT

Have an idea?

sales@ahmershah.dev
Book a call WhatsApp +92 370 4831994

On this site

  • 01About
  • 02Education
  • 03Certificates
  • 04Skills
  • 05Projects
  • 06Experience
  • 07Services
  • 08Testimonials
  • 09Contact

Pages

  • Projects
  • Blog
  • Saved articles
  • RSS
  • Privacy Policy
  • Terms of Service
  • llms.txt

Elsewhere · official profiles

35 links

Professional

Work history, code and credentials.

  • in/syedahmershah
  • company/syedahmershah
  • @ahmershahdev
  • @ahmershahdev
  • ahmershahdev
  • @ahmershahdev
  • g.dev/syedahmershah
  • syedahmershah
  • @ahmershahdev
  • ahmershahdev
  • The Orgorg/syed-ahmer-shah
  • syed-ahmer-shah
  • syed-ahmer-shah
  • u/syedahmershah
  • @syedahmershah
  • AWS@syedahmershah

Coding & credentials

Problem solving, verified badges.

  • u/syedahmershah
  • syedahmershah
  • users/syedahmershah
  • learner/syedahmershah

Google & business

The official listings.

  • Google Business Profileg.page
  • Syed Ahmer Shah
  • syedahmershah
  • syedahmershah
  • amsyedahmershah
  • syedahmershah

Social (@ahmershahdev)

Build logs, clips, threads.

  • @ahmershahdev
  • @ahmershahdev
  • @ahmershahdev
  • ahmershahdev
  • @ahmershahdev
  • @bluesky.ahmershah.dev
  • ahmershahdev

Design

Interfaces and visuals.

  • syedahmershah
  • syedahmershah

Direct

  • sales@ahmershah.dev

    New projects & quotes

  • support@ahmershah.dev

    Support & help

  • syedahmershahofficial@gmail.com

    Personal

  • +92 370 4831994

    Phone · WhatsApp

  • Hyderabad, Sindh, Pakistan

    Remote-first · Asia/Karachi (UTC+5)

Resume ↗
SYED AHMER SHAH

© 2026 Syed Ahmer Shah. All rights reserved.

PrivacyTermsRSS
ahmershah.dev