Nov 20, 20268 min read

Build a Dock Appointment Scheduling Backend for Warehouses

Let carriers book dock doors without double bookings: slot availability from warehouse hours, a Postgres exclusion constraint on time ranges, bookings that cannot overlap even under concurrent requests, gate check-in, no-show detection on a schedule and events for carriers, in TypeScript with Encore.

Illustration for Build a Dock Appointment Scheduling Backend for Warehouses

Dock appointment scheduling is the warehouse system carriers see first: they pick a door and a time, and the warehouse plans labor around those bookings. When it is a shared calendar or a spreadsheet, two trucks end up booked on the same door, drivers wait in the yard, and the detention charges arrive weeks later.

This guide builds the backend in TypeScript: availability, bookings that cannot overlap, check-in and no-show handling.

The Dock Scheduling Backend at a Glance

PieceWhat it doesBuilt with
Warehouses and docksOpening hours, time zone, slot length, inbound or outbound doorsPostgres
AppointmentsCarrier, reference, time range and status per bookingPostgres with an exclusion constraint
Availability APIFree slots per dock for a daySQL with generate_series
Booking APIBooks a slot, rejects overlaps atomicallyINSERT ... ON CONFLICT DO NOTHING
No-show jobMarks missed appointments and releases the doorCron
Carrier eventsBooked and no-show notificationsPub/Sub

How Do You Stop Double Bookings?

Checking availability and then inserting is a race: two carriers load the same free slot, both submit, and both checks pass before either insert lands. The fix belongs in the database. Postgres range types store an appointment as a tstzrange, and an exclusion constraint rejects any row whose range overlaps another on the same dock.

Mixing equality on dock_id with overlap on the range in one GiST index needs the btree_gist extension, which RDS, Cloud SQL and local Postgres all support. A WHERE clause on the constraint limits it to active appointments, so cancelled and no-show bookings free the door. INSERT ... ON CONFLICT DO NOTHING also works with exclusion constraints, so a booking that loses the race returns no row instead of an error you have to parse.

Slots are defined in the warehouse's local hours, but stored as absolute times, so daylight saving changes do not shift a 07:00 appointment to 06:00.

How Do You Build It with Encore?

Encore

Encore is a backend framework with built-in infrastructure, so the scheduling database, the no-show job and the carrier event topic are declared in the docks service, and Encore provisions them in your own AWS or GCP account on deploy. Pallet built an event-driven AI logistics platform on GCP without touching Terraform.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Encore provisions the infrastructure your application needs in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create yard --example=ts/hello-world$ cd yard && mkdir -p docks/migrations
// docks/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("docks");

The migration enables btree_gist and puts the no-overlap rule on the table itself:

-- docks/migrations/1_init.up.sql CREATE EXTENSION IF NOT EXISTS btree_gist; CREATE TABLE warehouses ( id TEXT PRIMARY KEY, tz TEXT NOT NULL, -- e.g. 'America/Chicago' opens TIME NOT NULL, closes TIME NOT NULL, slot_minutes INT NOT NULL DEFAULT 60 ); CREATE TABLE docks ( id TEXT PRIMARY KEY, warehouse_id TEXT NOT NULL REFERENCES warehouses (id), kind TEXT NOT NULL CHECK (kind IN ('inbound', 'outbound')) ); CREATE TABLE appointments ( id BIGSERIAL PRIMARY KEY, dock_id TEXT NOT NULL REFERENCES docks (id), carrier TEXT NOT NULL, reference TEXT NOT NULL, -- PO or load number slot TSTZRANGE NOT NULL, status TEXT NOT NULL DEFAULT 'booked' CHECK (status IN ('booked', 'checked_in', 'completed', 'no_show', 'cancelled')), checked_in_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), EXCLUDE USING gist (dock_id WITH =, slot WITH &&) WHERE (status IN ('booked', 'checked_in')) );

Availability and booking

Availability generates the day's slots in the warehouse's time zone and removes any that overlap an active appointment. Booking inserts with ON CONFLICT DO NOTHING, so a lost race comes back as a clean alreadyExists error:

// docks/booking.ts import { api, APIError } from "encore.dev/api"; import { Topic } from "encore.dev/pubsub"; import { SQLDatabase } from "encore.dev/storage/sqldb"; export const db = new SQLDatabase("docks", { migrations: "./migrations" }); export interface AppointmentEvent { appointmentId: number; carrier: string; reference: string; type: "booked" | "no_show"; } export const appointmentEvents = new Topic<AppointmentEvent>("appointment-events", { deliveryGuarantee: "at-least-once", }); interface Slot { dockId: string; start: Date; } export const availability = api( { expose: true, method: "GET", path: "/warehouses/:warehouseId/availability" }, async (p: { warehouseId: string; date: string; kind: string }): Promise<{ slots: Slot[] }> => { const slots = await db.queryAll<Slot>` SELECT d.id AS "dockId", s AS "start" FROM warehouses w JOIN docks d ON d.warehouse_id = w.id AND d.kind = ${p.kind} CROSS JOIN LATERAL generate_series( (${p.date}::date + w.opens) AT TIME ZONE w.tz, (${p.date}::date + w.closes - make_interval(mins => w.slot_minutes)) AT TIME ZONE w.tz, make_interval(mins => w.slot_minutes)) AS s WHERE w.id = ${p.warehouseId} AND s > now() AND NOT EXISTS ( SELECT 1 FROM appointments a WHERE a.dock_id = d.id AND a.status IN ('booked', 'checked_in') AND a.slot && tstzrange(s, s + make_interval(mins => w.slot_minutes))) ORDER BY s, d.id`; return { slots }; }, ); interface BookParams { dockId: string; start: string; // ISO timestamp from the availability response slots: number; // 1 to 4 consecutive slots carrier: string; reference: string; } export const book = api( { expose: true, method: "POST", path: "/appointments" }, async (p: BookParams): Promise<{ id: number }> => { if (p.slots < 1 || p.slots > 4) { throw APIError.invalidArgument("slots must be between 1 and 4"); } const row = await db.queryRow<{ id: number }>` INSERT INTO appointments (dock_id, carrier, reference, slot) SELECT d.id, ${p.carrier}, ${p.reference}, tstzrange(${p.start}::timestamptz, ${p.start}::timestamptz + make_interval(mins => w.slot_minutes * ${p.slots})) FROM docks d JOIN warehouses w ON w.id = d.warehouse_id WHERE d.id = ${p.dockId} AND ${p.start}::timestamptz > now() AND (${p.start}::timestamptz AT TIME ZONE w.tz)::time >= w.opens AND (${p.start}::timestamptz AT TIME ZONE w.tz)::time + make_interval(mins => w.slot_minutes * ${p.slots}) <= w.closes ON CONFLICT DO NOTHING RETURNING id`; if (!row) { throw APIError.alreadyExists("that dock is already booked for this time, or the time is outside opening hours"); } await appointmentEvents.publish({ appointmentId: row.id, carrier: p.carrier, reference: p.reference, type: "booked", }); return { id: row.id }; }, );

Two carriers submitting the same slot at the same moment get one id and one already_exists, decided by Postgres, with no lock in application code. The hours check in the WHERE clause keeps a client from booking 03:00 on a door that opens at 06:00. A production version also authenticates carriers with an auth handler and takes the carrier from the auth data rather than the request body.

Check-in and no-shows

The gate marks arrival, and a cron job every 15 minutes turns booked appointments that are more than 30 minutes past their start into no-shows, which releases the door through the constraint's WHERE clause:

