Wooden appointment book with two pencils crossing over the same time slot on a clinic desk

How to Prevent Double Booking in an Appointment Scheduling Backend

•11 min read

If you build online booking for a clinic, a salon or any service business, sooner or later two people will click the same 10:00 slot within the same second. This guide shows how to prevent double booking in an appointment scheduling backend: the data model, a database constraint that makes overlaps impossible, short-lived holds, idempotent booking requests, sync with external calendars and the failure cases you need to handle. The examples use PostgreSQL, but the trade-offs apply to any stack.

If you are planning the patient-facing side of a medical practice site (pages, content, what to publish), that is covered in our step-by-step guide to building a website for doctors. This article is about the system behind the "Book now" button.

Why check-then-insert fails

The first version of almost every booking endpoint looks like this:

// Naive: race condition
const conflict = await db.query(
  'SELECT 1 FROM appointments WHERE provider_id = $1 AND start_at < $3 AND end_at > $2',
  [providerId, start, end]
);
if (conflict.rowCount === 0) {
  await db.query('INSERT INTO appointments ...');
}

Two requests can both run the SELECT, both see no conflict and both INSERT. Under the default isolation level of most databases, nothing stops them. Adding a cache, a queue or a check in the frontend makes the window smaller but never closes it. The rule "a provider cannot be in two appointments at once" has to live where concurrent writes are serialized: in the database.

How to prevent double booking with an exclusion constraint

A UNIQUE constraint works for single values, but appointments are intervals, and two different intervals can still overlap. The PostgreSQL documentation on range types notes that UNIQUE is usually unsuitable for ranges and that an exclusion constraint is often more appropriate, because it can express "non-overlapping". With the btree_gist extension you can combine an equality check on a scalar column (the provider) with an overlap check on a range (the time):

CREATE EXTENSION IF NOT EXISTS btree_gist;

CREATE TABLE appointments (
  id              uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  provider_id     uuid NOT NULL REFERENCES providers(id),
  location_id     uuid NOT NULL REFERENCES locations(id),
  during          tstzrange NOT NULL,
  status          text NOT NULL
                  CHECK (status IN ('held','booked','cancelled','completed','no_show')),
  hold_expires_at timestamptz,
  patient_ref     uuid,
  created_at      timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT no_provider_overlap EXCLUDE USING gist (
    provider_id WITH =,
    during      WITH &&
  ) WHERE (status IN ('held','booked'))
);

Three details matter here:

  • Half-open ranges. Build ranges as tstzrange(start, end, '[)'), so a 9:00–9:30 appointment does not collide with one that starts at 9:30.
  • Partial constraint. The WHERE clause means cancelled or completed rows do not block the calendar, so you keep history without deleting it.
  • timestamptz, not timestamp. Store instants in UTC and keep the practice's IANA time zone (for example America/Bogota) on the location. Convert to local time only when you generate slots or render them.

When two transactions try to insert overlapping rows, one commits and the other fails with an exclusion violation (SQLSTATE 23P01 in the PostgreSQL error codes). That failure is not a bug; it is your signal to return HTTP 409 and offer other slots.

More than one resource

If an appointment needs a provider and a room (or a device), add one exclusion constraint per resource. For cleaning or preparation time between visits, store a second column such as blocked that extends the range by the provider's buffer, and put the constraint on that column instead of on the visible appointment time.

Holds: the two-phase booking flow

Real booking flows are not one request. The patient picks a slot, fills in a form, maybe pays a deposit. If you only write the row at the end, the slot can disappear while they type. The usual answer is a short hold:

  1. When the user selects a slot, insert a row with status = 'held' and a hold_expires_at a few minutes ahead. The exclusion constraint already protects it.
  2. When the form is submitted, promote the hold to booked in one conditional update.
  3. Expired holds must stop blocking the slot.

Step 3 is where most implementations get it wrong. An exclusion constraint cannot reference now(), so an expired hold keeps blocking until something removes it. Do not rely only on a cron sweeper; clear conflicting expired holds inside the same transaction that creates a new one:

BEGIN;

DELETE FROM appointments
 WHERE provider_id = $1
   AND status = 'held'
   AND hold_expires_at < now()
   AND during && $2;

INSERT INTO appointments (provider_id, location_id, during, status, hold_expires_at)
VALUES ($1, $3, $2, 'held', now() + $4::interval)
RETURNING id;

COMMIT;

Promotion must check that the hold is still alive:

UPDATE appointments
   SET status = 'booked', hold_expires_at = NULL, patient_ref = $2
 WHERE id = $1
   AND status = 'held'
   AND hold_expires_at > now()
RETURNING id;

If the update returns zero rows, the hold expired. Try to insert the appointment directly as booked; the constraint will tell you whether someone else took the slot in the meantime. Keep a background sweeper anyway, for tidiness and so availability queries stay fast.

Alternatives and their trade-offs

The exclusion constraint is not the only correct design. These are the options teams usually weigh:

  • Pre-materialized slots with a unique key. Generate a slots table ahead of time and book with UPDATE slots SET status = 'taken' WHERE id = $1 AND status = 'free'. Simple and portable to any SQL database, and the conditional update is atomic. The cost: you must regenerate slots whenever schedules, durations or buffers change, and variable-length appointments become awkward.
  • Lock the provider row. Run SELECT ... FROM providers WHERE id = $1 FOR UPDATE, then check and insert. This serializes all bookings for one provider. It is correct and easy to reason about, but every code path that writes appointments must remember to take the lock. One forgotten path reintroduces the race.
  • SERIALIZABLE isolation. Keep the naive check-then-insert and run it at SERIALIZABLE. The database detects the conflict and aborts one transaction with a serialization failure, which you must retry. See the transaction isolation docs. It works, but correctness now depends on retry logic everywhere.
  • Distributed locks (Redis and similar). Tempting in microservice setups, but a lock outside the database that holds the data can expire or be lost while the write is still in flight. If you use one, treat it as a performance optimization on top of a database constraint, never as the guarantee.

The exclusion constraint wins in most cases because the rule is declared once and enforced for every writer: the API, an admin panel, a migration script or a future integration.

Make the booking endpoint idempotent

Mobile networks drop responses. A patient taps "Confirm", the request succeeds, the response is lost, the app retries. Without idempotency you either create a second appointment (if the slot is different) or show a confusing "slot taken" error for a slot they just booked. Have the client send an Idempotency-Key header (a UUID generated per booking attempt) and store it:

CREATE TABLE idempotency_keys (
  key          text PRIMARY KEY,
  request_hash text NOT NULL,
  status_code  int,
  response     jsonb,
  created_at   timestamptz NOT NULL DEFAULT now()
);
async function book(req) {
  const key = req.headers['idempotency-key'];
  const hash = sha256(canonicalJson(req.body));
  const inserted = await db.query(
    'INSERT INTO idempotency_keys (key, request_hash) VALUES ($1, $2) ON CONFLICT DO NOTHING',
    [key, hash]);

  if (inserted.rowCount === 0) {
    const prev = await getKey(key);
    if (prev.request_hash !== hash) return reply(422, 'Key reused with different body');
    if (prev.response === null)     return reply(409, 'Request in progress');
    return reply(prev.status_code, prev.response);
  }

  try {
    const result = await confirmBooking(req.body);  // holds + promotion
    await saveResponse(key, 201, result);
    return reply(201, result);
  } catch (e) {
    if (e.code === '23P01') {
      const body = { error: 'slot_taken', alternatives: await nextSlots(req.body) };
      await saveResponse(key, 409, body);
      return reply(409, body);
    }
    await deleteKey(key);  // allow a clean retry on unexpected errors
    throw e;
  }
}

Ideally the key insert and the booking happen in the same transaction, so a crash between them cannot leave a booked appointment with no stored response.

Computing availability

Availability is a derived value: working rules, minus time off, minus appointments, minus busy blocks from external calendars. Keep these as separate inputs and compute slots on read:

