A customer clicks Book. The connection drops. They click again. Encore must save one booking, not two. Part 4 established who the customer is; now turn that authenticated request into a booking that survives retries.

The longer implementations below are pseudocode, kept in their original languages so the file boundaries and function shapes stay familiar. They are not runnable code. Give these sketches, Part 3’s interfaces and Part 4’s authentication flow to AI and ask it to generate the complete implementations, imports, database migrations and focused tests. Review the generated code against the rules in each section before running it.

Handle booking requests

backend/src/bookings/routes.ts is the boundary between an HTTP request and the booking service. TypeScript types describe expected values during development; Fastify’s JSON Schema validates the JSON and headers that actually arrive.

Booking request flow: frontend sends a booking and retry key, the API validates input and checks the session and CSRF token, PostgreSQL reserves and saves atomically, then the API confirms the booking

Define bookingSchema to accept only eventId and quantity in the body. Require an event ID of 1 to 100 characters and an integer quantity from 1 to 10. Require an Idempotency-Key header of 16 to 128 characters so retries can refer to the same booking intent. Disable automatic type coercion and extra-field removal so invalid requests receive a 400 instead of being silently changed.

The schema checks request shape, not identity, ownership or available tickets. The route checks the session and CSRF token; the service and database enforce the booking rules. Ask AI to expand this TypeScript sketch using those boundaries.

/** Pseudocode: expose booking use cases with validation and access checks. */
export function bookingRoutes(app: FastifyInstance, auth: Auth, bookings: Bookings) {
  // Create or replay one booking for the authenticated customer.
  app.post('/v1/bookings', { schema: bookingSchema }, async (req, reply) => {
    // Require a session, verify CSRF and call bookings.create with the retry key.
    // Reply 201 with the booking and Location only after persistence succeeds.
  });
  // Return only a booking owned by the current customer.
  app.get<{ Params: { id: string } }>('/v1/bookings/:id', async (req) => {
    // Require a session; call bookings.find; return 404 if absent or not owned.
  });
}

frontend/src/api/bookings.ts sends POST JSON with credentials: 'include', Content-Type: application/json, X-CSRF-Token from readSession() and an Idempotency-Key made with crypto.randomUUID(). Generate the key once per booking intent and reuse it after a timeout. Treat a non-2xx response as failure, not a confirmed booking.

Use node-postgres for the database

node-postgres, installed as pg, is the PostgreSQL client library for Node.js. It sends SQL to the database, reuses connections through a pool and lets several writes succeed or fail together in a transaction. Encore uses it because the critical operation is small and explicit: reserve tickets and save the booking as one unit.

Pass customer values separately from SQL using $1, $2 placeholders. Parameterized queries keep user input out of the SQL syntax; installing pg alone does not prevent unsafe queries.

The database schema has two jobs. events records remaining inventory and prevents negative stock. bookings records the customer, event, quantity and retry key; its foreign key requires a real event, and UNIQUE (owner_id, idempotency_key) prevents duplicate booking intents per customer. All booking fields are required.

Ask AI to turn this SQL pseudocode into a versioned migration. Keep the 100-ticket seed separate as local test data, not production setup.

-- Pseudocode: replace the comments with columns and constraints.
CREATE TABLE events (
  -- id: text primary key; remaining: required integer, never negative
);
CREATE TABLE bookings (
  -- id: text primary key; owner_id: required text; event_id: references events
  -- quantity: integer from 1 to 10; idempotency_key: text; all fields required
  -- UNIQUE (owner_id, idempotency_key)
);
-- Local seed only: insert launch-night with 100 available tickets.

Implement BookingStore in backend/src/bookings/postgres.ts. Every statement in a transaction must use the same checked-out pg client, not separate pool.query() calls.

Lock the customer/key pair before looking for an earlier booking. Return that booking when the payload matches; reject a changed payload with idempotency_conflict. Otherwise lock the event row, reject event_not_found or sold_out, decrement inventory and insert the booking. Commit before returning success. Roll back failures, rethrow the error and always release the client. These locks prevent concurrent requests from duplicating a booking or overselling an event.

/** Pseudocode: adapt PostgreSQL to the BookingStore contract. */
export function createBookingStore(pool: Pool): BookingStore {
  return {
    async persist(input, ownerId, key) {
      // BEGIN; lock customer/key; replay or reject; lock event; reserve and insert.
      // COMMIT then return; on failure ROLLBACK and rethrow; always release client.
    },
    async findOwned(id, ownerId) {
      // Parameterized SELECT by both IDs; return null when absent.
    },
  };
}

Do not delete the stored idempotency key while clients can retry. If the connection drops during commit, the outcome is unknown; retry the same key rather than reporting success or starting a new booking.

Connect the implementations in app.ts

The pieces do not connect themselves. A booking route needs authentication and a booking service; that service needs a database store. backend/src/app.ts creates those implementations once and passes each one to the code that needs it. This is where Part 3’s interfaces become a working application.

Keep this assembly in buildApp() without starting a network listener. Local tests can then send requests directly through Fastify’s app.inject(), using the same wiring as the running server. Configure CORS for the exact frontend origin with credentials enabled so the browser can send Encore’s session cookie.

/** Pseudocode: connect the modules without starting the server. */
export async function buildApp(config: AuthConfig) {
  // Create Fastify with strict schema validation, safe logging and HTTP errors.
  // Register credentialed CORS for config.frontendOrigin and map booking errors.
  const auth = await registerAuth(app, config);
  // Create one pg Pool from database settings; report pool errors.
  // Close the pool in app.onClose so shutdown releases connections.
  bookingRoutes(app, auth, createBookings(createBookingStore(pool)));
  // GET /health: run SELECT 1; report ready only when PostgreSQL responds.
  return app;
}

Map invalid input to 400, missing authentication to 401, CSRF failures to 403, missing events or inaccessible bookings to 404, and sold-out or conflicting retries to 409. Unexpected failures return 500 with a request ID. Log failures without cookies, authorization codes, tokens or secrets; do not expose raw exception messages.

backend/src/server.ts starts the application assembled by buildApp(). Ask AI to generate this small entry point with these steps:

  • Check required settings before startup so a missing login secret or database password causes a clear error, not a broken customer request later.
  • Validate the frontend origin and Google callback URL so redirects and credentialed requests use the intended addresses. Pass the checked login settings to buildApp() as AuthConfig.
  • Require SESSION_KEY_HEX to contain exactly 64 hexadecimal characters and decode it with Buffer.from(value, 'hex'). This produces the 32-byte encryption key for session cookies. Keep the same private key across restarts so existing sessions remain readable.
  • Listen on 0.0.0.0 so requests can reach the server inside its container. Validate PORT as an integer from 1 to 65535; use 3000 when it is not set.
  • Handle SIGTERM by calling app.close(). This lets active requests finish and closes the database pool instead of cutting connections off abruptly.

Run and test locally

Use the frontend/backend layout from Part 3. Vite, the frontend development server and build tool introduced there, serves React at http://localhost:5173. Docker Compose runs the API and PostgreSQL together on your machine; it is not the production deployment.

Create an uncommitted backend/.env with the Google settings from Part 4, GOOGLE_REDIRECT_URI=http://localhost:3000/auth/google/callback, FRONTEND_ORIGIN=http://localhost:5173, SESSION_KEY_HEX and PGPASSWORD. Generate the session key once with node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))" and keep it private.

Ask AI to expand this root compose.yaml pseudocode into a complete local configuration. Use the Dockerfile in the next section for the API image, but pass development settings here so local HTTP cookies work.

services:
  api:
    build: ./backend
    # Bind 127.0.0.1:3000; load backend/.env; set NODE_ENV=development.
    # Set PORT=3000, PGHOST=db, PGPORT=5432, PGUSER=encore, PGDATABASE=encore.
    # Wait for healthy db; probe /health until the API is ready.
  db:
    image: postgres:17
    # Set POSTGRES_USER/DB=encore and POSTGRES_PASSWORD from PGPASSWORD.
    # Mount pgdata; check pg_isready; do not publish a database host port.
volumes:
  pgdata: {}

The named volume keeps bookings across container restarts. pg connects using the PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE settings. Compose supplies db as the database hostname; the browser still calls the API at http://localhost:3000.

Run these commands only after generating the implementations, migration, Compose file and Dockerfile. Apply the generated migration and local seed at the psql prompt, then exit with \q before starting the API.

docker compose --env-file backend/.env up -d --wait db
docker compose --env-file backend/.env exec db psql -U encore -d encore
docker compose --env-file backend/.env up --build -d --wait api
curl --fail http://localhost:3000/health
npm --prefix frontend ci
npm --prefix frontend run dev -- --host localhost --port 5173 --strictPort

Test the behavior that matters before treating a booking as reliable:

  • Sign in, create a booking and read it back. Anonymous requests must return 401; missing CSRF tokens must return 403; another customer’s booking must return 404.
  • Retry the same request with the same key, including after a simulated timeout. It must return the same booking without reducing inventory again. A changed payload with that key must return 409.
  • Send competing one-ticket requests against 100 tickets. At most 100 bookings may succeed, remaining inventory must never be negative, and failed transactions must leave no partial booking.

Use real PostgreSQL for the transaction and concurrency checks; a mocked store cannot prove the locks work. Do not run docker compose down -v unless you intend to delete the local database.

Build and package for production

Local development runs Vite and a disposable database setup. Production packaging produces two artifacts: static frontend files and a backend container image. It does not deploy them or include the local database.

Build React with Vite into frontend/dist; these files can be served by a static host without a frontend Node container.

npm --prefix frontend ci
npm --prefix frontend run build

Compile the backend’s TypeScript into backend/dist. Set "type": "module" in backend/package.json, keep .js suffixes in backend imports and add these entries under "scripts" so Node can run the compiled server.

{
  "build": "tsc --target ES2022 --module NodeNext --moduleResolution NodeNext --strict --esModuleInterop --outDir dist src/server.ts",
  "start": "node dist/server.js"
}

Expand this backend/Dockerfile pseudocode with AI. The build stage installs the versions recorded in package-lock.json and compiles TypeScript. The runtime stage copies only package metadata, production dependencies and compiled output, then runs as an unprivileged user. Commit the generated lockfiles so builds use the same dependency versions.

FROM node:24-bookworm-slim AS build
WORKDIR /app
# Copy manifests; npm ci; copy source; npm run build; npm prune --omit=dev.
FROM node:24-bookworm-slim AS runtime
ENV NODE_ENV=production
WORKDIR /app
# Copy manifests, node_modules and dist from build, owned by node:node.
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]

Put this in backend/.dockerignore so local secrets, installed modules and old builds cannot enter the build context.

.env*
node_modules
dist
.git

Build the completed Dockerfile from the repository root:

docker build -t encore-api:local ./backend

Supply production settings when the container starts, never while building the image. Set NODE_ENV=production, use same-site HTTPS frontend/API origins for secure session cookies, and require verified TLS for hosted database connections. Keep migrations as a separate release step; never seed production with local test data.

Encore has a local booking flow and a container recipe. The next step is taking that flow to the cloud.