Stop double-bookings in Django: explicit slots, a review step, and a tight confirm
Stop double-bookings in Django: explicit slots, a review step, and a tight confirm Two people open the same 16:30 slot. Both see it as free. Both type a name and a mobile number. Both click Confirm. If your booking app
Stop double-bookings in Django: explicit slots, a review step, and a tight confirm
Two people open the same 16:30 slot. Both see it as free. Both type a name and a mobile number. Both click Confirm. If your booking app is even slightly careful about money, reputation or a real waiting room, that race is the bug that matters.
I built this flow for a small clinic-style appointment app: one location, a handful of practitioners, bilingual pages, and a reception desk that has to trust the list on the screen. The patterns below are generic Django. They are not a dump of a private codebase, and they do not assume a particular clinic. They are the rules I would start with again.
The goal is simple. A slot is bookable by at most one active appointment. Confirm is the only step that writes the booking. Everything before that is a draft the user can abandon.
1. Materialize the slots
An open range such as "Tuesday, 16:00 to 19:00, every 30 minutes" is a scheduling idea, not a bookable row. If two requests pick "16:30" independently, you have nothing unique to contend on.
Create the concrete slots ahead of time, in the clinic's local timezone, and book against those rows:
class Slot(models.Model):
practitioner = models.ForeignKey("Practitioner", on_delete=models.CASCADE)
starts_at = models.DateTimeField() # store UTC, display local time
duration_minutes = models.PositiveSmallIntegerField()
is_open = models.BooleanField(default=True)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["practitioner", "starts_at"],
name="unique_practitioner_start",
)
]
A closed day has no open slots. Repeating a generate-slots command for the same window should insert nothing new. If a slot already has booking history, do not move it; cancel or complete the appointment first, then block the slot if you must close it.
This also makes daylight-saving transitions boring. Generate slots from local civil times and reject a window that does not divide evenly, or a local time that does not exist or repeats on the transition day. Display every time in one named zone. I use Africa/Cairo.
2. Confirm is the only write
A flow that works for a patient, and for a receptionist helping someone on the phone, looks like this:
- Choose a practitioner.
- Choose a date.
- Choose a displayed time.
- Enter a name and a mobile number.
- Review the summary, then click Confirm.
Steps 1 to 4 only store a draft in the session, or in a draft row that is not an appointment. The public "booked" row is created in step 5. Voice input, if you add it, should fill the same fields. It should never submit the booking. Ambiguous speech should not silently pick a doctor or a slot.
Keep a short public horizon (for example 30 days) and a lead time (for example 30 minutes). A slot that starts too soon is simply not offered.
3. Let the database enforce "one booking"
A OneToOneField from the booking to the slot, or a unique constraint on booking.slot_id for active statuses, is the real lock. Application code that does "if slot is free, create booking" without a constraint will lose a race.
Confirm inside a transaction, lock the slot row, and re-read the facts you showed on the review screen:
from django.db import IntegrityError, transaction
@transaction.atomic
def confirm_booking(slot_id, draft):
slot = (
Slot.objects.select_for_update()
.select_related("practitioner")
.get(pk=slot_id)
)
if not slot.is_open or slot.starts_at != draft.starts_at:
raise SlotUnavailable()
if slot.practitioner_id != draft.practitioner_id:
raise SlotUnavailable()
if slot.starts_at <= timezone.now() + draft.lead_time:
raise SlotUnavailable()
try:
return Booking.objects.create(
slot=slot,
name=draft.name,
mobile=draft.mobile,
request_id=draft.request_id,
status=Booking.CONFIRMED,
)
except IntegrityError as exc:
raise SlotUnavailable() from exc
select_for_update() is the PostgreSQL path. It serializes two confirms on the same slot so one winner is created and the other hits the unique constraint, or sees is_open already flipped. On SQLite this race is harder to test honestly; I treat PostgreSQL as the real configuration and skip the concurrency test on SQLite.
After a successful create, mark the slot closed (or rely on the unique booking and treat "has an active booking" as closed). Either works if every reader uses the same rule.
4. Revalidate what the review screen showed
People hesitate. A receptionist may block a slot while a patient is still reading the summary. The practitioner or the start time might have changed. The review page is a snapshot, not a reservation, unless you explicitly hold the slot with a short timeout.
I prefer no silent hold. At Confirm, compare practitioner, start time and openness to the draft. If anything differs, do not book. Send the user back to the date list with a clear message: that time is no longer available, please pick another.
Normalize the mobile number before you store it. If your users type Arabic or Persian digits, convert them to ASCII digits first, then apply the local format. Reception search should use the same normalized form, or a receptionist will not find the appointment the patient just booked.
5. Retries and old tabs
The Confirm button will be clicked twice. The browser will also retry. Give every draft a request_id (a UUID is enough) and put a unique constraint on it. A retried Confirm with the same id returns the same booking, not a second one.
Old tabs are a separate problem. A patient starts a draft, opens a new tab, books 17:00, then goes back to the first tab and confirms 16:30. Protect that with a draft version, or a "current draft id" in the session. Confirm of a stale draft should fail and show the booking that already exists, not create a second visit.
The confirmation page should be private and session-bound. It can show status. It should not be a public URL that anyone with a guessable id can open.
6. WhatsApp is a draft link, not a sender
Reception often wants to send a confirmation or a reminder on WhatsApp. The safe version is an opt-in, then a https://wa.me/<number>?text=... link that opens the chat with prepared text. A person reads the draft and taps Send in WhatsApp.
Do not mark the message sent just because the link was opened. Do not send WhatsApp from your Django app unless you have a real messaging integration, delivery receipts and a policy for consent. Opening a link is not delivery.
Cancellation of a future appointment should release the slot so someone else can take it. Terminal states (completed, no-show, already cancelled) should not be silently reopened.
7. Prove the race with a test
A unique constraint you never race in CI is a rumour. With PostgreSQL, open two transactions (or two threads with django.test.TransactionTestCase) and let them confirm the same slot. One booking should exist. The loser should get a controlled SlotUnavailable, not a 500.
Also test the boring path: a slot that was blocked after review, a confirm after the lead time has passed, a second submit with the same request_id, and a stale tab.
What I would not add first
This is not a clinical record, a payments product, or a multi-clinic billing system. It does not need a queue, a background worker, or an AI agent to get the booking right. Staff users, sessions and permissions can stay with Django. Four ideas are enough: the location, the practitioner, the slot, and the booking.
Get the confirm path right, on PostgreSQL, with a test that two people cannot take the same 16:30. The rest of the product can grow after that.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.