Core distributed seats reservation web application [seats-reservation-postgres] built by GitHub Acti
1.9K
| Demo Version(s) | Demo Link(s) |
|---|---|
| GCP SQLite | https://seats-reservation-sqlite-2omkqplgya-uc.a.run.app (Last updated: 12/07/2026 15:40) |
| GCP Postgres | https://seats-reservation-postgres-2omkqplgya-uc.a.run.app (Last updated: 12/07/2026 15:40) |
| GKE SQLite | http://35.226.149.88:80 (Last updated: 06/07/2026 09:05) |
| GKE Postgres | http://136.114.146.251:80 (Last updated: 06/07/2026 09:05) |
Captured Prometheus Dashboard: 
Prometheus Dashboard: https://shortisthmus2724.grafana.net/public-dashboards/2b25c4d279144bcd82aec3f6d3328f80
(Last updated: 01/07/2026 13:38)
| GitHubCI/CD Workflows | Latest Running Status(es) |
|---|---|
| 🚢 Seats Reservation Platform CI/CD Pipeline |
The platform implements a highly resilient, hybrid identity management architecture controlled via a Dynamic Feature Toggle (AUTH_PROVIDER). This architecture supports runtime switching between two enterprise-grade authentication modes:
firebase): Offloaded authentication utilizing the Firebase Session Cookie Pattern.custom): An in-house, dual-token infrastructure featuring cryptographic isolation and token rotation.To eliminate the security vulnerabilities of standard client-side SDK implementations—where ID tokens stored in LocalStorage are exposed to Cross-Site Scripting (XSS) attacks—this platform strictly enforces the Server-Side Session Cookie Pattern.
IdToken and transmits it to the Next.js backend. The firebase-admin SDK validates the token and exchanges it for a secure, HTTP-Only Session Cookie with a 14-day validity window.onAuthStateChanged hooks. This ensures instant hydration of the user's SELECTED seat states and active countdown timers upon browser refreshes.The client-side apiKey utilized within the Firebase Client configuration differs fundamentally from conventional API keys, which are typically used to restrict backend resources. Instead, it functions purely as a public Project Identifier that enables the frontend application to route requests to the designated Google infrastructure.
Data confidentiality and operational integrity (including read/write loops and state mutations within the seat reservation matrix) are strictly enforced via standard defensive layers:
firebase-admin via secure, HTTP-Only session cookies.Consequently, exposing the apiKey within the client-side bundle complies with Google’s architectural specifications and introduces zero vulnerability to the core security posture of the platform.
The platform integrates Firebase Analytics to capture user behavioral metrics and conversion funnels (such as seat selections and checkout completions) without introducing render-blocking delays to the UI.
To prevent build-time failures and server runtime crashes during Next.js Pre-rendering (SSR), the application implements a strict Isomorphic Safe Initialization Pattern:
typeof window !== "undefined" conditional block, insulating the Node.js server context from web-browser-native variables.isSupported() interface to safely suppress tracking on strict storage environments, legacy browsers, or aggressive stealth/incognito viewports.purchase_seats) are dispatched asynchronously using non-blocking telemetry primitives, decoupled from the critical path of the local transactional database state machine.When operating in decoupled or on-premise environments, the platform switches to a custom, zero-dependency identity layer engineered for high security and performance.
SALT_ROUNDS). This proactively thwarts rainbow-table and high-throughput GPU brute-force attempts.HS256), attached to backend mutation requests.null in the user's row, any active session is immediately revoked on its next rotation attempt, enforcing strict state control.Both authentication subsystems converge into a single defensive interface (verifyAccessToken()). All downstream seat booking endpoints—such as /api/reserve/hold and /api/reserve—interact with this unified contract, remaining entirely agnostic of the underlying auth provider. This strict separation of concerns allows developers to swap the entire identity core via environment variables (.env) without refactoring a single line of business logic.
npm install
npx prisma db push
SEAT-1, SEAT-2, SEAT-3.npm run dev # no seeding sample data - DEV mode
or npm run dev_seed # with seeding sample data - DEV mode
http://localhost:3000 to evaluate.# DEV Mode
run-dev.bat build # MS Dos batch script (included step 1,2) without seeding sample data / with build to install dependencies
or run-dev-seed.bat build # MS Dos batch script (included step 1,2) with seeding sample data (user: [email protected]; password: password123) / with build to install dependencies
# PROD Mode
run-prod.bat build # MS Dos batch script (included step 1,2) without seeding sample data / with build to install dependencies
or run-prod-seed.bat build # MS Dos batch script (included step 1,2) with seeding sample data (user: [email protected]; password: password123) / with build to install dependencies
# Compose up
docker-compose-up.bat # for SQLite - build image with cache
or docker-compose-up.bat postgres # for PostgreSQL - build image with cache
docker-compose-up.bat sqlite --no-cache # for SQLite - build image without cache, fresh build
or docker-compose-up.bat postgres --no-cache # for PostgreSQL - build image without cache, fresh build
# Compose down
docker-compose-down.bat # for SQLite
or docker-compose-down.bat postgres # for PostgreSQL
The platform currently utilizes a client-triggered proxy (mockPaymentSuccess) within the /api/reserve endpoint to simulate payment outcomes. While highly efficient for local integration testing and instant state transition verification, this synchronous approach introduces a single point of failure and does not meet enterprise production standards for asynchronous financial reconciliation.
To ensure 100% financial reliability, network fault tolerance, and eventual consistency, the production blueprint replaces the mock layer with an asynchronous, decoupled Webhook architecture integrated with payment gateways (e.g., Stripe, PayPal, or local banking APIs).
+----------------+ 1. Hold Seat +------------------+ 2. Checkout Session +-----------------+
| Web/Mobile | ---------------------> | Next.js Server | ---------------------------> | Payment Gateway |
+----------------+ +------------------+ +-----------------+
^ | |
| | 4. Update State | 3. Webhook Event
+-------------------------------------------+ <----------------------------------------------+
(ACID/Idempotent)
Payment gateways often guarantee At-Least-Once delivery, meaning the same webhook event (e.g., payment_intent.succeeded) can be fired multiple times due to network retries.
PaymentIntentID or TransactionID as a locking key.COMPLETED or FAILED, the server immediately skips execution and returns a 200 OK handshake response to the gateway, preventing duplicate billing or multiple seat assignments.To thwart Replay Attacks and prevent malicious actors from spoofing successful payment payloads to unblock seats without paying:
X-Webhook-Signature header from the incoming request.WEBHOOK_SIGNING_SECRET), the runtime recalculates the HMAC-SHA256 checksum of the raw request body.400 Bad Request if the computed signature does not perfectly match the header payload.Network instability or transient database deadlocks can cause webhook ingestion to fail mid-flight.
If a payment gateway suffers a catastrophic outage and fails to fire webhooks entirely, the platform’s Passive Sweeper Logic (/api/seats) and Active Background Worker (/api/release) act as safety nets [^2, 3]:
PENDING state.BOOKED and completes the order [^2], maintaining absolute eventual consistency across all edge distributed node clusters.To comply with enterprise security auditing, financial reconciliation, and anomaly detection standards, the platform features an asynchronous, Append-Only Audit Logging Infrastructure.
This component acts as an immutable ledger designed to monitor and store data related to high-risk business state changes without introducing performance overhead to the primary seating pipeline.
AuditLog database entity behaves as a data-sink. The backend service architecture purposefully exposes no Update or Delete endpoints for this model.console.error), and permits the user’s primary financial transaction to proceed uninterrupted.To enforce non-repudiation and defend against malicious automated scripts or distributed attacks, the logger extracts metadata passing through Kubernetes Ingress or reverse-proxies:
X-Forwarded-For and X-Real-IP.Each generated log captures a strict, standardized state dictionary:
action: High-level operational type classification (HOLD_SEAT, PAYMENT_SUCCESS, PAYMENT_FAILED).target: Clear text representation of the mutated resources (e.g., Seats: seat-1, seat-2).details: A comprehensive JSON payload capturing contextual data, exception trace messages, or raw webhook identifiers for subsequent cross-referencing.Does the current session approach have the ability to handle a mobile app integration in the future?
Yes, absolutely. The core authentication architecture of this platform was engineered from day one to be completely stateless and API-first, ensuring seamless horizontal scalability across multiple client channels, including Web, iOS, Android, and third-party API integrations.
To satisfy enterprise-grade mobile requirements, the platform deliberately avoids traditional, stateful server-side sessions (such as Redis-backed or sticky session stores). Instead, it implements a strict Stateless Dual-Token Framework (JWT Access Token + Refresh Token):
While the Web client securely encapsulates tokens within HTTP-Only, SameSite=Lax Cookies to mitigate Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) vulnerabilities, the mobile client is decoupled from browser-native cookie management:
Authorization: Bearer <JWT> header, ensuring total compatibility with the existing backend parsing logic.The backend's Silent Token Rotation endpoint (/api/auth/refresh) is completely decoupled from Web context [^8]:
401 Unauthorized status.Because the backend endpoints—such as /api/reserve/hold and /api/reserve—rely entirely on a stateless contract contract interface (verifyAccessToken()), they are fully agnostic of the client’s architecture.
+-----------------------+ (HTTP-Only Cookie) +---------------------------------+
| Web App | <--------------------------> | |
+-----------------------+ | |
| Next.js API Gateway |
+-----------------------+ (Authorization Header) | (Stateless Token Verification) |
| Mobile App (iOS) | <--------------------------> | |
+-----------------------+ +---------------------------------+
When operating in Cloud-Native Mode (AUTH_PROVIDER="firebase"), migrating to mobile introduces zero backend friction. The native iOS/Android Firebase SDKs will authenticate users directly against Google OAuth endpoints. The generated IdToken will then be transmitted to our API gateway via raw request bodies to establish the same verified session context.
By adopting a Stateless Token Pipeline rather than traditional server-bound cookie sessions, the platform eliminates infrastructure lock-in. This delivers a unified, production-ready backend capable of powering responsive desktop layouts and native mobile viewports under a single, shared security blueprint.
How would you handle a failed webhook from the payment gateway?
Handling a failed webhook requires a multi-layered defensive strategy to ensure eventual consistency and prevent deadlocks (where a seat remains permanently locked in PENDING status or a user pays but never gets their seat) [^2, 3].
The platform guarantees data reconciliation and transactional recovery through four coordinated engineering patterns:
Most modern payment gateways (e.g., Stripe, Adyen) do not expect an immediate single handshake. If our server fails to return a 200 OK response due to transient network drops or database lock contention, the gateway automatically queues the webhook for retry using an exponential backoff strategy (e.g., retrying up to 3–5 times over a 24-hour window).
In a high-concurrency production scenario, the webhook landing endpoint does not process business logic or communicate with the database directly.
If the payment gateway suffers an internal disaster and completely fails to broadcast webhooks, the system activates its dual passive/active sweeping architecture to prevent seating state deadlocks [^2, 3]:
/api/seats endpoint, the server runs a sub-millisecond query to locate any PENDING bookings that have outlived their 5-minute lifespan (expiresAt < NOW()) and automatically reverts those seats back to AVAILABLE [^2, 3].PENDING rows close to expiration. It makes an outbound secure REST API request directly to the payment gateway's logs (e.g., GET /v1/payment_intents/id) to verify the factual status. If the gateway reports the transaction was successful, our script bypasses the missing webhook, upgrades the seat to BOOKED, and confirms the order [^2].If a webhook payload contains malformed data or fails processing after maximum message broker retries, it is quarantined inside a Dead-Letter Queue (DLQ).
The platform packages a production-ready Playwright automation suite to perform end-to-end regression testing on the core distributed business state machine.
| GitHubCI/CD Workflows | Latest Running Status(es) |
|---|---|
| 🚀 [ TEST ] Seats Reservation Platform CI/CD Pipeline |
The automated matrix simulates headless user actors to validate non-deterministic edge scenarios:
Content type
Image
Digest
sha256:7901040c4…
Size
607.6 MB
Last updated
4 months ago
docker pull hainguyen81/seats-reservation-postgres