DEV Community

Cover image for How to build a booking system in Node.js with NestJS: preventing double bookings
Kamil Mysliwiec for NestJS

Posted on

How to build a booking system in Node.js with NestJS: preventing double bookings

On paper, a booking system is one of the friendliest backends you can build. Some rooms, a table of bookings, a page of free slots, a cancel button. Whatever you pick in Node.js, the first version takes an afternoon. Then two people click "Book" on the same 10:00 slot a few milliseconds apart, and both of them get a confirmation.

The obvious fix is a check in the service: query for a confirmed booking of that room whose times cross the new one's, and only insert when the query comes back empty. It reads correctly, and it passes any test that sends one request at a time. Send two of those requests at the same moment, though, and each runs its query before the other has written anything, so each sees an empty calendar and each writes a booking. The race test at the end of this post ran ten users against that version, and it accepted between five and ten bookings of the one slot, in each of five runs.

So in this app, the rule isn't enforced by application code at all. It's an exclusion constraint in PostgreSQL: the database itself rejects whichever of two clashing bookings comes second, no matter how close together they were sent or which code sent them, and the API translates the rejection into a 409 Conflict. The rest of the system is built around it: time zones that survive daylight saving time, a list of free slots computed in one query, and cancellation as one conditional statement.

This post builds the whole application with NestJS 12, PostgreSQL and Drizzle: every file, the migrations, a session with curl, the tests and a production checklist. The same app lives in the docs as Build a booking system in Node.js without double bookings.

What the API does

The API manages resources, such as meeting rooms, and bookings of them. When it's finished:

  • Reads are public, writes are for staff: anyone can browse resources and see which slots of a day are still open, while creating and editing resources takes the staff role, checked with @nestjs/authorization.
  • Clients send times in ISO 8601 with an explicit offset; the database keeps them as UTC instants, and every response gives them back in UTC.
  • Overlapping bookings of one resource get a 409, because a PostgreSQL exclusion constraint refuses them, regardless of what the application code does.
  • A booking can be cancelled until 24 hours before its start, in a single conditional UPDATE.
  • A test against a real PostgreSQL server sends ten simultaneous bookings for one slot and checks that exactly one of them wins.

These are the routes, grouped by the section that adds them:

  • Sign-in and health, from the JWT API: POST /auth/sign-up, POST /auth/token, POST /auth/token/refresh, POST /auth/token/revoke, GET /me, GET /health/live, GET /health/ready.
  • Resources: GET /resources, GET /resources/:id, POST /resources, PATCH /resources/:id.
  • Bookings: POST /bookings, GET /bookings, GET /bookings/:id.
  • Free slots: GET /resources/:id/availability.
  • Cancellation: POST /bookings/:id/cancel.

The code was run with @nestjs/core 12.5.1, @nestjs/authentication 0.1.6, @nestjs/authorization 0.1.4, drizzle-orm and drizzle-kit 1.0.0-rc.5, pg 8.23.1, Zod 4.6.7, Vitest 5.1.1 and Node.js 24.

Set up the project

The sign-in side is the API from Build a REST API with JWT authentication: access and refresh tokens from @nestjs/authentication, request validation with Zod, and PostgreSQL through Drizzle. I won't explain it again here. The packages are the JWT API's, plus @nestjs/authorization:

$ npm i -g @nestjs/cli
$ nest new booking-api --minimal
$ cd booking-api
$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication @nestjs/authorization @nestjs/throttler @nestjs/swagger @nestjs/terminus
$ npm i --save-dev drizzle-kit@rc @types/pg @nestjs/testing vitest vite
Enter fullscreen mode Exit fullscreen mode

Then add the JWT API's files: src/config.ts, src/main.ts, drizzle.config.ts, vitest.config.e2e.ts, everything under src/auth/, src/users/ and src/health/, and test/refresh-token.store.e2e-spec.ts. So that this post stands on its own, they're all listed in full in the appendix at the end, already renamed for the booking system (the realm in JwtAuth is booking, and the OpenAPI document is titled "Booking API"). The JWT API's notes module and its drizzle/ folder don't come along: the first migration here is generated from this app's own schema, a section from now.

The end-to-end tests need a script in package.json:

"test:e2e": "vitest run --config ./vitest.config.e2e.ts"
Enter fullscreen mode Exit fullscreen mode

The booking system gets a database of its own. With Docker:

$ docker run -d --name booking-db -e POSTGRES_PASSWORD=booking -e POSTGRES_DB=booking -p 5432:5432 postgres:17
Enter fullscreen mode Exit fullscreen mode

Its URL goes in .env, together with the secret that signs the access tokens:

DATABASE_URL=postgres://postgres:booking@localhost:5432/booking
# Generate with: openssl rand -base64 32
JWT_SECRET=
Enter fullscreen mode Exit fullscreen mode

Staff and the people who book sign in the same way, so the one change to the user is a role:

// src/users/user.ts
export type Role = 'customer' | 'staff';

export interface User {
  id: string;
  email: string;
  role: Role;
  createdAt: Date;
}
Enter fullscreen mode Exit fullscreen mode

UsersRepository selects the role along with the other columns (const columns = { id: users.id, email: users.email, role: users.role, createdAt: users.createdAt }, in the appendix). The role is deliberately not in the access token. JwtAuth.validate() loads the user on every request, so when someone is promoted to staff, or demoted, it applies from their next request, with no token to reissue.

Design the schema for bookings and time zones

Here's the whole schema in one file. The users and refresh_tokens tables come from the JWT API unchanged, except for the new role column:

// src/database/schema.ts
import { sql } from 'drizzle-orm';
import { boolean, check, index, integer, jsonb, pgTable, text, time, timestamp, uuid } from 'drizzle-orm/pg-core';

// timestamptz: an instant, stored in UTC, whatever offset the client sent.
const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: text('email').notNull().unique(),
  passwordHash: text('password_hash').notNull(),
  role: text('role', { enum: ['customer', 'staff'] }).notNull().default('customer'),
  createdAt: at('created_at').notNull().defaultNow(),
});

export const resources = pgTable(
  'resources',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    name: text('name').notNull(),
    // The IANA time zone of the opening hours, such as Europe/Warsaw.
    timeZone: text('time_zone').notNull(),
    // Local times of day, in `timeZone`.
    opensAt: time('opens_at').notNull(),
    closesAt: time('closes_at').notNull(),
    // The length of the slots that availability lists.
    slotMinutes: integer('slot_minutes').notNull(),
    active: boolean('active').notNull().default(true),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [check('resources_opens_before_closes', sql`${table.opensAt} < ${table.closesAt}`)],
);

export const bookings = pgTable(
  'bookings',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    resourceId: uuid('resource_id')
      .notNull()
      .references(() => resources.id),
    userId: uuid('user_id')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    // The booking is the half-open range [startsAt, endsAt).
    startsAt: at('starts_at').notNull(),
    endsAt: at('ends_at').notNull(),
    status: text('status', { enum: ['confirmed', 'cancelled'] }).notNull().default('confirmed'),
    createdAt: at('created_at').notNull().defaultNow(),
    cancelledAt: at('cancelled_at'),
  },
  (table) => [
    check('bookings_ends_after_starts', sql`${table.endsAt} > ${table.startsAt}`),
    index('bookings_user_id_starts_at_idx').on(table.userId, table.startsAt),
    // The exclusion constraint that prevents double bookings is in a custom migration.
  ],
);

// What @nestjs/authentication keeps for refresh tokens, stored by their SHA-256.
export const refreshTokens = pgTable(
  'refresh_tokens',
  {
    id: text('id').primaryKey(),
    familyId: text('family_id').notNull(),
    userId: text('user_id').notNull(),
    createdAt: at('created_at').notNull(),
    expiresAt: at('expires_at').notNull(),
    familyExpiresAt: at('family_expires_at').notNull(),
    usedAt: at('used_at'),
    // A family is revoked when any of its tokens is.
    revoked: boolean('revoked').notNull().default(false),
    claims: jsonb('claims').$type<Record<string, unknown>>(),
  },
  (table) => [
    index('refresh_tokens_family_id_idx').on(table.familyId),
    index('refresh_tokens_user_id_idx').on(table.userId),
    index('refresh_tokens_family_expires_at_idx').on(table.familyExpiresAt),
  ],
);

export type Resource = typeof resources.$inferSelect;
export type Booking = typeof bookings.$inferSelect;
Enter fullscreen mode Exit fullscreen mode

Most of the bugs a booking system can have are decided in that file, so here's what each choice is for:

  • Every instant is a timestamptz. The name timestamp with time zone is misleading: PostgreSQL doesn't keep a time zone in it. It converts whatever offset the client sent and stores the instant, in UTC. Without the time zone part, a column holds a bare 10:00 with no place attached, and a client in Lisbon and one in Warsaw would read two different moments into the same value.
  • A booking covers its start but not its end, a half-open range in math terms. That's what makes 10:00 to 11:00 and 11:00 to 12:00 not overlap, which is what everyone means by back to back.
  • Opening hours are local times, next to their time zone. A room in Warsaw opens at 09:00 Warsaw time all year. That's 08:00 UTC in winter and 07:00 UTC in summer, so storing 08:00 UTC would be wrong for half the year.
  • Cancelling doesn't delete. A cancelled booking keeps its row and gets a status, so the history stays, and the constraint in the next section skips it.
  • A CHECK keeps ends_at after starts_at. A reversed range is an error in PostgreSQL, and a booking with no length couldn't collide with anything, so neither should reach the table.

