Skip to main content
Case Study · Crown Wheels

Engineering a high-integrity luxury mobility & fleet operating platform.

Crown Wheels unites two distinct business scales: a dedicated, owned luxury fleet for chauffeured hire alongside an open, ongoing sales inventory. This is the engineering record of how WEBMUSE engineered database-enforced concurrency, offline emergency telemetry, zero-trust driver links, and 22 lint-enforced domain boundaries.

PostgreSQL EXCLUDE constraintNext.js 15 after() SOSRepository PatternLayered IdempotencyZero-Trust Driver TokensPure JS PDF Receipts
01 — Problem

When luxury assets and human safety meet real-world networks, application guards are not enough.

Operating a chauffeured luxury mobility service in Nigeria is fundamentally different from a standard e-commerce store. Vehicles command premium hire rates, itineraries span multiple days across intercity corridors, and emergencies demand immediate operational clarity.

Concurrency

High-demand luxury vehicles (e.g. Mercedes-Benz G-Wagons, Maybachs, Range Rovers) face simultaneous booking attempts during peak executive calendars. Traditional application-level 'check-then-create' logic creates a race window where two users book the same vehicle for overlapping dates.

Safety Criticality

In transit, when a driver or passenger triggers an SOS, network connections can be degraded. If emergency dispatch waits for third-party email APIs inline or relies on a scheduled cron job, serverless timeouts and dropped packets can delay life-critical intervention.

Financial Trust

Handling multi-million Naira transactions over unstable mobile connections leads to double-clicks and repeated webhooks. The system must guarantee real database idempotency and strict decimal precision with zero floating-point rounding drift.

Driver Usability

Drivers in the field need instant access to trip schedules and communications without password friction, yet sharing manifest URLs across unauthorized devices creates security vulnerabilities.

02 — Thesis

Make correctness structural, not procedural.

Procedural code can always be bypassed by concurrent database connections, unhandled exceptions, or serverless lifecycle freezes. WEBMUSE built Crown Wheels around a 25-pillar engineering fortress where invariants are pushed to the lowest possible layer: the database engine, durable transaction outboxes, and strict architectural lint rules.

Database-Enforced Invariants

PostgreSQL EXCLUDE constraint with GiST index and tsrange guarantees zero overlapping vehicle reservations under any concurrency load.

Sub-150ms SOS Telemetry

Emergency SOS mutations write durable database events immediately and hand off external notification dispatch to Next.js 15 after().

Zero-Trust Driver Token Links

Passwordless opaque cryptographic tokens with lightweight first-use device binding alert operators without locking out emergency SOS.

Lint-Enforced Layering

Architecture boundaries strictly enforced by ESLint: controllers validate and route, services orchestrate, and only repositories import Prisma.

03 — Architecture

The Fortress Architecture: 22 isolated domains, thin controllers, and atomic transactions.

Every request follows a unidirectional dependency flow. Route handlers strictly parse HTTP inputs, validate schemas via Zod, and delegate to a single domain service. Services depend on injected repository interfaces, keeping business rules 100% testable in memory.

  HTTP Client (Mobile / PWA / Web)
          │
          ▼
  Thin Route Handler (app/api/v1/**)
  ├─ Zod Schema Validation
  └─ Idempotency-Key Header Lookup (Cache check)
          │
          ▼
  Fat Domain Service (src/domains/*/service/)
  ├─ Business Rules & Pricing Engine (Decimal strings)
  └─ Injected Repository Contract (Zero direct DB imports)
          │
          ▼
  Repository Layer (src/domains/*/repository/)
  ├─ prisma.$transaction([
  │    Booking status update,
  │    CalendarBlock reservation,
  │    Trip record initialization,
  │    AuditLogEntry write
  │  ])
          │
          ▼
  PostgreSQL Engine (Storage Layer)
  ├─ EXCLUDE USING gist (vehicle_id WITH =, daterange WITH &&)
  ├─ Unique Compound Indexes: (user_id, idempotency_key)
  └─ Constraint Violation 23P01 ──> 409 BOOKING_DATES_UNAVAILABLE
          │
          ▼
  Background Execution: Next.js after()
  └─ NotificationDispatcher ──> Resend Email & Fleet Security Outbox
LayerTechnologyWhy it's there
Web & PWANext.js 15 App Router · React 19 · Tailwind CSSServerless web application with mobile-optimized luxury showcases, vehicle catalog, and offline-capable PWA manifest
ArchitectureThin Controllers · Fat Services · Repository Pattern22 domain bounded contexts with strict dependency inversion — route handlers never touch Prisma directly
DatastorePostgreSQL 16 · Prisma ORM · GiST ExtensionRelational persistence across 36 models, audited state mutations, and compound unique indexes
Concurrency GuardPostgres EXCLUDE Constraint (GiST Index)Hardware-enforced double-booking exclusion on overlapping date ranges — eliminating check-then-act race conditions
SettlementPaystack (Webhook HMAC-SHA512 + Poller)Transactional booking confirmation, automatic Trip creation, audit outbox logging, and idempotent webhook handling
Emergency TelemetryNext.js 15 after() · Non-blocking Event OutboxDurable database write committed in <150ms with asynchronous background notification dispatch on serverless
Document Enginepdf-lib (Pure JavaScript)Zero headless-Chrome/Puppeteer serverless dependency; generates branded luxury booking receipts in ~40ms
Boundaries & QAeslint-plugin-boundaries · Vitest FakesLint-enforced architectural layers and 31 unit test suites executed against in-memory repository fakes without live DB
04 — Deep Dive

Eliminating double-booking races at the database hardware layer.

In car hire software, double-booking prevention is often built as an application-level query: find overlapping reservations; if none exist, create the booking. Under concurrent traffic, this check-then-act pattern creates a race window that guarantees double bookings.

The Application Check Fallacy

Check-Then-Act Race Condition

A typical application queries 'SELECT * FROM bookings WHERE vehicleId = X AND dates overlap'. Under two concurrent requests arriving milliseconds apart, both read an empty result, both pass validation, and both write confirmed bookings. The result is a catastrophic double-booking for a multi-million Naira private hire.

The Structural Fix

Postgres EXCLUDE USING gist

Crown Wheels pushes calendar block exclusion directly to PostgreSQL: 'EXCLUDE USING gist (vehicle_id WITH =, daterange(start_date, end_date, '[]') WITH &&)'. The database engine serializes the index check atomically during transaction commit. Competing writes are rejected at the storage layer.

The Controller Contract

RFC-7807 409 Conflict Surface

When concurrent booking attempts collide, the repository catches Postgres error code 23P01 (exclusion_violation) and cleanly transforms it to a 409 BOOKING_DATES_UNAVAILABLE error response. The user sees a clear, immediate availability notice without orphaned state.

PostgreSQL Constraint Definition
ALTER TABLE "CalendarBlock"
ADD CONSTRAINT "no_overlapping_vehicle_blocks"
EXCLUDE USING gist (
  vehicle_id WITH =,
  daterange(start_date, end_date, '[]') WITH &&
);

Because this constraint lives in Postgres rather than TypeScript, concurrent booking transactions are evaluated by Postgres index serialization locks. The application never needs an error-prone distributed lock for date ranges.

05 — Deep Dive

Sub-150ms Emergency SOS: Non-blocking telemetry on serverless runtimes.

When an executive passenger or fleet driver taps SOS, the system cannot afford 3–5 seconds of HTTP connection stalling while calling downstream notification APIs. Worse, in serverless environments (e.g. Vercel), a bare fire-and-forget Promise (void dispatch()) is routinely killed mid-flight the moment the function response finishes.

01 · Passenger or Driver

Trigger SOS Button

Client dispatches payload with coordinates, battery level, trip token, and offline timestamp.

02 · PostgreSQL Transaction

Durable Write (<150ms)

SosEvent row commits immediately to database. HTTP 200/201 response returns to device instantly without blocking.

03 · Next.js after()

Asynchronous Dispatch

Serverless execution schedules NotificationDispatcher without freezing lambda lifecycle. Resend email alerts fire to fleet security.

04 · Trip State

Pre-Created Trip Anchor

Trips are created at payment confirmation — not deferred to hire start date — ensuring emergency SOS anchors exist immediately.

A key architectural decision was made in Sprint 6: A Trip record is generated immediately upon booking payment confirmation, rather than deferred to a scheduled job at hire start date. Because SOS attaches directly to a Trip, a passenger in transit is never blocked by an unrun background cron.

06 — Deep Dive

Financial precision: Zero-float contracts and real DB idempotency.

High-value Nigerian transactions cannot tolerate floating-point math bugs. A calculation error of ₦0.01 accumulates over invoices, and duplicate webhook delivery can double-credit bookings.

Decimal Strings Only

Money across all API contracts is serialized as a strict decimal string (e.g. '450000.00'), never a JavaScript IEEE-754 float.

DB Idempotency Index

A unique compound index on (userId, idempotencyKey) halts duplicate checkout submissions before any mutation occurs.

Dual-Path Settlement

Paystack webhook payloads are verified via HMAC-SHA512 signatures, backed by direct server-to-server transaction verification.

07 — Deep Dive

Zero-trust driver private links with first-use device binding.

Drivers operate on personal mobile hardware and require instant access to daily trip manifests, passenger communications, and status updates. Traditional password authentication creates high support friction and lost-credential delays.

Cryptographic Tokens with First-Use Fingerprint Binding

Drivers receive high-entropy opaque private URLs. On first launch, the driver client computes a browser device fingerprint and persists Driver.boundDeviceHash in the database.

The Safety Trade-off: Non-Blocking Alerting

If a driver accesses the link from a different device, the system raises an immediate alert to the fleet operations console rather than hard-blocking access. Because this token also gates the Driver SOS emergency trigger, locking the interface during an unplanned phone switch would be an unacceptable life-safety failure.

08 — Principles & ADRs

Architectural Decision Records: What we chose not to build.

High-integrity software is defined as much by what is excluded as what is included. Crown Wheels adheres to strict Architectural Decision Records (ADRs) documented in the project blueprint.

ADR-007 · No Automated WhatsApp Business API

Automated WhatsApp bots add monthly Meta per-conversation fees, rate-limit drops during critical updates, and maintenance overhead. Crown Wheels uses pure manual wa.me links with pre-filled context, letting clients chat directly with the owner while automated notifications remain strictly on verified transactional email.

ADR-012 · pdf-lib Over Puppeteer / Headless Chrome

Deploying Puppeteer or Chromium binaries to Vercel Serverless balloons function cold starts by 4–8 seconds and risks OOM crashes. pdf-lib is 100% pure JavaScript with zero native dependencies, generating pixel-perfect luxury hire invoices in 40ms.

ADR-015 · Fail-Open Geographic Coverage Zone Guard

If the CoverageZone geographic database table is empty or unseeded in a new deployment, bookings are permitted rather than globally rejected. An unconfigured operational zone table must never brick customer checkouts before the fleet manager sets boundaries.

ADR-021 · Non-Blocking Device Fingerprint Security

Drivers access trip manifests via secure cryptographic private tokens. When a device fingerprint mismatch occurs (Driver.boundDeviceHash), the system alerts fleet operators rather than locking the link. A locked token during an on-road incident would strip the driver of their emergency SOS trigger.

09 — By the numbers
92
API Route Handlers
22
Bounded Domain Modules
36
Prisma Database Models
0 ms
Double-booking race window
<150 ms
SOS event durability
0
Float rounding errors
31
In-memory test suites
~40 ms
Pure JS PDF receipt time
Building mission-critical fleet or transactional platforms? Let's talk.