Two patients, one time slot: how Markmedi prevents double booking
Temporary slot holds, a pessimistic per-clinic lock, idempotency keys and race tests against a real MySQL: how I solved concurrency in Markmedi's scheduling.
Every online scheduling system has the same nightmare: two people look at the same free slot, both click "confirm" in the same second, and on Monday morning the clinic finds out it has two patients booked at 9 a.m. with the same doctor. In Markmedi this gets trickier, because a slot is not just the practitioner's calendar. An appointment can reserve a room and a piece of equipment, it can be in person or a teleconsultation, and the front desk is also booking, rescheduling and checking patients in from the dashboard while patients book through the public page.
In this article I explain how the problem was solved in layers, why I didn't trust a single defense, and how I prove it works.

Why a unique index doesn't solve it
Almost everyone's first idea is a unique index on (doctor_id, scheduled_at). It catches the most obvious case, two appointments starting at exactly the same minute, and lets everything else through. Appointments have variable durations: a 30-minute assessment at 9:00 and a 60-minute procedure at 9:15 don't collide in the index but do collide in real life. There are also calendar blocks, events coming from Google Calendar, appointments already in progress that ran past their scheduled time, and physical resources shared between doctors.
The right question is whether two intervals overlap, and MySQL can't guarantee that with an ordinary index (there is no exclusion constraint like in PostgreSQL). So the guarantee has to come from serialization: only one transaction at a time can make decisions about a clinic's schedule.

Layer 1: the temporary slot hold
On the public page, the patient picks a slot and then still fills in details, answers questions and sometimes pays. To keep the experience from turning into a race, when they pick a slot the system creates a 15-minute hold tied to a random session token. While the hold exists, that slot disappears from the list for other visitors. If someone tries to hold a slot that is already held, they get a 409 and the interface offers another one.
This hold is deliberately advisory. It improves the experience and reduces conflicts, but it is not the source of truth. Expired holds are cleaned up by a command scheduled every minute, and the hold, release and booking routes are rate limited.
Layer 2: the final decision happens under a lock
Writing the appointment runs inside a transaction with automatic retry on deadlock. The first thing it does is lock the clinic's resources with SELECT ... FOR UPDATE, always in the same order: the clinic row, then the doctors ordered by id, then the rooms and the equipment.
DB::transaction(function () use ($clinic, $data) {
$this->lockResources->execute($clinic); // clinic, doctors, rooms, equipment
if (! $this->window->isFree($data->doctor, $data->start, $data->end)) {
throw new SlotTakenException(); // becomes a 409 for the client
}
return Appointment::create([...]);
}, attempts: 3);Locking the clinic row works as a per-tenant mutex. Two different clinics never wait for each other, and within the same clinic scheduling decisions are queued. The fixed lock order is what prevents deadlocks between, say, a reschedule and a check-in that need the same resources. The action that takes the lock also refuses to run outside a transaction: if someone calls it without one, it throws an exception instead of giving a false sense of safety.

Once under the lock, the system checks again whether the window is free. The overlap rule is the classic one, start_a < end_b and end_a > start_b, applied against appointments that still occupy the calendar (cancellations and no-shows don't count), blocks (including those that cross midnight) and busy intervals in the doctor's external calendar. For appointments in progress, actual time is what counts: if the appointment started late, the end taken into account is the actual start plus the duration, and never earlier than now.
There is also a check before the transaction, outside the lock, just to return an error quickly in the common case. It does not replace the one inside.
The price can change midway too
A less obvious race involves price. The patient sees an amount, and while they are filling in the form the clinic changes its price table or the slot starts carrying a different price. The client sends the version of the quote it saw, and inside the transaction the system checks whether it is still the current one. This is optimistic concurrency applied to data that doesn't need a lock: if the version changed, the booking is rejected and the screen shows the new amount.
Layer 3: idempotency for double clicks and bad networks
The third problem is the same patient creating two appointments. Double clicks, the "back" button, a mobile network that resends the request. For this, the client generates a request key and the server derives a context with HMAC from whoever is booking (the staff user, or the visitor and their session). The server also stores a hash of the canonical payload, with sorted keys.
- If the same key arrives again with the same data, the server returns the appointment that already exists, with the same confirmation receipt.
- If the same key arrives with different data, the response is 409, because that indicates a client error.
The check happens before and again inside the transaction, and the database has the final say with a unique index on (clinic_id, context, key). A public journey test confirms that repeating the request returns the same receipt and leaves exactly one appointment and one patient in the database.
The same pattern across every scheduling action
Booking is just one of the entry points. Rescheduling, starting an appointment, changing status, checking in, reserving a room and applying changes coming from Google Calendar follow the same recipe: a transaction with retry, a lock on the clinic's resources, a lock on the appointment itself, and revalidation. Starting an appointment, for example, returns 409 if the doctor already has another appointment in progress. Status changes go through an enum-based state machine, so a completed appointment can't go back to "scheduled" because of a late request.
Some guarantees live in the database because they are simple there: each appointment has at most one resource reservation, rooms and equipment use composite keys with clinic_id so they can never point to another tenant, and the waiting list uses a nullable column as an "active record" marker inside a unique index, which guarantees at most one active entry per patient.
How I prove it works
A concurrency test on in-memory SQLite proves nothing, because there are no two connections competing for a lock. So I wrote a harness that creates a disposable MySQL database, runs the migrations and spawns workers with pcntl_fork. Each worker opens its own connection, waits on a filesystem barrier and, when the barrier opens, they all run the same action at the same time. At the end, each one records its result and the test checks the scoreboard.
it('only one of two simultaneous starts wins', function () {
$results = $this->race(workers: 2, fn () => startAppointment($appointmentId));
expect($results)->toHaveSuccesses(1)->toHaveConflicts(1);
expect(Appointment::inProgress()->count())->toBe(1);
});The scenarios cover two simultaneous starts for the same doctor (one success, one 409), duplicate check-ins (a single waiting list entry and a single event), contention for the same room or piece of equipment and, as a counter-check, different units of the same equipment in different rooms, where both reservations must go through. The same harness covers the patient wallet, cashback and gift cards, where the race is over balance.
These tests form a dedicated suite that runs on demand against real MySQL with the pcntl extension, separate from the main suite that runs on SQLite. I run them whenever I touch locking, transactions or availability rules.
What I'd take to another project
The main lesson is to separate the experience from the guarantee. The temporary hold keeps the interface pleasant, the locked transaction is what decides, and idempotency protects against the user themselves. Each layer is simple on its own, and none depends on the others working. The rest is discipline: a fixed lock order, always revalidating inside the transaction, and testing against the database that goes to production.
This post is part of the series about Markmedi. Once saved, the appointment fires domain events and jobs; that is covered in architecture, DDD and domain events and in queues with Laravel Horizon.