With the schema in place, drizzle-kit writes the first migration and applies it to the database (Migrations has the details):

$ npx drizzle-kit generate --name=booking
$ npx drizzle-kit migrate
Enter fullscreen mode Exit fullscreen mode

Prevent double bookings in PostgreSQL with an exclusion constraint

Back to the check-then-insert version from the introduction. It isn't wrong because the check is written badly; it's wrong because a check and an insert are two steps, and nothing stops a second request from running its check between them. In the race test, it let through five to ten bookings of one slot per run, in five runs out of five.

PostgreSQL can hold the rule itself. A unique constraint says that no two rows have equal values in some columns. An exclusion constraint is the same idea with any operator: here, no two rows of one resource may have time ranges that overlap. PostgreSQL checks it on every insert and update, from any code, including statements that run at the same time, and fails the statement that would break it.

Drizzle can't declare an exclusion constraint in the schema file, so drizzle-kit generate will never emit one. It has to be hand-written SQL in a custom migration: pass --custom, and drizzle-kit creates an empty migration file that is applied in sequence with the generated ones:

$ npx drizzle-kit generate --custom --name=no_double_bookings
Enter fullscreen mode Exit fullscreen mode

Open the file it created, drizzle/<timestamp>_no_double_bookings/migration.sql, and put the extension and the constraint in it:

-- btree_gist lets a GiST index compare uuid columns with =.
CREATE EXTENSION IF NOT EXISTS btree_gist;
--> statement-breakpoint
-- No two confirmed bookings of one resource may overlap. tstzrange() builds
-- half-open ranges, [starts_at, ends_at), so back-to-back bookings don't.
ALTER TABLE bookings ADD CONSTRAINT bookings_no_overlap
  EXCLUDE USING gist (resource_id WITH =, tstzrange(starts_at, ends_at) WITH &&)
  WHERE (status = 'confirmed');
Enter fullscreen mode Exit fullscreen mode

It's short, but every part of it matters:

  • resource_id WITH =, tstzrange(starts_at, ends_at) WITH && defines a clash: equal resource_id, and ranges that overlap (&&). Two rooms can be booked for the same hour without any conflict.
  • tstzrange(starts_at, ends_at) computes a range out of the two timestamp columns, so there's no range column to store, and the TypeScript side deals only in timestamps. Unless told otherwise, it uses [) bounds, which is what lets one booking end at 11:00 and the next start at 11:00.
  • WHERE (status = 'confirmed') restricts the rule to live bookings. Once cancelled, a booking stops occupying its time, and new bookings are free to overlap it.
  • btree_gist is required because PostgreSQL enforces the constraint through a GiST index, and out of the box GiST has no = for uuid. The extension is part of the standard PostgreSQL distribution. The same index helps the free-slots query later on.
  • --> statement-breakpoint is how drizzle-kit marks where one statement ends and the next begins; its generated migrations use the same marker.

Then apply it. Custom migrations are invisible to drizzle-kit's schema diff, so the constraint isn't something it tracks, and a later generate won't try to remove it, as the second command shows:

$ npx drizzle-kit migrate
$ npx drizzle-kit generate
No schema changes, nothing to migrate
Enter fullscreen mode Exit fullscreen mode

Let staff manage resources

@nestjs/authorization expresses permissions as policies: classes whose methods answer "may this user do this?". Its module registers a global guard, and so does AuthenticationModule. The authorization guard needs the user that authentication sets, so AuthorizationModule goes right after AuthenticationModule. Here is the finished root module, with every feature module of the booking system already imported:

// src/app.module.ts
import { Module, StandardSchemaValidationPipe } from '@nestjs/common';
import { APP_GUARD, APP_PIPE } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthenticationModule } from '@nestjs/authentication';
import { AuthorizationModule } from '@nestjs/authorization';
import { DrizzleModule } from '@nestjs/drizzle';
import { createObserveModule } from '@nestjs/observe';
import { ThrottlerGuard, ThrottlerModule, minutes, normalizeIp } from '@nestjs/throttler';
import { drizzle } from 'drizzle-orm/node-postgres';
import { accountEmail } from './auth/account-email.js';
import { AuthModule } from './auth/auth.module.js';
import { BookingsModule } from './bookings/bookings.module.js';
import { envSchema, type Env } from './config.js';
import { HealthModule } from './health/health.module.js';
import { ResourcesModule } from './resources/resources.module.js';
import { UsersModule } from './users/users.module.js';

export const { ObserveModule, ObserveInstrument } = createObserveModule();

@Module({
  imports: [
    // First, so it shuts down last and still sends what the other modules did.
    ObserveModule.forRoot({
      // Empty until `npx @nestjs/observe link` writes the key pair into .env: the SDK then sends nothing.
      appKey: process.env.OBSERVE_APP_KEY ?? '',
      appSecret: process.env.OBSERVE_APP_SECRET ?? '',
      serviceId: 'booking-api',
    }),
    ConfigModule.forRoot({ isGlobal: true, validationSchema: envSchema }),
    DrizzleModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        drizzle,
        connection: config.get('DATABASE_URL', { infer: true }),
      }),
    }),
    AuthenticationModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        accessToken: {
          key: config.get('JWT_SECRET', { infer: true }),
          issuer: 'booking-api',
          audience: 'booking-api',
          ttl: '15m',
        },
        refreshToken: { ttl: '30d', absoluteTtl: '90d' },
      }),
    }),
    // After AuthenticationModule: its guard reads the user that authentication sets.
    AuthorizationModule.forRoot(),
    ThrottlerModule.forRoot([
      // Per IP address, on every route.
      { name: 'default', ttl: minutes(1), limit: 100 },
      // Per email and IP address, wherever the request body names an account.
      {
        name: 'account',
        ttl: minutes(15),
        limit: 5,
        skipIf: (context) => !accountEmail(context.switchToHttp().getRequest()),
        getTracker: (req) => `${accountEmail(req)}|${normalizeIp(req.ip)}`,
      },
    ]),
    UsersModule,
    AuthModule,
    ResourcesModule,
    BookingsModule,
    HealthModule,
  ],
  providers: [
    { provide: APP_PIPE, useClass: StandardSchemaValidationPipe },
    { provide: APP_GUARD, useClass: ThrottlerGuard },
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Out of the box, the authorization guard denies: unless a route states who may call it, it doesn't run. There are three ways to state it. @Can() checks a policy, @Can.Anyone() admits every caller that got past authentication, and @Public() is treated like @Can.Anyone(). I like this default a lot for a system like this one, because the route somebody forgets to annotate is closed rather than open. The JWT API's routes under /auth and /health are @Public() already. GET /me is for any signed-in user, so it gets @Can.Anyone():

// src/users/me.controller.ts
import { Controller, Get } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import type { User } from './user.js';

@Can.Anyone()
@Controller('me')
export class MeController {
  @Get()
  me(@CurrentUser() user: User) {
    return user;
  }
}
Enter fullscreen mode Exit fullscreen mode

The policy for resources has a single ability, managing them. Because a guest arrives as null, the method takes User | null, which lets the guard evaluate it whether or not anyone signed in:

// src/resources/resource.policy.ts
import { Policy } from '@nestjs/authorization';
import type { User } from '../users/user.js';

@Policy()
export class ResourcePolicy {
  // `null` is a guest.
  manage(user: User | null) {
    return user?.role === 'staff';
  }
}
Enter fullscreen mode Exit fullscreen mode

The request schemas come next. The file already includes the query string of the free-slots route, which a later section adds:

// src/resources/resources.schemas.ts
import { z } from 'zod';

const name = z.string().trim().min(1).max(200);
// Any IANA time zone the runtime knows, such as Europe/Warsaw.
const timeZone = z.string().refine(isTimeZone, 'Unknown time zone');
// A local time of day, HH:MM.
const timeOfDay = z.iso.time({ precision: -1 });
const slotMinutes = z.number().int().min(5).max(480);

export const createResourceSchema = z
  .object({ name, timeZone, opensAt: timeOfDay, closesAt: timeOfDay, slotMinutes })
  .refine((r) => r.opensAt < r.closesAt, { message: 'Must be after opensAt', path: ['closesAt'] });
export type CreateResourceDto = z.infer<typeof createResourceSchema>;

// The time zone and opening hours stay as created: changing them would leave
// existing bookings outside the hours.
export const updateResourceSchema = z.object({ name, slotMinutes, active: z.boolean() }).partial();
export type UpdateResourceDto = z.infer<typeof updateResourceSchema>;

export const availabilityQuerySchema = z.object({
  // A day in the resource's time zone.
  date: z.iso.date(),
});
export type AvailabilityQuery = z.infer<typeof availabilityQuerySchema>;

function isTimeZone(value: string): boolean {
  // Names only: PostgreSQL reads an offset such as +01:00 the POSIX way, with the sign flipped.
  if (/^[+-]/.test(value)) {
    return false;
  }
  try {
    new Intl.DateTimeFormat('en-US', { timeZone: value });
    return true;
  } catch {
    return false;
  }
}
Enter fullscreen mode Exit fullscreen mode

isTimeZone() has two traps hiding behind it. The obvious list to validate against is Intl.supportedValuesOf('timeZone'), but it holds only canonical names and leaves out UTC, so the function asks the runtime's time zone database instead, which accepts IANA names, their aliases and UTC. That database also accepts an offset such as +01:00, and that one is worse: PostgreSQL's AT TIME ZONE reads it as a POSIX offset, with east and west swapped. A room created with +01:00 would open two hours off, and nothing would raise an error. So anything that starts with a sign is refused.

The service is plain Drizzle:

// src/resources/resources.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { resources, type Resource } from '../database/schema.js';
import type { CreateResourceDto, UpdateResourceDto } from './resources.schemas.js';

@Injectable()
export class ResourcesService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  findAll(): Promise<Resource[]> {
    return this.db.select().from(resources).where(eq(resources.active, true)).orderBy(asc(resources.name)).limit(100);
  }

  async findOne(id: string): Promise<Resource> {
    const [resource] = await this.db
      .select()
      .from(resources)
      .where(and(eq(resources.id, id), eq(resources.active, true)));
    return resource ?? notFound();
  }

  async create(dto: CreateResourceDto): Promise<Resource> {
    const [resource] = await this.db.insert(resources).values(dto).returning();
    return resource;
  }

  async update(id: string, dto: UpdateResourceDto): Promise<Resource> {
    const [resource] = await this.db.update(resources).set(dto).where(eq(resources.id, id)).returning();
    return resource ?? notFound();
  }
}

