Skip to content

About

High-performance distributed ticket reservation system built with Node.js, Express, TypeScript, PostgreSQL, Redis, and Docker. Handles high-concurrency traffic, prevents race conditions with distributed locking, and manages async checkout queues via BullMQ.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

# 🎟️ TicketFlow — High-Performance Ticket Reservation Backend System

**TicketFlow** is a production-ready, modular, and high-concurrency ticket reservation backend system built with **Node.js, Express, TypeScript, PostgreSQL, and Redis**.

The system is designed to handle high traffic and prevent **race conditions** (overbooking) during peak ticket sales using a multi-layer defense strategy featuring **Redis Distributed Locks**, **PostgreSQL Optimistic Locking**, and **BullMQ Delay Workers**.

---

## 🏗️ Architecture & Features

- **Functional & Modular Architecture**: Built without classes for lighter, cleaner, and highly testable code with zero `this` binding issues.
- **Race Condition Prevention**:
  - **Layer 1 (Redis Instant Lock)**: `SET key val NX PX` ensures fast atomic lock acquisition before hitting the database.
  - **Layer 2 (Optimistic Locking)**: PostgreSQL `version` field checks prevent concurrent modification errors.
- **Automated Expiry Workers (BullMQ)**: Reserved tickets are automatically released back to the market if payment is not completed within 15 minutes.
- **Security & RBAC**: Access & Refresh token rotation with **Redis-backed Token Revocation** and Role-Based Access Control (`ADMIN`, `CUSTOMER`).
- **Rate Limiting & Protection**: Protected against DDoS and ticket scraping via **Helmet** and **Redis-backed IP Rate Limiting**.
- **Centralized Error Handling & Logging**: Fully structured JSON logging powered by **Pino** and wrapped with `asyncHandler`.
- **Interactive API Documentation**: Live Swagger/OpenAPI UI served directly at `/api-docs`.

---

## 🛠️ Tech Stack

- **Language & Runtime**: Node.js, TypeScript (Native ESM / NodeNext)
- **Framework**: Express.js
- **Database**: PostgreSQL (`pg` raw queries)
- **Caching & Locks**: Redis (`ioredis` + `@redis/client`)
- **Queue / Background Jobs**: BullMQ
- **Validation**: Zod
- **Documentation**: Swagger UI & OpenAPI 3.0
- **DevOps**: Docker, Docker Compose (Multi-stage build)

---

## ⚡ Quick Start with Docker

### Prerequisites
Make sure you have **Docker** and **Docker Compose** installed on your machine.

### 1. Clone the Repository
```bash
git clone [https://github.com/your-username/ticketflow.git](https://github.com/your-username/ticketflow.git)
cd ticketflow

2. Environment Setup

Copy the example environment file and configure your variables if necessary:

cp .env.example .env

3. Run with Docker Compose

Start the backend app, PostgreSQL, and Redis with a single command:

docker-compose up --build -d

Note: PostgreSQL tables and ENUM types are automatically initialized on startup using src/database/init.sql.

The API will be available at: http://localhost:3000

The Swagger Documentation will be available at: http://localhost:3000/api-docs


📂 Project Structure

ticketflow/
├── src/
│   ├── config/            # Database, Redis, Pino, and Swagger configs
│   ├── database/          # Database initialization SQL scripts
│   ├── jobs/              # BullMQ queue definitions and workers
│   ├── middlewares/       # Auth, Rate Limiter, Validation, and Global Error Handler
│   ├── modules/
│   │   ├── auth/          # User authentication module (Types, Repo, Service, Controller, Routes)
│   │   └── tickets/       # Event and Ticket reservation module
│   ├── utils/             # AppError and asyncHandler helpers
│   ├── app.ts             # Express app setup and middleware configuration
│   └── server.ts          # Bootstrap server, DB connections, and Graceful Shutdown
├── .env.example           # Example environment variables template
├── Dockerfile             # Multi-stage Docker build file
└── docker-compose.yml     # Docker Compose orchestration


📑 API Endpoints Summary

Auth Module (/api/v1/auth)

Method Endpoint Access Description
POST /register Public Register a new user
POST /login Public Login and receive Access & Refresh Tokens
POST /refresh Public Exchange Refresh Token for new Access Token
POST /logout Protected Revoke session and remove Refresh Token from Redis

Tickets Module (/api/v1)

Method Endpoint Access Description
GET /events Public Get list of all upcoming events
GET /events/:eventId/tickets Public Get all seats and status for a specific event
POST /events Admin Create a new event and generate tickets
POST /tickets/reserve Customer Lock and reserve a ticket (starts 15-min timer)
POST /tickets/purchase Customer Finalize payment and set ticket status to SOLD

🛡️ License

This project is open-source and available under the MIT License.


About

High-performance distributed ticket reservation system built with Node.js, Express, TypeScript, PostgreSQL, Redis, and Docker. Handles high-concurrency traffic, prevents race conditions with distributed locking, and manages async checkout queues via BullMQ.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages