Trending

World technology news

→
PostgreSQL 9.2: preventing overlapping instrument bookings
Software Engineering · 2012
Software Engineering2012

PostgreSQL 9.2: preventing overlapping instrument bookings

Use PostgreSQL 9.2 range types to design booking boundaries, concurrent writes and conflict tests for shared lab equipment.

Archive retrospective · Topic year 2012

Developer's JournalPublished: Nov 27, 20266 min read
Reading progress0%
In this article
  1. Two open forms create a data integrity problem
  2. Boundary choices are policy
  3. Expressing the conflict in the schema
  4. Exercise the 09:30 boundary
  5. Clean up an existing calendar before enforcing the rule
  6. Keep the behavior under test

Two open forms create a data integrity problem

Two technicians open a laboratory calendar for the same instrument. Both see a morning session as available. Their requests arrive seconds apart, with each request reading the calendar before inserting a booking. Both reads can be accurate and both inserts can still produce a conflict. Availability is a statement about the snapshot shown to the technician. A confirmation promises something about the database after a concurrent write. The range types documented for PostgreSQL 9.2 help make that distinction explicit. We will put the institution's rule in the schema using half-open timestamps. Adjacent sessions may share a boundary. Overlapping sessions on a single instrument may not share actual time. These are synthetic lab bookings for a technical exercise, with concrete outcomes you can verify.

Boundary choices are policy

A booking includes its start and excludes its end. Two sessions from 08:00 to 09:30 and 09:30 to 10:00 can therefore sit side by side. Moving the second start to 09:29 creates an overlap. Share this convention with the user interface and reports. Shifting an end time backwards by a millisecond makes future precision changes hazardous. A tstzrange compares actual instants, including offset differences. The application may still retain the named time zone to display local times or reschedule a session. When a transition produces two possible 02:30 instants, resolve the choice at the input boundary. An unknown maintenance end has different semantics from a confirmed session. Keeping empty and unbounded ranges out simplifies capacity checks and ambiguous conflict reports.

Database access flowConceptual sketch · summary of the article's technical flow
Technical referencesPostgreSQL 9.2 range types ↗

Expressing the conflict in the schema

The exclusion constraint says that two rows cannot both compare equal on instrument and overlap on their booked ranges. GiST can handle the overlap operator. The btree_gist extension supplies the necessary operator class for the integer instrument identifier in that same index. Different instruments remain independent. Non-null declarations matter because a null comparison does not become true. The check rejects empty or unbounded intervals, infinite timestamp values, and alternative boundary conventions. Confirm extension provisioning before an application deployment, especially in managed instances. The service credential can remain a writer without ownership of the extension. Identifiers may skip after an unsuccessful insert because a sequence can have allocated a value already. A gap in identifiers tells you little about the calendar's integrity. An accepted reservation determines the instrument's availability.

CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE calibration_booking (
  id bigserial PRIMARY KEY,
  instrument_id integer NOT NULL,
  booked tstzrange NOT NULL,
  CHECK (NOT isempty(booked)
    AND NOT lower_inf(booked) AND NOT upper_inf(booked)
    AND lower_inc(booked) AND NOT upper_inc(booked)
    AND isfinite(lower(booked)) AND isfinite(upper(booked))),
  EXCLUDE USING gist (instrument_id WITH =, booked WITH &&)
);

Exercise the 09:30 boundary

Three inserts should succeed. Two sessions touch at exactly 09:30 on instrument 7, while the third overlaps their times on instrument 8. A 09:15–09:45 query for instrument 7 should find both sessions. Try inserting that same window on instrument 7 and observe an exclusion violation. On instrument 9 it should succeed. Repeat with two connections. Open a transaction on the first, write a booking, and leave it open. Try a conflicting booking on the other connection. Commit the first transaction and observe the conflict in the second. Roll back the first transaction in a fresh trial and the second may proceed. Record the wait duration as well as the outcome. The client can ask the user to choose another time without disclosing any other technician's reservation.

INSERT INTO calibration_booking (instrument_id, booked)
VALUES
  (7, tstzrange('2012-12-03 08:00+00', '2012-12-03 09:30+00', '[)')),
  (7, tstzrange('2012-12-03 09:30+00', '2012-12-03 10:00+00', '[)')),
  (8, tstzrange('2012-12-03 09:00+00', '2012-12-03 10:00+00', '[)'));
SELECT id, booked
FROM calibration_booking
WHERE instrument_id = 7
  AND booked && tstzrange('2012-12-03 09:15+00', '2012-12-03 09:45+00', '[)')
ORDER BY lower(booked);

Clean up an existing calendar before enforcing the rule

If an older system stores separate start and end columns, collect exceptions before adding the constraint. List missing starts, end times no later than their start, and records whose named zone cannot be recovered. Collect conflicting pairs with both identifiers and device, and use increasing identifier order to report each pair once. Run this on a small copy before attempting a costly legacy join against production. Confirm which record to retain with the person who owns the schedule. A previously communicated booking may need human rescheduling even when the row is malformed. Rehearse adding the constraint and check locking during the maintenance window. The old availability lookup is still useful for a preview. Confirming an appointment should happen after the write transaction successfully completes.

Keep the behavior under test

Query exactly at the start and at the end to preserve the half-open contract. Send the same instant from clients using different UTC offsets and check that both cannot reserve it. Move a booking to a slot that another user holds and confirm that the original valid booking survives the failed update. If cancellation history remains in the table, choose which booking states the exclusion rule covers. Review the lookup plan with a realistically busy instrument instead of assuming a uniform distribution. Measure response time separately from integrity. The useful idea from 2012 is the combination of explicit boundaries and a database rule independent of every caller. A future calendar interface can change without taking responsibility for implementing the concurrency invariant again.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

Which alternative architecture would you try for the same problem?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.