function notFound(): never {
  throw new NotFoundException('Resource not found');
}
Enter fullscreen mode Exit fullscreen mode

Bookings point at resources, so a resource is deactivated rather than deleted. In the controller, anyone may read, while creating and editing go through the policy before the handler is reached. A guest who tries to create a room gets a 401, which means "sign in", and a signed-in customer gets a 403, which means signing in won't help:

// src/resources/resources.controller.ts
import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { ApiSecurity } from '@nestjs/swagger';
import { z } from 'zod';
import { ResourcePolicy } from './resource.policy.js';
import {
  createResourceSchema,
  updateResourceSchema,
  type CreateResourceDto,
  type UpdateResourceDto,
} from './resources.schemas.js';
import { ResourcesService } from './resources.service.js';

const resourceId = { schema: z.uuid() };

@Controller('resources')
export class ResourcesController {
  constructor(private readonly resourcesService: ResourcesService) {}

  @Public()
  @ApiSecurity({})
  @Get()
  findAll() {
    return this.resourcesService.findAll();
  }

  @Public()
  @ApiSecurity({})
  @Get(':id')
  findOne(@Param('id', resourceId) id: string) {
    return this.resourcesService.findOne(id);
  }

  @Can(ResourcePolicy, 'manage')
  @Post()
  create(@Body({ schema: createResourceSchema }) dto: CreateResourceDto) {
    return this.resourcesService.create(dto);
  }

  @Can(ResourcePolicy, 'manage')
  @Patch(':id')
  update(@Param('id', resourceId) id: string, @Body({ schema: updateResourceSchema }) dto: UpdateResourceDto) {
    return this.resourcesService.update(id, dto);
  }
}
Enter fullscreen mode Exit fullscreen mode

The policy is registered as a provider of its module, which is where the authorization module finds it:

// src/resources/resources.module.ts
import { Module } from '@nestjs/common';
import { ResourcePolicy } from './resource.policy.js';
import { ResourcesController } from './resources.controller.js';
import { ResourcesService } from './resources.service.js';

@Module({
  controllers: [ResourcesController],
  providers: [ResourcesService, ResourcePolicy],
})
export class ResourcesModule {}
Enter fullscreen mode Exit fullscreen mode

Sign-up only ever creates customers. The first staff member is promoted in the database directly; after that, an admin screen of your own can do it:

$ docker exec booking-db psql -U postgres -d booking -c "UPDATE users SET role = 'staff' WHERE email = 'sam@example.com'"
Enter fullscreen mode Exit fullscreen mode

Book without double bookings

To book, a client sends the resource's id plus a start and an end. Both have to carry an offset: Z for UTC, or one such as +01:00. A time without one, such as 2026-12-01T10:00:00, is a different instant in every time zone, so instead of guessing, the API answers 400:

// src/bookings/bookings.schemas.ts
import { z } from 'zod';

// An instant with an explicit offset, such as 2026-12-01T10:00:00+01:00 or ...Z.
// A local time without one ("10:00 where?") is a 400.
const instant = z.iso.datetime({ offset: true }).transform((value) => new Date(value));

export const createBookingSchema = z
  .object({ resourceId: z.uuid(), startsAt: instant, endsAt: instant })
  .refine((b) => b.endsAt > b.startsAt, { message: 'Must be after startsAt', path: ['endsAt'] });
export type CreateBookingDto = z.infer<typeof createBookingSchema>;
Enter fullscreen mode Exit fullscreen mode

The handler gets the schema's output, Date objects. The OpenAPI document describes the input, strings in the date-time format, so clients see what they have to send.

An insert that would break the constraint fails with SQLSTATE 23P01 (exclusion_violation), and the error carries the constraint's name. Drizzle adds a layer on top: what the code catches is a DrizzleQueryError whose message is the SQL that failed, with the pg driver's DatabaseError inside it as cause. This helper unwraps it:

// src/database/errors.ts
import { DrizzleQueryError } from 'drizzle-orm';
import { DatabaseError } from 'pg';

/** Whether a query failed because it would have violated the named exclusion constraint. */
export function isExclusionViolation(error: unknown, constraint: string): boolean {
  // Drizzle wraps the driver's error: the PostgreSQL error is its `cause`.
  const cause = error instanceof DrizzleQueryError ? error.cause : error;
  // 23P01 is exclusion_violation.
  return cause instanceof DatabaseError && cause.code === '23P01' && cause.constraint === constraint;
}
Enter fullscreen mode Exit fullscreen mode

In the service, the insert is wrapped in a try, and only that specific error becomes a 409:

// src/bookings/bookings.service.ts
import { ConflictException, Injectable, NotFoundException, UnprocessableEntityException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, eq, gt, sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { isExclusionViolation } from '../database/errors.js';
import { bookings, resources, type Booking } from '../database/schema.js';
import type { CreateBookingDto } from './bookings.schemas.js';

@Injectable()
export class BookingsService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  async create(userId: string, { resourceId, startsAt, endsAt }: CreateBookingDto): Promise<Booking> {
    // A time of day in the resource's time zone.
    const local = (instant: Date) => sql`(${instant}::timestamptz AT TIME ZONE ${resources.timeZone})`;
    try {
      // One statement: inserts the booking only if the resource is active and the
      // booking fits its opening hours. The exclusion constraint does the rest.
      const [booking] = await this.db
        .insert(bookings)
        .select((qb) =>
          qb
            .select({
              resourceId: resources.id,
              userId: sql`${userId}::uuid`.as('user_id'),
              startsAt: sql`${startsAt}::timestamptz`.as('starts_at'),
              endsAt: sql`${endsAt}::timestamptz`.as('ends_at'),
            })
            .from(resources)
            .where(
              and(
                eq(resources.id, resourceId),
                eq(resources.active, true),
                sql`${startsAt}::timestamptz > now()`,
                sql`${local(startsAt)}::date = ${local(endsAt)}::date`,
                sql`${local(startsAt)}::time >= ${resources.opensAt}`,
                sql`${local(endsAt)}::time <= ${resources.closesAt}`,
              ),
            )
            // Locks the resource's row: bookings of one resource take turns.
            .for('no key update'),
        )
        .returning();
      return booking ?? (await this.refuseBooking(resourceId));
    } catch (error) {
      if (isExclusionViolation(error, 'bookings_no_overlap')) {
        throw new ConflictException('The resource is already booked at that time');
      }
      throw error;
    }
  }

  findUpcoming(userId: string): Promise<Booking[]> {
    return this.db
      .select()
      .from(bookings)
      .where(and(eq(bookings.userId, userId), gt(bookings.endsAt, sql`now()`)))
      .orderBy(asc(bookings.startsAt))
      .limit(100);
  }

  async findOne(userId: string, id: string): Promise<Booking> {
    const [booking] = await this.db.select().from(bookings).where(this.owned(userId, id));
    if (!booking) {
      throw new NotFoundException('Booking not found');
    }
    return booking;
  }

  private owned(userId: string, id: string) {
    return and(eq(bookings.id, id), eq(bookings.userId, userId));
  }

  /** Why the insert added no row: 404 for an unknown resource, 422 for times that don't fit. */
  private async refuseBooking(resourceId: string): Promise<never> {
    const [resource] = await this.db
      .select({ id: resources.id })
      .from(resources)
      .where(and(eq(resources.id, resourceId), eq(resources.active, true)));
    if (!resource) {
      throw new NotFoundException('Resource not found');
    }
    throw new UnprocessableEntityException('A booking must start in the future, within the opening hours of one day');
  }
}
Enter fullscreen mode Exit fullscreen mode

This is the method the whole system depends on, so it's worth reading slowly:

  • Nothing in it looks for overlapping bookings. The insert either commits or fails on the constraint, and the catch turns that one failure into a 409: the slot is taken, and another one may still be free. Every other database error is rethrown and stays a 500.
  • The insert is an INSERT ... SELECT from the resource's row. The WHERE clause produces a row to insert only when the resource is active, the booking starts in the future, and it fits the opening hours of one local day. There's no read before the write to race with. For the hours check, AT TIME ZONE shifts each instant to the resource's wall clock, with whichever offset applies on that date, so a room's 09:00 opening is 09:00 local in July and in December alike.
  • The SELECT takes a lock on the resource's row (FOR NO KEY UPDATE). Bookings for the same room queue up behind each other; bookings for other rooms are unaffected. Correctness doesn't depend on this lock, the constraint is enough for that. The lock is there because of something the race test turned up: with two inserts in flight, each can end up waiting on the other's constraint check, and PostgreSQL breaks that cycle after its deadlock timeout (one second unless configured otherwise) by aborting one statement with 40P01, deadlock detected. Without the lock, a user got that as a 500 in 4 of 100 runs of the ten-user test. With it, the later booking simply waits until the earlier one commits, and then hits the constraint immediately. After that change, the test ran 100 times on one copy of the app and 60 times on another without a single deadlock. The lock lasts for one statement.
  • No row inserted means 404 or 422. refuseBooking() only runs on the failure path, and tells an unknown or inactive resource (404) from times that don't fit (422: the request is valid, the server just can't carry it out).

The controller is open to every signed-in user, and every query in it is scoped to the caller's own bookings:

// src/bookings/bookings.controller.ts
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import { createBookingSchema, type CreateBookingDto } from './bookings.schemas.js';
import { BookingsService } from './bookings.service.js';

const bookingId = { schema: z.uuid() };

// Any signed-in user books, and sees only their own bookings.
@Can.Anyone()
@Controller('bookings')
export class BookingsController {
  constructor(private readonly bookingsService: BookingsService) {}

  @Post()
  create(@CurrentUser('id') userId: string, @Body({ schema: createBookingSchema }) dto: CreateBookingDto) {
    return this.bookingsService.create(userId, dto);
  }

  @Get()
  findUpcoming(@CurrentUser('id') userId: string) {
    return this.bookingsService.findUpcoming(userId);
  }

  @Get(':id')
  findOne(@CurrentUser('id') userId: string, @Param('id', bookingId) id: string) {
    return this.bookingsService.findOne(userId, id);
  }
}
Enter fullscreen mode Exit fullscreen mode

The module wires the controller and the service together:

// src/bookings/bookings.module.ts
import { Module } from '@nestjs/common';
import { BookingsController } from './bookings.controller.js';
import { BookingsService } from './bookings.service.js';

@Module({
  controllers: [BookingsController],
  providers: [BookingsService],
})
export class BookingsModule {}
Enter fullscreen mode Exit fullscreen mode

List the free slots of a day

Users will want to see what's open before they book. A day's slots are the opening hours divided into pieces slotMinutes long, and a slot counts as free if no confirmed booking overlaps it. That's one query in PostgreSQL: generate_series() emits every slot of the day, and a NOT EXISTS with the constraint's own overlap test filters out the taken ones. It goes into ResourcesService, with a Slot type and two extra imports, sql and bookings:

// src/resources/resources.service.ts
import { and, asc, eq, sql } from 'drizzle-orm';
import { bookings, resources, type Resource } from '../database/schema.js';
// ...

export interface Slot {
  startsAt: Date;
  endsAt: Date;
}

@Injectable()
export class ResourcesService {
  // ...

  /** The free slots of one day, in the resource's time zone, that haven't started yet. */
  async availability(id: string, date: string): Promise<Slot[]> {
    const { timeZone, opensAt, closesAt, slotMinutes } = await this.findOne(id);
    const length = sql`make_interval(mins => ${slotMinutes})`;
    // The day's opening and closing times, as instants. AT TIME ZONE applies the
    // offset that is valid on that date, so a day with a DST change is right too.
    const opens = sql`(${date}::date + ${opensAt}::time) AT TIME ZONE ${timeZone}`;
    const closes = sql`(${date}::date + ${closesAt}::time) AT TIME ZONE ${timeZone}`;
    const slot = sql`slot`;

    return this.db
      .select({
        startsAt: sql`${slot}`.mapWith(bookings.startsAt),
        endsAt: sql`${slot} + ${length}`.mapWith(bookings.endsAt),
      })
      .from(sql`generate_series(${opens}, ${closes} - ${length}, ${length}) AS slot`)
      .where(
        and(
          sql`${slot} > now()`,
          // The same rule as the exclusion constraint: confirmed bookings, half-open ranges.
          sql`NOT EXISTS (
            SELECT 1 FROM ${bookings}
            WHERE ${bookings.resourceId} = ${id}
              AND ${bookings.status} = 'confirmed'
              AND tstzrange(${bookings.startsAt}, ${bookings.endsAt}) && tstzrange(${slot}, ${slot} + ${length})
          )`,
        ),
      )
      .orderBy(slot);
  }
}
Enter fullscreen mode Exit fullscreen mode

A few things about that query:

  • Dates are local to the resource. For Europe/Warsaw, 2026-12-01 at 09:00 comes out as 08:00 UTC, and a July date at the same time comes out as 07:00 UTC. A day when the clocks jump still gets slots from opening to closing.
  • mapWith(bookings.startsAt) tells Drizzle to treat the two computed columns like that timestamptz column, so each slot is returned as a pair of Date objects, consistent with the rest of the API.
  • The constraint's index pulls double duty. The NOT EXISTS matches on resource, status and the range expression, exactly what bookings_no_overlap indexes, so PostgreSQL can answer it from that index.
  • Listing a slot doesn't reserve it. Another user can book it in the meantime, and then this user's booking comes back as a 409. That's the constraint working as intended, and the client just fetches the slots again.

Like the other catalog reads, the free-slots route needs no sign-in. The controller gets Query in its @nestjs/common import, availabilityQuerySchema and AvailabilityQuery in its schema import, and one more handler:

// src/resources/resources.controller.ts
import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
// ...
import {
  availabilityQuerySchema,
  createResourceSchema,
  updateResourceSchema,
  type AvailabilityQuery,
  type CreateResourceDto,
  type UpdateResourceDto,
} from './resources.schemas.js';
// ...

  @Public()
  @ApiSecurity({})
  @Get(':id/availability')
  async availability(
    @Param('id', resourceId) id: string,
    @Query({ schema: availabilityQuerySchema }) { date }: AvailabilityQuery,
  ) {
    return { date, slots: await this.resourcesService.availability(id, date) };
  }
Enter fullscreen mode Exit fullscreen mode

Cancel a booking before the cutoff

The cancellation rule: until 24 hours before the start, a booking can be cancelled by the person who made it. As with every other write in this app, that's a single UPDATE with the rule in its WHERE clause. The row must belong to the caller, still be confirmed, and start later than 24 hours from now, where now is the database's clock, not the Node.js process's. Add the constant, the method and its error helper to BookingsService:

// src/bookings/bookings.service.ts
// ...

/** How long before its start a booking can still be cancelled. */
const CANCELLATION_CUTOFF = '24 hours';

@Injectable()
export class BookingsService {
  // ...

  /** The owner cancels a confirmed booking, up to the cutoff before it starts. */
  async cancel(userId: string, id: string): Promise<Booking> {
    // Conditional, and on the database's clock: of two cancellations, or one at
    // the moment of the cutoff, the WHERE clause decides.
    const [booking] = await this.db
      .update(bookings)
      .set({ status: 'cancelled', cancelledAt: sql`now()` })
      .where(
        and(
          this.owned(userId, id),
          eq(bookings.status, 'confirmed'),
          sql`${bookings.startsAt} > now() + ${CANCELLATION_CUTOFF}::interval`,
        ),
      )
      .returning();
    return booking ?? (await this.refuseCancel(userId, id));
  }

  // ...

  /** Why the cancellation changed nothing: 404 if the booking isn't theirs, 409 otherwise. */
  private async refuseCancel(userId: string, id: string): Promise<never> {
    const { status } = await this.findOne(userId, id);
    if (status === 'cancelled') {
      throw new ConflictException('Booking is already cancelled');
    }
    throw new ConflictException(`Bookings can't be cancelled less than ${CANCELLATION_CUTOFF} before they start`);
  }
}
Enter fullscreen mode Exit fullscreen mode

The version that loads the booking, checks its status and start time in JavaScript, and then saves it has a gap between the check and the write, the same shape of bug as the check-then-insert booking. Here the WHERE clause is the check, so there's no gap. And because the constraint only counts confirmed bookings, the moment the status turns cancelled, the slot is free for someone else.

Cancelling changes a booking that already exists, so the route answers 200 rather than the 201 a POST gets by default. It needs HttpCode in the import:

// src/bookings/bookings.controller.ts
import { Body, Controller, Get, HttpCode, Param, Post } from '@nestjs/common';
// ...

  @Post(':id/cancel')
  @HttpCode(200)
  cancel(@CurrentUser('id') userId: string, @Param('id', bookingId) id: string) {
    return this.bookingsService.cancel(userId, id);
  }
Enter fullscreen mode Exit fullscreen mode

Try it

Start the app in watch mode:

$ npm run start:dev
Enter fullscreen mode Exit fullscreen mode

What follows is a recorded session. Its dates were ahead of the recording date, so substitute future dates of your own, and tomorrow's date in the final example. Sign up a user, Ada, and a staff member, Sam, and promote Sam with the UPDATE above. Both tokens keep working after the promotion, since the role is read on every request. Tokens and response bodies are shortened here and below:

$ curl localhost:3000/auth/sign-up --json '{"email":"ada@example.com","password":"correct horse battery"}'
{"accessToken":"eyJhbGciOiJIUzI1NiIs...","refreshToken":"...","expiresIn":900}
$ ADA="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
$ SAM="Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
Enter fullscreen mode Exit fullscreen mode

Only staff can add a resource. Room A sits in Warsaw and takes bookings between 09:00 and 17:00 local time, an hour at a time. Ada's attempt is refused with a 403; Sam's creates it:

$ curl localhost:3000/resources -H "$ADA" --json '{"name":"Room A","timeZone":"Europe/Warsaw","opensAt":"09:00","closesAt":"17:00","slotMinutes":60}'
{"message":"Forbidden","statusCode":403}
$ curl localhost:3000/resources -H "$SAM" --json '{"name":"Room A","timeZone":"Europe/Warsaw","opensAt":"09:00","closesAt":"17:00","slotMinutes":60}'
{"id":"8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8","name":"Room A","timeZone":"Europe/Warsaw","opensAt":"09:00:00","closesAt":"17:00:00","slotMinutes":60,"active":true,"createdAt":"2026-11-19T22:06:06.275Z"}
Enter fullscreen mode Exit fullscreen mode

On December 1, Warsaw is on winter time, UTC+1, so the eight free slots start at 08:00 UTC and the last one ends at 16:00 UTC:

$ curl "localhost:3000/resources/8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8/availability?date=2026-12-01"
{"date":"2026-12-01","slots":[{"startsAt":"2026-12-01T08:00:00.000Z","endsAt":"2026-12-01T09:00:00.000Z"},{"startsAt":"2026-12-01T09:00:00.000Z","endsAt":"2026-12-01T10:00:00.000Z"},...,{"startsAt":"2026-12-01T15:00:00.000Z","endsAt":"2026-12-01T16:00:00.000Z"}]}
Enter fullscreen mode Exit fullscreen mode

Ada books 10:00 to 11:00 in Warsaw, written with its +01:00 offset, and gets the booking back with the same two moments expressed in UTC:

$ curl localhost:3000/bookings -H "$ADA" --json '{"resourceId":"8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8","startsAt":"2026-12-01T10:00:00+01:00","endsAt":"2026-12-01T11:00:00+01:00"}'
{"id":"f30a70ac-eec9-4f60-920d-2bd86f603e31","resourceId":"8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8","userId":"d0276247-b9ac-4830-a774-fdb5f452f03c","startsAt":"2026-12-01T09:00:00.000Z","endsAt":"2026-12-01T10:00:00.000Z","status":"confirmed","createdAt":"2026-11-19T22:06:46.343Z","cancelledAt":null}
Enter fullscreen mode Exit fullscreen mode

Sam tries to book half an hour into Ada's booking and gets a 409. The next hour, which starts exactly where Ada's ends, goes through. Leave the offset off and the request is a 400; start before opening time and it's a 422:

$ curl localhost:3000/bookings -H "$SAM" --json '{"resourceId":"8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8","startsAt":"2026-12-01T09:30:00Z","endsAt":"2026-12-01T10:30:00Z"}'
{"message":"The resource is already booked at that time","error":"Conflict","statusCode":409}
$ curl localhost:3000/bookings -H "$SAM" --json '{"resourceId":"8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8","startsAt":"2026-12-01T10:00:00Z","endsAt":"2026-12-01T11:00:00Z"}'
{"id":"db5a86fc-3015-4f22-8106-33b0f013dfce",...,"startsAt":"2026-12-01T10:00:00.000Z","endsAt":"2026-12-01T11:00:00.000Z","status":"confirmed",...}
$ curl localhost:3000/bookings -H "$SAM" --json '{"resourceId":"8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8","startsAt":"2026-12-01T12:00:00","endsAt":"2026-12-01T13:00:00"}'
{"message":["startsAt: Invalid ISO datetime","endsAt: Invalid ISO datetime"],"error":"Bad Request","statusCode":400}
$ curl localhost:3000/bookings -H "$SAM" --json '{"resourceId":"8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8","startsAt":"2026-12-01T07:00:00Z","endsAt":"2026-12-01T09:00:00Z"}'
{"message":"A booking must start in the future, within the opening hours of one day","error":"Unprocessable Entity","statusCode":422}
Enter fullscreen mode Exit fullscreen mode

Listing December 1 again, 09:00 and 10:00 UTC are no longer offered. On March 28, 2027, when Poland switches to summer time, the first slot of the same room starts at 07:00 UTC:

$ curl "localhost:3000/resources/8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8/availability?date=2026-12-01"
{"date":"2026-12-01","slots":[{"startsAt":"2026-12-01T08:00:00.000Z","endsAt":"2026-12-01T09:00:00.000Z"},{"startsAt":"2026-12-01T11:00:00.000Z","endsAt":"2026-12-01T12:00:00.000Z"},...]}
$ curl "localhost:3000/resources/8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8/availability?date=2027-03-28"
{"date":"2027-03-28","slots":[{"startsAt":"2027-03-28T07:00:00.000Z","endsAt":"2027-03-28T08:00:00.000Z"},...,{"startsAt":"2027-03-28T14:00:00.000Z","endsAt":"2027-03-28T15:00:00.000Z"}]}
Enter fullscreen mode Exit fullscreen mode

Now Ada cancels. When Sam tries to cancel her booking, Sam gets a 404, the same answer as for a booking that doesn't exist. Ada's own cancellation works once, and the second attempt is a 409. Her hour is free again immediately, and Sam books part of it:

$ curl -X POST localhost:3000/bookings/f30a70ac-eec9-4f60-920d-2bd86f603e31/cancel -H "$SAM"
{"message":"Booking not found","error":"Not Found","statusCode":404}
$ curl -X POST localhost:3000/bookings/f30a70ac-eec9-4f60-920d-2bd86f603e31/cancel -H "$ADA"
{"id":"f30a70ac-eec9-4f60-920d-2bd86f603e31",...,"status":"cancelled","createdAt":"2026-11-19T22:06:46.343Z","cancelledAt":"2026-11-19T22:07:12.645Z"}
$ curl -X POST localhost:3000/bookings/f30a70ac-eec9-4f60-920d-2bd86f603e31/cancel -H "$ADA"
{"message":"Booking is already cancelled","error":"Conflict","statusCode":409}
$ curl localhost:3000/bookings -H "$SAM" --json '{"resourceId":"8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8","startsAt":"2026-12-01T09:30:00Z","endsAt":"2026-12-01T10:00:00Z"}'
{"id":"32d1c620-05b3-4239-82b5-e0b4cbf45b99",...,"startsAt":"2026-12-01T09:30:00.000Z","endsAt":"2026-12-01T10:00:00.000Z","status":"confirmed",...}
Enter fullscreen mode Exit fullscreen mode

Finally, a booking for tomorrow morning is already inside the 24-hour cutoff when it's made, so it can't be cancelled:

$ curl localhost:3000/bookings -H "$ADA" --json '{"resourceId":"8bc932f4-1aa4-4ba1-a16d-0dca819ef5c8","startsAt":"2026-11-20T10:00:00+01:00","endsAt":"2026-11-20T11:00:00+01:00"}'
{"id":"dc96c803-b64d-4c17-acf2-385b4c860a9c",...,"startsAt":"2026-11-20T09:00:00.000Z","endsAt":"2026-11-20T10:00:00.000Z","status":"confirmed",...}
$ curl -X POST localhost:3000/bookings/dc96c803-b64d-4c17-acf2-385b4c860a9c/cancel -H "$ADA"
{"message":"Bookings can't be cancelled less than 24 hours before they start","error":"Conflict","statusCode":409}
Enter fullscreen mode Exit fullscreen mode

Test concurrent bookings against a real PostgreSQL

Everything that matters in this app is about concurrency, and that rules out the usual shortcut for database tests. An in-process database such as PGlite has a single connection, so requests never truly race on it. So the suite talks to an actual PostgreSQL server over a pool of connections, and uses app.inject() to fire requests concurrently. Schema setup is just the migrations, custom one and all:

// test/bookings.e2e-spec.ts
import { fileURLToPath } from 'node:url';
import { PasswordHasher } from '@nestjs/authentication';
import { getDrizzleToken } from '@nestjs/drizzle';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { eq, sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { AppModule } from '../src/app.module.js';
import { bookings, users } from '../src/database/schema.js';
import type { Role } from '../src/users/user.js';

// A real PostgreSQL with a pool, so concurrent bookings really race.
const url = process.env.TEST_DATABASE_URL;

// Three days from now, in UTC: in the future, and past the cancellation cutoff.
const day = new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
const at = (time: string) => `${day}T${time}:00Z`;

describe.skipIf(!url)('Booking API (e2e)', () => {
  const db = drizzle({ client: new Pool({ connectionString: url, max: 20 }) });
  let app: NestNodeApplication;

  beforeAll(async () => {
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
    await db.execute(sql`TRUNCATE users, resources, bookings, refresh_tokens CASCADE`);
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(db)
      // scrypt at the default cost takes 128 MiB and a few hundred ms per hash.
      .overrideProvider(PasswordHasher)
      .useValue(new PasswordHasher({ logN: 10 }))
      .compile();
    app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    await app.init();
  });

  afterAll(() => app.close()); // closes the pool too

  let clients = 0;

  /** Signs a user up, and returns the headers that authenticate as them. */
  async function signUp(email: string, role: Role = 'customer') {
    const res = await app.inject({
      method: 'POST',
      url: '/auth/sign-up',
      payload: { email, password: 'correct horse battery' },
      // Each user signs up from an address of their own, as they would in
      // production: sign-up is rate-limited per IP address.
      remoteAddress: `10.0.0.${++clients}`,
    });
    await db.update(users).set({ role }).where(eq(users.email, email));
    return { authorization: `Bearer ${res.json<{ accessToken: string }>().accessToken}` };
  }

  /** A room open 08:00 to 18:00 UTC, with one-hour slots. */
  async function createRoom() {
    const res = await app.inject({
      method: 'POST',
      url: '/resources',
      headers: await signUp(`staff-${crypto.randomUUID()}@example.com`, 'staff'),
      payload: { name: 'Room', timeZone: 'UTC', opensAt: '08:00', closesAt: '18:00', slotMinutes: 60 },
    });
    expect(res.statusCode).toBe(201);
    return res.json<{ id: string }>().id;
  }

  function book(headers: Record<string, string>, resourceId: string, startsAt: string, endsAt: string) {
    return app.inject({ method: 'POST', url: '/bookings', headers, payload: { resourceId, startsAt, endsAt } });
  }

  function cancel(headers: Record<string, string>, bookingId: string) {
    return app.inject({ method: 'POST', url: `/bookings/${bookingId}/cancel`, headers });
  }

  it('lets only staff create resources', async () => {
    const payload = { name: 'Room', timeZone: 'UTC', opensAt: '08:00', closesAt: '18:00', slotMinutes: 60 };
    const customer = await signUp('customer@example.com');
    expect((await app.inject({ method: 'POST', url: '/resources', payload })).statusCode).toBe(401);
    expect((await app.inject({ method: 'POST', url: '/resources', headers: customer, payload })).statusCode).toBe(403);
  });

  it('books a slot exactly once when ten users race for it', async () => {
    const roomId = await createRoom();
    const racers = await Promise.all(Array.from({ length: 10 }, (_, i) => signUp(`racer${i}@example.com`)));

    const results = await Promise.all(racers.map((headers) => book(headers, roomId, at('10:00'), at('11:00'))));

    expect(results.map((res) => res.statusCode).sort()).toEqual([201, ...Array(9).fill(409)]);
    const rows = await db.select().from(bookings).where(eq(bookings.resourceId, roomId));
    expect(rows).toHaveLength(1);
  });

  it('accepts back-to-back bookings, and refuses overlapping ones', async () => {
    const roomId = await createRoom();
    const headers = await signUp('back-to-back@example.com');

    expect((await book(headers, roomId, at('10:00'), at('11:00'))).statusCode).toBe(201);
    // Ends exactly when the next one starts: the ranges are half-open.
    expect((await book(headers, roomId, at('11:00'), at('12:00'))).statusCode).toBe(201);
    expect((await book(headers, roomId, at('09:00'), at('10:00'))).statusCode).toBe(201);
    // Any overlap, even one minute, is refused.
    expect((await book(headers, roomId, at('11:59'), at('13:00'))).statusCode).toBe(409);

    const availability = await app.inject({ method: 'GET', url: `/resources/${roomId}/availability?date=${day}` });
    const { slots } = availability.json<{ slots: { startsAt: string }[] }>();
    const starts = slots.map((slot) => slot.startsAt.slice(11, 16));
    expect(starts).toEqual(['08:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00']);
  });

  it('frees the slot when a booking is cancelled', async () => {
    const roomId = await createRoom();
    const ada = await signUp('ada@example.com');
    const bob = await signUp('bob@example.com');
    const booking = (await book(ada, roomId, at('14:00'), at('15:00'))).json<{ id: string }>();

    // Someone else's booking is a 404, as if it didn't exist.
    expect((await cancel(bob, booking.id)).statusCode).toBe(404);
    expect((await cancel(ada, booking.id)).json()).toMatchObject({ status: 'cancelled' });
    expect((await cancel(ada, booking.id)).statusCode).toBe(409);

    // The cancelled booking still overlaps, but the constraint only counts confirmed ones.
    expect((await book(bob, roomId, at('14:30'), at('15:30'))).statusCode).toBe(201);
  });

  it('refuses to cancel a booking that starts within the cutoff', async () => {
    const roomId = await createRoom();
    const headers = await signUp('late@example.com');
    const [{ id: userId }] = await db.select({ id: users.id }).from(users).where(eq(users.email, 'late@example.com'));
    // Inserted directly: it starts in an hour, whatever the room's opening hours.
    const [booking] = await db
      .insert(bookings)
      .values({
        resourceId: roomId,
        userId,
        startsAt: new Date(Date.now() + 60 * 60 * 1000),
        endsAt: new Date(Date.now() + 2 * 60 * 60 * 1000),
      })
      .returning();

    expect((await cancel(headers, booking.id)).statusCode).toBe(409);
    const [row] = await db.select().from(bookings).where(eq(bookings.id, booking.id));
    expect(row.status).toBe('confirmed');
  });
});
Enter fullscreen mode Exit fullscreen mode

What each test pins down:

  • "books a slot exactly once" is the one this whole post is about: ten users book the same hour at the same moment. Exactly one request gets a 201, the other nine get a 409, and a single row ends up in the table.
  • "back-to-back" makes a 10:00 to 11:00 booking, then the hours on either side of it, 11:00 to 12:00 and 09:00 to 10:00, which share an edge but no time, then one from 11:59 that overlaps by a minute and must fail. The availability afterwards lists exactly the untouched hours.
  • "frees the slot" is the test for the constraint's WHERE clause: after a cancellation, a booking that overlaps the cancelled one is accepted.
  • "within the cutoff" writes a booking that starts in one hour directly to the table (through the API, whether it fits the room's hours would depend on when the test runs), then confirms that the cancel is refused and the row is still confirmed.

The tests truncate tables, so give them a database of their own, then run them:

$ docker exec booking-db psql -U postgres -c "CREATE DATABASE booking_test"
$ TEST_DATABASE_URL=postgres://postgres:booking@localhost:5432/booking_test npm run test:e2e -- --no-file-parallelism

 Test Files  2 passed (2)
      Tests  10 passed (10)
Enter fullscreen mode Exit fullscreen mode

The second file is the JWT API's refresh-token store test. Since both files truncate tables in one shared database, --no-file-parallelism keeps them from running at the same time.

To watch the constraint do its work, remove it from the test database with ALTER TABLE bookings DROP CONSTRAINT bookings_no_overlap and rerun the suite. Every one of the ten racers gets a 201, and the one-minute overlap in the back-to-back test goes through as well. Note that the row lock is still in place in that run: it makes bookings take turns, but without the constraint, each one still inserts.

Production checklist

Everything on the JWT API's production checklist applies here too. On top of it, for bookings:

  • Treat the custom migration as a normal release step. drizzle-kit migrate applies it in sequence with the rest. It starts by creating btree_gist, and if your migration role lacks permission to create extensions, ask an administrator to create it once.
  • Find and fix existing overlaps first, if the table already has bookings. Adding the constraint fails when confirmed bookings already collide, and the error names the two rows.
  • Use UTC everywhere except the screen. timestamptz in the database, ISO 8601 with Z in responses, and local time only when the client displays it. Time zones are IANA names; a fixed offset like +01:00 is wrong for half of every year.
  • Translate this one constraint violation into a 409, and nothing else. Any other database error points at a bug, and leaving it a 500 keeps it reported as one.
  • Give production its own Observe key pair, and know what a 409 means there. I create the pair on the project's API Keys page and set it as OBSERVE_APP_KEY and OBSERVE_APP_SECRET in the platform's environment, because start:prod doesn't load .env. In NestJS Observe, the Errors view then lists every failed request. An exception your code throws on purpose, like this ConflictException, isn't counted as a new defect, and 4xx responses are left out of the error rate. So a popular slot that many users try to grab shows up as a run of 409s, without raising an alert. A 23P01 that slipped through unmapped, or a 40P01 deadlock, is a 500, and that does count.
  • Keep an eye on the lock when traffic peaks. Bookings for one popular room wait on its row, each for the duration of a single INSERT. Observe tracks average and p95 latency per route, so you'd see POST /bookings getting slower during a rush.

What's next

  • Hold a slot during payment, with a held status and an expires_at column. The catch is that the constraint's WHERE clause can't reference now(): an index predicate has to return the same result on every evaluation, so an expired hold still blocks its slot until something releases it. Do that release for the resource inside the booking's own statement or transaction, or periodically from a scheduled job.
  • Send a confirmation and a reminder for each booking, outside the request, with Mail and Queues.
  • Let staff see and cancel any booking of a resource, through a second policy.
  • See slow bookings and their SQL in production, request by request, with Observability.

Most of the code that matters in this post is SQL, and it would be the same SQL with any Node.js framework. What Nest adds is the part around it that you'd otherwise have to decide and wire yourself: validation from schemas that also type the handlers and describe the OpenAPI document, authentication on every route unless a route opts out, authorization that refuses routes that don't declare a rule, and a testing module that swaps in a pooled test database with one override.

What's left below is the sign-in side's code, for copying.

Appendix: the files from the JWT API

These are the JWT API's files as this app uses them, already adapted for the booking system. The reasoning behind them is in Build a REST API with JWT authentication; here they're just the code.

Configuration, entry point and tooling

The environment schema, which ConfigModule checks at startup:

// src/config.ts
import { z } from 'zod';

export const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().default(3000),
  DATABASE_URL: z.url(),
  // Signs the access tokens: at least 32 bytes.
  JWT_SECRET: z.string().min(32),
  // The browser origins allowed to call the API, comma-separated. None by default.
  CORS_ORIGINS: z
    .string()
    .default('')
    .transform((value) => value.split(',').map((origin) => origin.trim()).filter(Boolean))
    .pipe(z.array(z.url())),
});

export type Env = z.infer<typeof envSchema>;
Enter fullscreen mode Exit fullscreen mode

The entry point runs on the Node adapter, writes JSON logs in production with passwords and tokens masked, sets security headers and CORS, enables shutdown hooks, and serves the OpenAPI document at /docs, with the bearer token required document-wide:

// src/main.ts
import { ConsoleLogger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule, ObserveInstrument } from './app.module.js';
import type { Env } from './config.js';

const production = process.env.NODE_ENV === 'production';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
  instrument: ObserveInstrument,
  logger: new ConsoleLogger({
    // One JSON object per line in production; readable text in development.
    json: production,
    // Masks these properties wherever they appear in a logged object.
    redact: ['password', 'authorization', 'accessToken', 'refreshToken'],
  }),
});
app.useSecurityHeaders();
app.enableShutdownHooks();

const config = app.get<ConfigService<Env, true>>(ConfigService);
app.enableCors({ origin: config.get('CORS_ORIGINS', { infer: true }) });

const document = new DocumentBuilder()
  .setTitle('Booking API')
  .setVersion('1.0')
  .addBearerAuth()
  .addSecurityRequirements('bearer')
  .build();
SwaggerModule.setup('docs', app, () => SwaggerModule.createDocument(app, document));

await app.listen(config.get('PORT', { infer: true }));
Enter fullscreen mode Exit fullscreen mode

drizzle-kit reads the schema and writes migrations to drizzle/:

// drizzle.config.ts
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  dialect: 'postgresql',
  schema: './src/database/schema.ts',
  out: './drizzle',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});
Enter fullscreen mode Exit fullscreen mode

The Vitest configuration for the end-to-end tests sets the two required variables, so the config check passes; the tests replace the database connection themselves:

// vitest.config.e2e.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    root: './',
    include: ['test/**/*.e2e-spec.ts'],
    env: {
      DATABASE_URL: 'postgres://unused-in-tests',
      JWT_SECRET: 'test-only-jwt-secret-of-at-least-32-bytes',
    },
  },
});
Enter fullscreen mode Exit fullscreen mode

Users

The repository, with the role in its columns. Only User objects leave it; password hashes stay inside:

// src/users/users.repository.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { users } from '../database/schema.js';
import type { User } from './user.js';

const columns = { id: users.id, email: users.email, role: users.role, createdAt: users.createdAt };

/** Only `User` objects leave this class: password hashes stay inside. */
@Injectable()
export class UsersRepository {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  /** The new user, or `null` when the email is taken. */
  async create(email: string, passwordHash: string): Promise<User | null> {
    // One statement: two sign-ups with the same email can't both succeed.
    const [user] = await this.db
      .insert(users)
      .values({ email: normalize(email), passwordHash })
      .onConflictDoNothing({ target: users.email })
      .returning(columns);
    return user ?? null;
  }

  async findById(id: string): Promise<User | null> {
    const [user] = await this.db.select(columns).from(users).where(eq(users.id, id));
    return user ?? null;
  }

  /** For password sign-in only. */
  async findCredentials(email: string): Promise<{ user: User; passwordHash: string } | null> {
    const [row] = await this.db.select().from(users).where(eq(users.email, normalize(email)));
    if (!row) {
      return null;
    }
    const { passwordHash, ...user } = row;
    return { user, passwordHash };
  }

  async updatePasswordHash(id: string, passwordHash: string): Promise<void> {
    await this.db.update(users).set({ passwordHash }).where(eq(users.id, id));
  }
}

const normalize = (email: string) => email.trim().normalize('NFC').toLowerCase();
Enter fullscreen mode Exit fullscreen mode

The users module exports the repository for the auth module, and holds the MeController shown earlier:

// src/users/users.module.ts
import { Module } from '@nestjs/common';
import { MeController } from './me.controller.js';
import { UsersRepository } from './users.repository.js';

@Module({
  controllers: [MeController],
  providers: [UsersRepository],
  exports: [UsersRepository],
})
export class UsersModule {}
Enter fullscreen mode Exit fullscreen mode

Authentication

The account email that the throttler's per-account limit keys on, normalized the same way as the repository's emails:

// src/auth/account-email.ts
/** The address the request body names, trimmed, lowercased and in Unicode NFC, or `''`. */
export function accountEmail(req: { body?: { email?: unknown } }): string {
  const email = req.body?.email;
  return typeof email === 'string' ? email.trim().normalize('NFC').toLowerCase() : '';
}
Enter fullscreen mode Exit fullscreen mode

This declaration tells @nestjs/authentication which type the signed-in user has, so @CurrentUser() is typed:

// src/auth/auth-types.ts
import type { User } from '../users/user.js';

declare module '@nestjs/authentication' {
  interface AuthenticationTypes {
    user: User;
  }
}
Enter fullscreen mode Exit fullscreen mode

The request schemas for sign-up, sign-in and refresh tokens:

// src/auth/auth.schemas.ts
import { z } from 'zod';

export const signUpSchema = z.object({
  email: z.email(),
  password: z.string().min(12).max(128),
});
export type SignUpDto = z.infer<typeof signUpSchema>;

// No minimum here: a password set under an older rule still signs in.
export const signInSchema = z.object({
  email: z.email(),
  password: z.string().max(128),
});
export type SignInDto = z.infer<typeof signInSchema>;

export const refreshTokenSchema = z.object({
  refreshToken: z.string().min(1),
});
export type RefreshTokenDto = z.infer<typeof refreshTokenSchema>;
Enter fullscreen mode Exit fullscreen mode

CredentialsService registers users and checks passwords, at the same cost whether or not the email has an account:

// src/auth/credentials.service.ts
import { ConflictException, Injectable } from '@nestjs/common';
import { PasswordHasher } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class CredentialsService {
  constructor(
    private readonly usersRepository: UsersRepository,
    private readonly passwordHasher: PasswordHasher,
  ) {}

  async register(email: string, password: string): Promise<User> {
    const user = await this.usersRepository.create(email, await this.passwordHasher.hash(password));
    if (!user) {
      throw new ConflictException('Email already registered');
    }
    return user;
  }

  /** The user, or `null` when the email or the password is wrong. */
  async verify(email: string, password: string): Promise<User | null> {
    const found = await this.usersRepository.findCredentials(email);
    // With no account, verify() checks a dummy hash, so the response
    // time doesn't reveal which emails are registered.
    const valid = await this.passwordHasher.verify(password, found?.passwordHash);
    if (!valid || !found) {
      return null;
    }
    if (this.passwordHasher.needsRehash(found.passwordHash)) {
      await this.usersRepository.updatePasswordHash(found.user.id, await this.passwordHasher.hash(password));
    }
    return found.user;
  }
}
Enter fullscreen mode Exit fullscreen mode

The refresh-token store keeps the package's tokens in the refresh_tokens table, so every instance of the API shares them. Spending a token is one conditional UPDATE:

// src/auth/drizzle-refresh-token.store.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationStorage, type RefreshTokenRecord, type RefreshTokenStore } from '@nestjs/authentication';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, eq, isNull, lte } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { refreshTokens } from '../database/schema.js';

/** Refresh tokens in PostgreSQL, shared by every instance of the API. */
@Injectable()
export class DrizzleRefreshTokenStore implements RefreshTokenStore {
  constructor(
    @InjectDrizzle() private readonly db: NodePgDatabase,
    storage: AuthenticationStorage,
  ) {
    storage.registerSource({ refreshTokens: this });
  }

  async getRefreshToken(id: string): Promise<RefreshTokenRecord | undefined> {
    const [row] = await this.db.select().from(refreshTokens).where(eq(refreshTokens.id, id));
    if (!row) {
      return undefined;
    }
    const { revoked: _, usedAt, claims, ...token } = row;
    return { ...token, usedAt: usedAt ?? undefined, claims: claims ?? undefined };
  }

  async saveRefreshToken(record: RefreshTokenRecord): Promise<void> {
    await this.db.insert(refreshTokens).values(record);
    // Families past their absolute lifetime can go.
    await this.db.delete(refreshTokens).where(lte(refreshTokens.familyExpiresAt, record.createdAt));
  }

  async markRefreshTokenUsed(id: string, at: Date): Promise<boolean> {
    // Conditional: of two refreshes with the same token, one updates the row.
    const updated = await this.db
      .update(refreshTokens)
      .set({ usedAt: at })
      .where(and(eq(refreshTokens.id, id), isNull(refreshTokens.usedAt)))
      .returning({ id: refreshTokens.id });
    return updated.length === 1;
  }

  async revokeRefreshTokenFamily(familyId: string): Promise<void> {
    await this.db.update(refreshTokens).set({ revoked: true }).where(eq(refreshTokens.familyId, familyId));
  }

  async isRefreshTokenFamilyRevoked(familyId: string): Promise<boolean> {
    const revoked = await this.db
      .select({ id: refreshTokens.id })
      .from(refreshTokens)
      .where(and(eq(refreshTokens.familyId, familyId), eq(refreshTokens.revoked, true)))
      .limit(1);
    return revoked.length > 0;
  }

  async revokeUserRefreshTokens(userId: string): Promise<void> {
    await this.db.update(refreshTokens).set({ revoked: true }).where(eq(refreshTokens.userId, userId));
  }
}
Enter fullscreen mode Exit fullscreen mode

JwtAuth turns a verified access token into a user, by loading it on every request; that's what makes role changes apply at once:

// src/auth/jwt-auth.provider.ts
import { Injectable } from '@nestjs/common';
import { AuthenticationRegistry, JwtBearerProvider, type JwtClaims } from '@nestjs/authentication';
import type { User } from '../users/user.js';
import { UsersRepository } from '../users/users.repository.js';

@Injectable()
export class JwtAuth extends JwtBearerProvider<User> {
  constructor(
    private readonly usersRepository: UsersRepository,
    registry: AuthenticationRegistry,
  ) {
    // The key, issuer and audience come from the `accessToken` options.
    super({ realm: 'booking' });
    registry.registerProvider(this);
  }

  // Called once the signature, `exp`, `iss` and `aud` checked out.
  // Returning null (the user was deleted) rejects the token.
  validate({ sub }: JwtClaims) {
    return sub ? this.usersRepository.findById(sub) : null;
  }
}
Enter fullscreen mode Exit fullscreen mode

The auth controller signs users up and in, and refreshes and revokes tokens, with its own rate limits:

// src/auth/auth.controller.ts
import { Body, Controller, HttpCode, Post, UnauthorizedException } from '@nestjs/common';
import { Public, TokenService } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { SkipThrottle, Throttle, hours, minutes } from '@nestjs/throttler';
import {
  refreshTokenSchema,
  signInSchema,
  signUpSchema,
  type RefreshTokenDto,
  type SignInDto,
  type SignUpDto,
} from './auth.schemas.js';
import { CredentialsService } from './credentials.service.js';

@Public()
@ApiSecurity({})
@Controller('auth')
export class AuthController {
  constructor(
    private readonly credentialsService: CredentialsService,
    private readonly tokenService: TokenService,
  ) {}

  @SkipThrottle({ account: true })
  @Throttle({ default: { limit: 10, ttl: hours(1) } })
  @Post('sign-up')
  async signUp(@Body({ schema: signUpSchema }) body: SignUpDto) {
    const user = await this.credentialsService.register(body.email, body.password);
    return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
  }

  @Throttle({
    default: { limit: 30, ttl: minutes(15) },
    account: { limit: 5, ttl: minutes(15) },
  })
  @Post('token')
  @HttpCode(200)
  async token(@Body({ schema: signInSchema }) body: SignInDto) {
    const user = await this.credentialsService.verify(body.email, body.password);
    if (!user) {
      throw new UnauthorizedException('Invalid email or password');
    }
    return this.tokenService.issue(user.id, { method: 'password', claims: { amr: ['pwd'] } });
  }

  // An unknown, expired or reused refresh token gets a 401.
  @Post('token/refresh')
  @HttpCode(200)
  refresh(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
    return this.tokenService.refresh(body.refreshToken);
  }

  // Signs this device out. Unknown tokens get the same answer, as in RFC 7009.
  @Post('token/revoke')
  @HttpCode(204)
  async revoke(@Body({ schema: refreshTokenSchema }) body: RefreshTokenDto) {
    await this.tokenService.revoke(body.refreshToken);
  }
}
Enter fullscreen mode Exit fullscreen mode

The auth module ties them together:

// src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from '../users/users.module.js';
import { AuthController } from './auth.controller.js';
import { CredentialsService } from './credentials.service.js';
import { DrizzleRefreshTokenStore } from './drizzle-refresh-token.store.js';
import { JwtAuth } from './jwt-auth.provider.js';

@Module({
  imports: [UsersModule],
  controllers: [AuthController],
  providers: [JwtAuth, CredentialsService, DrizzleRefreshTokenStore],
})
export class AuthModule {}
Enter fullscreen mode Exit fullscreen mode

Health checks

The readiness check runs select 1 against the database, with a one-second timeout:

// src/health/database.health.ts
import { Injectable } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { HealthIndicatorService } from '@nestjs/terminus';
import { sql } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';

@Injectable()
export class DatabaseHealthIndicator {
  constructor(
    private readonly healthIndicatorService: HealthIndicatorService,
    @InjectDrizzle() private readonly db: NodePgDatabase,
  ) {}

  isHealthy(key: string) {
    return this.healthIndicatorService
      .check(key)
      .attempt(async () => {
        await this.db.execute(sql`select 1`);
      })
      .withTimeout('1s');
  }
}
Enter fullscreen mode Exit fullscreen mode

The health controller is public and skips rate limiting; live checks nothing but the process, ready checks the database:

// src/health/health.controller.ts
import { Controller, Get } from '@nestjs/common';
import { Public } from '@nestjs/authentication';
import { ApiSecurity } from '@nestjs/swagger';
import { HealthCheck, HealthCheckService } from '@nestjs/terminus';
import { SkipThrottle } from '@nestjs/throttler';
import { DatabaseHealthIndicator } from './database.health.js';

@Public()
@ApiSecurity({})
@SkipThrottle()
@Controller('health')
export class HealthController {
  constructor(
    private readonly health: HealthCheckService,
    private readonly database: DatabaseHealthIndicator,
  ) {}

  @Get('live')
  @HealthCheck()
  live() {
    return this.health.check([]);
  }

  @Get('ready')
  @HealthCheck()
  ready() {
    return this.health.check([() => this.database.isHealthy('database')]);
  }
}
Enter fullscreen mode Exit fullscreen mode

And its module:

// src/health/health.module.ts
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { DatabaseHealthIndicator } from './database.health.js';
import { HealthController } from './health.controller.js';

@Module({
  imports: [TerminusModule],
  controllers: [HealthController],
  providers: [DatabaseHealthIndicator],
})
export class HealthModule {}
Enter fullscreen mode Exit fullscreen mode

The refresh-token store test

The second test file runs the contract suite that @nestjs/authentication ships against the store, on a real pool, with concurrent calls:

// test/refresh-token.store.e2e-spec.ts
import { fileURLToPath } from 'node:url';
import { AuthenticationStorage } from '@nestjs/authentication';
import { authenticationStoreContract } from '@nestjs/authentication/testing';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import { Pool } from 'pg';
import { DrizzleRefreshTokenStore } from '../src/auth/drizzle-refresh-token.store.js';

// A real PostgreSQL with a pool, where parallel calls really race.
const url = process.env.TEST_DATABASE_URL;

describe.skipIf(!url)('DrizzleRefreshTokenStore', () => {
  const pool = new Pool({ connectionString: url });
  const db = drizzle({ client: pool });

  beforeAll(async () => {
    await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
  });
  afterAll(() => pool.end());

  /** The store on an empty table, registered nowhere: the suite builds its own registry. */
  async function emptyStore() {
    await pool.query('TRUNCATE refresh_tokens');
    return { refreshTokens: new DrizzleRefreshTokenStore(db, new AuthenticationStorage()) };
  }

  for (const c of authenticationStoreContract(emptyStore, { contracts: ['refreshTokens'], concurrent: true })) {
    it(c.name, c.run);
  }
});
Enter fullscreen mode Exit fullscreen mode

That's the whole application. The docs version of this article, kept up to date, is Build a booking system in Node.js without double bookings.

Top comments (2)

Collapse
 
prisminfoways profile image
Prism Infoways Private Limited •

Really solid walkthrough, especially the race test showing the check-then-insert version failing five runs out of five. That's the part that convinces people to move the rule into the database.

One gotcha I've hit when extending this pattern: if you need buffer time between bookings (say 15 minutes to clean a room), the obvious version EXCLUDE USING gist (resource_id WITH =, tstzrange(starts_at, ends_at + interval '15 minutes') WITH &&) is rejected, because timestamptz + interval is only STABLE, not IMMUTABLE (day-sized intervals depend on the session's TimeZone). A generated column hits the same wall. What worked for us was storing the buffered end as its own column, set by the application (or a trigger) when the booking is written, and putting that column in the constraint instead. The free-slots query then has to use the same column, otherwise it happily offers slots the constraint will reject.

Collapse
 
maxbuildsdev profile image
Max Kaya •

Overlap isn't the only thing a slot needs, though. Nothing here forces starts_at onto the grid: a 10:07–10:37 booking passes the exclusion constraint, and then vanishes from the availability list, because generate_series only emits points computed from opensAt. The row occupies real time, is invisible as taken, and anyone who books that window off the grid gets a 409 from a slot the API never offered. A check constraint on the offset from opensAt (mod slot_minutes = 0) closes it, and it's cheaper than debugging it from a support ticket.The 409 is also less immediate than the test suggests. An EXCLUDE conflict waits on the competing transaction before it can decide: if the booking row is inserted before a slow payment step and committed after, the second request sits blocked inside Postgres rather than failing — your ten-user test still ends with exactly one winner, but under real traffic you collect idle-in-transaction sessions and a p99 that has nothing to do with the database being slow. Commit the row first and confirm payment out of band, or set a local lock_timeout and turn 55P03 into a 503 the client retries. And when you map the error, note that Drizzle wraps driver errors, so the 23P01 code is on err.cause.code, not err.code.Does the booking commit before or after the payment call in your version?