slots(provider, date):
  tz     = provider.location.timezone
  rules  = weekly_rules(provider, weekday(date))    // local wall-clock times
  window = rules converted to UTC instants for that date in tz
  busy   = appointments(status in held, booked)
         + time_off
         + external_busy_blocks
  free   = window minus busy
  return split(free, service.duration, step = service.step)

Convert rules to instants per date, not once, because the UTC offset of a zone can change across the year and governments change rules. Store IANA zone names, never fixed offsets, and keep the tzdata in your runtime and database up to date. Index during with GiST (the exclusion constraint already creates one) so overlap queries stay fast as history grows.

Syncing with external calendars

Providers often keep a personal calendar or an EHR/practice-management system that also holds appointments. Two rules keep sync from creating double bookings of its own:

  • Inbound: import busy blocks, not events. Store external busy intervals in their own table and subtract them during availability. Do not try to merge them into appointments; you do not own them and their IDs and edits follow someone else's rules.
  • Outbound: use an outbox. In the same transaction that books an appointment, insert a row into an outbox table. A worker reads it and pushes the event to the external calendar, retrying with backoff. This way a calendar API outage never rolls back a valid booking, and a booking never exists only in the external system.

External data is always slightly stale. If a provider adds a personal event that overlaps a booking already confirmed in your system, you cannot prevent it; detect it on import and alert the front desk instead of silently cancelling.

Keep patient data out of the booking pipeline

Scheduling systems for health care handle sensitive data. The engineering principle is minimization: the scheduling tables need a time, a resource and an opaque patient_ref. Names, contact details and reason for visit belong in a separate store with stricter access. In practice:

  • Never put patient names, reasons or emails in URLs, query strings or idempotency keys.
  • Strip request bodies from application logs and error trackers on booking routes.
  • Do not fire third-party analytics or ad pixels on booking confirmation pages with identifiable data; send only non-identifying events, if any.
  • Encrypt the patient store at rest, and log who reads it.

Which regulations apply (HIPAA in the United States, local data protection laws across Latin America) depends on your jurisdiction and role, so confirm requirements with legal counsel; the design above makes compliance easier either way.

Pre-launch checklist

  • Overlap rule enforced by a database constraint, not only application code.
  • Ranges are half-open and stored as timestamptz.
  • Holds expire and expired holds are cleared inside the booking transaction.
  • Promotion from held to booked is a single conditional update.
  • Constraint violations map to HTTP 409 with alternative slots.
  • Booking endpoint accepts and stores an idempotency key.
  • Availability computed per date in the location's IANA time zone.
  • External calendars imported as busy blocks; outbound sync through an outbox.
  • A concurrency test fires many parallel requests at one slot and asserts exactly one success.
  • No patient data in URLs, logs or third-party scripts.

Common mistakes

  • Checking availability in the frontend or in a cache and treating it as a guarantee.
  • Closed ranges [] that make back-to-back appointments collide.
  • Storing local times without a zone, then breaking when the offset changes.
  • Holds that never expire because the sweeper job stopped running.
  • Calling the external calendar API inside the booking transaction, so its latency or outages block your database.
  • Retrying on every error, including the 409, and hammering the database during peak hours.

If your scheduling logic has grown beyond what an off-the-shelf widget can handle (multiple locations, shared rooms, deposits, integrations), our team builds this kind of system as custom software for service businesses.

Frequently asked questions

Can I prevent double booking in MySQL, which has no exclusion constraints?

Yes. Use pre-materialized slots with a conditional update, or lock a parent row (the provider) with SELECT ... FOR UPDATE before checking and inserting. Both are correct if every write path follows them.

Does an exclusion constraint slow down inserts?

It adds a GiST index lookup per insert, which is the same work an overlap check would do anyway. For booking workloads, where writes are far rarer than reads, it is rarely the bottleneck; measure with your own data before optimizing.

How long should a hold last?

Long enough for a normal user to finish the form or payment, short enough that abandoned holds do not hide availability. Make it configurable per service and review abandonment data after launch.

Comments

No comments yet. Be the first to share what you think.

Leave a comment

It is never published.