// docks/gate.ts import { api, APIError } from "encore.dev/api"; import { CronJob } from "encore.dev/cron"; import log from "encore.dev/log"; import { appointmentEvents, db } from "./booking"; export const checkIn = api( { expose: true, method: "POST", path: "/appointments/:id/check-in" }, async ({ id }: { id: number }): Promise<{ minutesLate: number }> => { const row = await db.queryRow<{ minutes_late: number }>` UPDATE appointments SET status = 'checked_in', checked_in_at = now() WHERE id = ${id} AND status = 'booked' RETURNING floor(extract(epoch FROM now() - lower(slot)) / 60)::int AS minutes_late`; if (!row) { throw APIError.failedPrecondition("appointment is not in booked state"); } return { minutesLate: row.minutes_late }; }, ); export const markNoShows = api({}, async (): Promise<{ marked: number }> => { const rows = await db.queryAll<{ id: number; carrier: string; reference: string }>` UPDATE appointments SET status = 'no_show' WHERE status = 'booked' AND lower(slot) < now() - interval '30 minutes' RETURNING id, carrier, reference`; for (const r of rows) { await appointmentEvents.publish({ appointmentId: r.id, carrier: r.carrier, reference: r.reference, type: "no_show", }); } if (rows.length > 0) { log.info("no-shows marked", { count: rows.length }); } return { marked: rows.length }; }); const _ = new CronJob("mark-no-shows", { title: "Mark missed dock appointments", every: "15m", endpoint: markNoShows, });

A negative minutesLate means the truck arrived early, which yard teams often want to see as much as lateness. A subscriber on appointment-events can email or call the carrier's API, and a scorecard service can count no-shows per carrier from the same events.

Run it locally and deploy

encore run starts Postgres with btree_gist available, so you can seed a warehouse, fire two parallel bookings at the same slot with curl and watch one succeed. Cron jobs do not run locally, so call markNoShows directly in tests. On deploy to your AWS or GCP account, the database becomes RDS or Cloud SQL and the topic becomes SNS with SQS or Google Pub/Sub, as described in the infrastructure docs, and the no-show schedule is managed by the Encore platform.

Rules change often in yard operations, such as a longer grace period for one carrier or a door reserved for refrigerated loads, and a coding agent can change the migration, the query and the job in one diff and prove it against local Postgres before anyone touches the live schedule.

Best fit: logistics and warehouse teams who want carrier self-service booking that cannot double-book a door, with check-in and no-show events running in their own AWS or GCP account.

Things to Decide Early

  • Slot length by load type. Floor-loaded containers take longer than palletized trucks, so tie duration to the load, not only the door.
  • Door capabilities. Refrigerated, oversized or hazmat loads need doors that support them; add a capability column and filter on it.
  • Booking windows. Decide how far ahead carriers can book and the cutoff for changes, and enforce both in the booking query.
  • Overbooking policy. Some sites allow a small number of floating appointments not tied to a door; model them separately from the constraint.
  • Labor planning. Expose booked volume per hour so the warehouse can staff receiving shifts around it.

Frequently asked questions

How do I prevent double booking of dock doors?

Store each appointment's time as a tstzrange and add an exclusion constraint with btree_gist: EXCLUDE USING gist (dock_id WITH =, slot WITH &&) for active appointments. Postgres then rejects any overlapping booking for the same door, even when two requests arrive at the same moment, which an application-level availability check cannot guarantee.

How do I compute available dock appointment slots?

Generate the slots for the day from the warehouse's opening hours and slot length in its local time zone with generate_series, then remove slots that overlap an active appointment on the same dock using the range overlap operator &&.

How should a scheduling system handle no-shows?

Mark a booked appointment as a no-show once a grace period after its start passes without a gate check-in, release the door for walk-ins, and publish an event so carrier scorecards and notifications can react. A job that runs every 15 minutes is usually frequent enough.

How do I build a dock scheduling backend with Encore?

Declare a SQLDatabase with a migration that enables btree_gist and adds the exclusion constraint, write booking endpoints that insert with ON CONFLICT DO NOTHING and return an alreadyExists error when no row comes back, and add a CronJob that marks no-shows and publishes them to a Topic.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders