healthcare-appointment-platform: BookMyDoc Makes a Double Booking Unrepresentable

A healthcare scheduling app where the database, not the code, has the final say.

9 min read • View on GitHub • More from srivishnu1644

An editorial black-ink illustration of a clinic reception area. A massive iron-bound ledger book lies open on a wooden lectern at center, its ruled pages dense with stamps. To its right, a small brass ticket window is cut into a stone wall and dispenses a single numbered paper ticket. Two hands reach toward the window from opposite sides; only one will close on the ticket. Rows of empty waiting-room chairs recede into the distance.
One authority, one ticket. The ledger decides; the people queue. This is the thesis of BookMyDoc in a single room.
Key Takeaways

The Booking That Cannot Be Written

Picture the worst version of a scheduling bug. A patient taps to claim a 9:30 AM slot. The code calls setStatus(slot, 'booked'), the slot flips to booked, and then the appointment insert throws. There is no transaction wrapping the two writes. The slot now says booked. No appointment exists. The state is invisible to the user, and it is never repaired. The slot quietly disappears from the calendar forever.

BookMyDoc was built to make that state unrepresentable. Two PostgreSQL constraints, appointments_one_active_per_slot and appointments_patient_no_overlap, guarantee that a slot marked booked without an appointment, or two appointments for the same slot, cannot be written at all. The application cannot corrupt the schedule even if it tries, because the database refuses the contradictory row.

That is the whole thesis of this repository, and it is a rarer posture than it sounds. Most systems treat the database as a dumb store and enforce business rules in application code. BookMyDoc inverts that. The schema guarantees the truth; the code exists only to make the failure graceful.

Three Problems, One Waiting Room

The booking itself is commodity work. The README is blunt that the interesting part comes after the appointment is made, and it names three gaps that existing tools tend to leave open.

Three roles share that waiting room. Patients book, check in, and watch their position in a live queue. Doctors manage slots, call the next patient, and record outcomes. Administrators get cross-clinic dashboards, directories, and notification logs, and their view of appointments is read-only by design: status changes travel through the same PATCH /api/appointments/:id/status endpoint providers use, so the ownership and transition rules apply uniformly.

The README calls the whole thing a monolith, and it means it plainly: one React client, one Express API, one PostgreSQL database. No microservices, no message broker, no cache tier, no container orchestration, and no API keys required to boot. That last claim is load-bearing. The optional integrations (Gemini for AI features, Resend for email, Twilio for SMS) all warn rather than throw when their credentials are missing, so a fresh clone runs with a database and nothing else.

The Database Has the Final Say

Here is the inversion in concrete terms. When two patients race for the same slot, the code does not try to be clever about who wins. It takes a row lock, re-checks the appointment table, and writes conditionally. Those locks exist for one reason: so the patient who loses the race gets a clean 409 SLOT_TAKEN instead of a 500 error and a broken page.

The lock is a courtesy. The constraint is the law. Even if the lock were removed entirely, the second write would still fail, because appointments_one_active_per_slot rejects a duplicate active appointment at the storage layer. A dbErrors utility maps that constraint violation to the exact same 409, so the user experience does not depend on the lock at all. Correctness holds regardless of what the application believes.

This is defence in depth done properly, and the source comments say so directly. The slot row's own status can disagree with reality if an older code path once set it without creating an appointment, so the booking logic checks the appointment table too rather than trusting the flag. The database is the referee because the application has been wrong before.

Inside the Transaction

The booking service is where the discipline concentrates. A single function, lockBookableSlot, locks the slot row and then decides, all inside one transaction. The header comment documents a lock ordering, appointment then slot, so two concurrent lifecycle operations cannot grab the same rows in opposite order and deadlock. That is textbook concurrency control, and it is rarely written down.

State transitions live in one frozen table, so every code path agrees on what is legal. Cancellation is reached through the same changeStatus function as everything else, which means no second code path can quietly disagree about what a cancelled appointment may become.

// ALLOWED_TRANSITIONS: the single source of truth for the state machine.
// Every status change in the codebase routes through this table.
const ALLOWED_TRANSITIONS = Object.freeze({
  scheduled: ["confirmed", "in-progress", "cancelled", "no-show"],
  confirmed: ["in-progress", "cancelled", "no-show"],
  "in-progress": ["completed", "cancelled", "no-show"],
  completed: [],
  cancelled: [],
  "no-show": [],
});

Then there is the notification problem. The README insists that duplicate notifications are prevented by the database, not by an application check, and the code shows how. A notification is rendered and persisted inside the same transaction that books the appointment, so the message cannot be lost if delivery fails, and no network call ever happens while a transaction is open. Delivery happens afterward, asynchronously. This is the transactional outbox pattern, implemented with a table instead of a broker.

An editorial black-ink close-up illustration of two hands at a wooden desk. The left hand seals a folded paper envelope and slides it into an open drawer fitted with a brass lock. The right hand, its postal courier's cap edge just visible at the frame, waits with an open satchel, reaching for the drawer only after the lock has clicked shut. Beside the drawer sit a stamp and a small stack of identical envelopes.
Write before you commit, deliver only after. The transactional outbox, made physical: the message is sealed in the drawer first, and the courier waits for the lock to click.

Race Two Patients for One Slot

The clearest way to see all of this at once is to watch the race unfold. The interactive diagram below runs two patients at one slot, step by step, and then lets you do the thing that proves the point: remove the lock and watch the constraint catch what the lock no longer does.

Step through a concurrent booking race, then remove the lock and watch the schema constraint refuse the second write anyway. The apology is the code's job; the truth is the database's.

A Prototype That Boots Like Production

The package.json calls this a prototype, but the boot sequence reads like something that has already been burned in production. Startup runs a preflight health check with linear backoff, five attempts at 500 milliseconds apart, on the reasoning that a few seconds of patience beats a crash loop. Only after the database answers does the scheduler start, because a timer firing against an unreachable database would mark every pass as failing for no reason.

Schema reconciliation runs at boot for a subtle reason the code spells out: a query naming a missing column returns a 500, and a 500 on the notification inbox looks exactly like an inbox with nothing in it. The reconciliation is designed never to throw or hang, and a role without DDL rights gets a warning while the server still starts. Shutdown is ordered too: the scheduler stops first so a pass cannot begin while the pool is closing, then open connections drain, then the pool closes.

Configuration is fail-closed. A production boot with no JWT_SECRET exits immediately with a generation command in the error message. Development generates a random per-process secret that is never written to disk, so tokens die on restart. And a deny-list of known-insecure secrets exists because of a specific audit finding: a production boot with JWT_SECRET=test-only-secret-not-for-production had succeeded happily, since the string was 37 characters and cleared the length rule. The fix was to name the value and refuse it. That is an audit loop closing on itself.

How It Compares

BookMyDoc is not the only open-source appointment platform, and it is worth placing it against the field. It is the only one of the four below that ships as a single process with zero required external credentials, and the only one whose stated focus begins after the appointment is already booked. Star and issue counts change, so the table cites architecture and focus, not popularity.

ProjectArchitectureData storeDistinctive focusExternal services required
BookMyDocMonolith (Express + React)PostgreSQLPost-booking: waiting room, notifications, operations; schema-enforced invariantsNone to boot (AI, email, SMS optional)
adityatagat/healthcare-appointment-systemMicroservices + API gatewayPer repositoryInfrastructure, Kubernetes, observability stackK8s, Prometheus, Grafana, Loki
munna516/Healthcare-Appointment-System (Health Point)Next.js full-stackMongoDBIntegrated booking with paymentsStripe, NextAuth
suman313/ai-healthcare-appointmentMulti-tenant appPer repositoryMulti-clinic management, AI booking, live waiting roomAI provider

Where the Armour Has Seams

A fair reading has to name the weak points, and this codebase has several. For any non-localhost database, the connection is configured with ssl: { rejectUnauthorized: false }, which encrypts the traffic but skips certificate verification, leaving the connection open to a man-in-the-middle. It is a common shortcut for Supabase-compatible deployments, and it is still a shortcut.

The Content Security Policy allows 'unsafe-inline' for both scripts and styles, a concession to the Vite bootstrap and the inline-style design system. That weakens one of the main protections a CSP is meant to provide. Unhandled promise rejections are logged but not fatal, which trades crash-safety for availability. A test-harness guard lives inside the production database module, so a development environment variable can change how the data layer behaves. And in the role permissions, patients are permitted to move their own appointment into in-progress, which is a product decision with a real abuse surface if the handler does not verify that the check-in is happening on the right day at the right location.

None of these erase the central idea. They simply mean the repository is a prototype with unusually mature instincts, not a finished product. The instinct worth stealing is the one that says the database should be able to say no.