Case Study: Design a Hotel Reservation System

“Hotel reservation system giong nhu mot san bay quoc te — hang trieu nguoi cung muon dat cho tren cung mot chuyen bay, nhung moi chuyen chi co gioi han cho ngoi. Neu ban qua so ghe, hanh khach se bi ‘bumped’ va uy tin cua hang bay mat vinh vien.”

Tags: system-design hotel-reservation concurrency-control overbooking inventory-management alex-xu-vol2 case-study Student: Hieu Prerequisite: Tuan-02-Back-of-the-envelope · Tuan-07-Database-Sharding-Replication · Tuan-08-Message-Queue Lien quan: Tuan-11-Microservices-Pattern · Tuan-14-AuthN-AuthZ-Security · Tuan-15-Data-Security-Encryption · Case-Design-Payment-System Reference: Alex Xu, System Design Interview Volume 2 — Chapter 6: Hotel Reservation System


1. Context & Why — Tai sao Hotel Reservation System quan trong?

1.1 Analogy: He thong dat phong khach san nhu Booking.com / Agoda

Hieu, em tuong tuong minh dang xay dung he thong cho Booking.com hoac Agoda. Moi ngay co hang trieu nguoi tren toan the gioi truy cap de tim phong khach san. Ho search theo thanh pho, ngay check-in/check-out, so nguoi, roi chon phong va dat.

Van de la: khach san “Muong Thanh Grand Da Nang” chi co 50 phong Deluxe. Khi co 200 nguoi cung muon dat phong Deluxe cho dem 31/12 (Giao thua), he thong phai:

  1. Hien thi chinh xac so phong con trong — khong duoc hien thi “con phong” khi da het
  2. Dam bao khong ban qua (overbooking) — 50 phong thi chi cho 50 nguoi dat (hoac nhieu hon 1 chut neu co overbooking strategy)
  3. Xu ly dong thoi — 200 nguoi click “Dat ngay” cung luc, chi 50 nguoi thanh cong
  4. Khong charge 2 lan — nguoi dung click retry vi mang cham, khong duoc tao 2 booking
  5. Tich hop thanh toan — sau khi dat phong, phai thu tien hoac giu the (authorization hold)

1.2 Tai sao day la bai toan kho?

Thach thucGiai thich
Concurrency controlHang ngan nguoi cung dat phong mot thoi diem — lam sao dam bao khong ban qua so phong?
Inventory accuracySo phong phai chinh xac real-time. Hien thi “con 2 phong” nhung thuc te da het = trai nghiem te
Double booking preventionNguoi dung click dat 2 lan, mang cham retry — khong duoc tao 2 reservation
Peak trafficDip le Tet, Noel, Black Friday — traffic tang 10-50x so voi ngay thuong
Cross-service consistencyDat phong thanh cong nhung payment fail → phai rollback inventory
Search performanceTim khach san theo location, gia, rating, amenities — dataset lon, query phuc tap
Overbooking as business decisionAirlines overbooking 5-10% la binh thuong. Khach san cung vay. Phai configurable

1.3 Tai sao Backend Dev can hieu Hotel Reservation?

Ly doGiai thich
Concurrency la core skillHieu concurrency control (pessimistic/optimistic locking) giup em xu ly bat ky bai toan nao co shared resource
Inventory management patternE-commerce (ton kho), ticketing (ghe ngoi), airline (cho) — tat ca deu dung pattern tuong tu
Real-world distributed transactionDat phong + thanh toan + cap nhat inventory = distributed transaction dien hinh
Read-heavy + Write-criticalSearch (read) nhieu gap boi, nhung reservation (write) phai chinh xac 100%
Interview favoriteDay la bai thuong gap trong system design interview vi no bao phu nhieu concept

Aha Moment: Hotel reservation khong chi la “CRUD rooms va bookings”. Core problem la concurrency control tren shared inventory — va cach giai quyet no anh huong den toan bo architecture.


Step 1 — Requirements

1.1 Functional Requirements

RequirementMo taPriority
Search hotelsTim khach san theo location, check-in/check-out date, so khach, filters (gia, rating, amenities)P0
View hotel detailsXem thong tin chi tiet khach san: hinh anh, mo ta, room types, gia, reviewsP0
View room availabilityXem so phong con trong cho tung loai phong, tung ngayP0
Reserve a roomDat phong: chon room type, ngay, nhap thong tin khach, thanh toanP0
Cancel reservationHuy dat phong, refund theo chinh sachP0
Admin: manage inventoryHotel admin cap nhat so phong, gia, dong/mo phong theo muaP0
Admin: view reservationsHotel admin xem danh sach booking, check-in/check-out statusP1
Price managementDynamic pricing theo mua, ngay le, demandP1
Loyalty programTich diem, uu dai cho khach hang than thietP2

1.2 Non-Functional Requirements

RequirementTargetLy do
Availability99.99% (4 nines)Downtime = mat doanh thu truc tiep
ConsistencyStrong consistency cho reservationKhong duoc ban qua so phong
Latency (search)P99 < 500msUser experience — search phai nhanh
Latency (reservation)P99 < 2s (bao gom payment)Chap nhan cham hon search vi co payment
DurabilityZero data loss cho reservationMat booking = mat tien + mat khach
ScalabilityHandle peak 10x normal trafficDip le, flash sale

1.3 Scale Estimation (Pham vi bai toan)

Thong soGia triGhi chu
So khach san5,000Quy mo Agoda Vietnam
Tong so phong1,000,000 (1M)Trung binh 200 phong/khach san
So loai phong trung binh20 / khach sanStandard, Deluxe, Suite, Family, etc.
Read:Write ratio3:7 cho reservation pageNhieu nguoi xem nhung it nguoi dat
Occupancy rate trung binh70%Industry average
Peak season multiplier10xTet, Noel, summer holidays
Average reservation duration2-3 demBusiness + leisure mix

Chu y: Ty le read:write 3:7 cho reservation page la KHAC voi search page. Search page la read-heavy (90%+ read). Reservation page co nhieu write vi moi lan dat phong = write inventory + write reservation + write payment.


Step 2 — High-Level Design

2.1 System Components Overview

ComponentVai troAnalogy
Hotel ServiceQuan ly thong tin khach san, phong, hinh anh, amenitiesCatalog cua khach san
Search ServiceTim kiem khach san theo nhieu tieu chi, rankingGoogle cho khach san
Rate ServiceQuan ly gia phong theo ngay, mua, demand (dynamic pricing)Bo phan dinh gia
Inventory ServiceQuan ly so phong kha dung theo ngay — THE critical serviceKho hang
Reservation ServiceXu ly dat phong, huy phong, thay doi bookingQuay le tan
Payment ServiceTich hop PSP, xu ly thanh toan, refundThu ngan
Notification ServiceGui email/SMS xac nhan booking, reminder check-inNhan vien CSKH

2.2 High-Level Architecture

flowchart TB
    subgraph "Client Layer"
        WEB[Web App<br/>React / Next.js]
        MOBILE[Mobile App<br/>iOS / Android]
        ADMIN[Hotel Admin<br/>Dashboard]
    end

    subgraph "API Gateway"
        GW[API Gateway<br/>Rate Limiting · Auth · Routing]
    end

    subgraph "Core Services"
        HOTEL[Hotel Service<br/>Hotel & Room Info]
        SEARCH[Search Service<br/>Elasticsearch]
        RATE[Rate Service<br/>Dynamic Pricing]
        INV[Inventory Service<br/>Room Availability]
        RESV[Reservation Service<br/>Booking Management]
        PAY[Payment Service<br/>PSP Integration]
    end

    subgraph "Supporting Services"
        NOTIFY[Notification Service<br/>Email · SMS · Push]
        LOYALTY[Loyalty Service<br/>Points · Rewards]
    end

    subgraph "Data Stores"
        PGDB[(PostgreSQL<br/>Reservation · Inventory)]
        REDIS[(Redis<br/>Cache · Session)]
        ES[(Elasticsearch<br/>Hotel Search Index)]
        MQ[Message Queue<br/>Kafka]
    end

    subgraph "External"
        PSP[PSP<br/>Stripe · VNPay]
        CDN[CDN<br/>Hotel Images]
    end

    WEB --> GW
    MOBILE --> GW
    ADMIN --> GW

    GW --> HOTEL
    GW --> SEARCH
    GW --> RESV

    HOTEL --> PGDB
    HOTEL --> CDN
    SEARCH --> ES
    RATE --> PGDB
    RATE --> REDIS
    INV --> PGDB
    INV --> REDIS
    RESV --> PGDB
    RESV --> INV
    RESV --> PAY
    RESV --> MQ
    PAY --> PSP

    MQ --> NOTIFY
    MQ --> LOYALTY

    style INV fill:#e53935,color:#fff
    style RESV fill:#1e88e5,color:#fff
    style PGDB fill:#43a047,color:#fff

Highlight: Inventory Service (mau do) la critical path — moi reservation deu phai di qua no. Neu Inventory Service cham hoac sai, toan bo he thong bi anh huong.

2.3 API Design Overview

APIMethodMo ta
/hotels/searchGETTim khach san theo location, date, filters
/hotels/{id}GETXem chi tiet khach san
/hotels/{id}/roomsGETXem danh sach room types va gia
/hotels/{id}/rooms/availabilityGETCheck so phong con trong theo ngay
/reservationsPOSTTao reservation moi
/reservations/{id}GETXem chi tiet reservation
/reservations/{id}/cancelPOSTHuy reservation
/admin/hotels/{id}/inventoryPUTCap nhat so phong (admin)
/admin/hotels/{id}/ratesPUTCap nhat gia phong (admin)

2.4 Basic Reservation Flow (High-Level)

1. User search khach san tai "Da Nang" cho ngay 31/12 - 02/01
2. Search Service tra ve danh sach khach san co phong trong
3. User chon "Muong Thanh Grand" → xem room types va gia
4. User chon "Deluxe Room" — hien thi "con 3 phong" — click "Dat ngay"
5. Reservation Service: kiem tra inventory → con phong → tao reservation (PENDING)
6. User nhap thong tin + thanh toan
7. Payment Service: charge card hoac authorization hold
8. Payment thanh cong → Reservation chuyen CONFIRMED → Inventory giam 1
9. Notification Service: gui email xac nhan cho user

Step 3 — Deep Dive

3.1 Data Model — Mo hinh du lieu

Hotel Table

FieldTypeMo ta
hotel_idUUIDPrimary key
nameVARCHAR(255)Ten khach san
addressTEXTDia chi
cityVARCHAR(100)Thanh pho
countryVARCHAR(100)Quoc gia
latitudeDECIMAL(10,8)Vi do
longitudeDECIMAL(11,8)Kinh do
star_ratingSMALLINTSo sao (1-5)
descriptionTEXTMo ta chi tiet
amenitiesJSONBTien ich (pool, gym, spa, wifi…)
imagesJSONBDanh sach URL hinh anh
statusENUMACTIVE, INACTIVE, SUSPENDED
created_atTIMESTAMPThoi diem tao
updated_atTIMESTAMPThoi diem cap nhat

Room Type Table

FieldTypeMo ta
room_type_idUUIDPrimary key
hotel_idUUIDForeign key → Hotel
nameVARCHAR(100)Ten loai phong (Standard, Deluxe, Suite)
descriptionTEXTMo ta phong
max_occupancySMALLINTSo nguoi toi da
base_priceBIGINTGia co ban (don vi nho nhat — VND dong)
amenitiesJSONBTien ich phong (minibar, balcony, bathtub)
imagesJSONBHinh anh loai phong
statusENUMACTIVE, INACTIVE

Room Type Inventory Table — THE CORE TABLE

FieldTypeMo ta
inventory_idUUIDPrimary key
hotel_idUUIDForeign key → Hotel
room_type_idUUIDForeign key → Room Type
dateDATENgay cu the
total_inventoryINTTong so phong loai nay
total_reservedINTSo phong da dat
total_availableINTSo phong con trong (= total - reserved)
versionINTOptimistic locking version

Tai sao co bang inventory rieng theo ngay? Vi so phong kha dung khac nhau moi ngay. Ngay 31/12 co the het phong nhung ngay 02/01 con nhieu. Hotel admin cung co the dong mot so phong de bao tri vao ngay cu the. Schema nay cho phep quan ly inventory per-day granularity.

Unique constraint tren inventory table:

UNIQUE (hotel_id, room_type_id, date)

Moi hotel + room type + date chi co dung mot record inventory.

CHECK constraint chong overbooking:

CHECK (total_reserved <= total_inventory)
-- Hoac voi overbooking allowance:
CHECK (total_reserved <= FLOOR(total_inventory * (1 + overbooking_percentage / 100.0)))

Reservation Table

FieldTypeMo ta
reservation_idUUIDPrimary key, dong thoi la idempotency key
hotel_idUUIDForeign key → Hotel
room_type_idUUIDForeign key → Room Type
guest_idUUIDForeign key → User
check_in_dateDATENgay check-in
check_out_dateDATENgay check-out
num_roomsSMALLINTSo phong dat
total_priceBIGINTTong gia (VND)
currencyVARCHAR(3)ISO 4217
statusENUMPENDING, CONFIRMED, CANCELLED, CHECKED_IN, CHECKED_OUT, NO_SHOW
payment_idUUIDForeign key → Payment
special_requestsTEXTYeu cau dac biet
created_atTIMESTAMPThoi diem tao
updated_atTIMESTAMPThoi diem cap nhat
cancelled_atTIMESTAMPThoi diem huy (nullable)
cancellation_reasonTEXTLy do huy (nullable)

Reservation State Machine

stateDiagram-v2
    [*] --> PENDING: User click "Dat phong"

    PENDING --> CONFIRMED: Payment thanh cong
    PENDING --> CANCELLED: Payment fail / timeout / user cancel

    CONFIRMED --> CHECKED_IN: Khach den nhan phong
    CONFIRMED --> CANCELLED: Huy truoc ngay check-in (theo policy)
    CONFIRMED --> NO_SHOW: Khach khong den

    CHECKED_IN --> CHECKED_OUT: Khach tra phong

    CANCELLED --> [*]
    NO_SHOW --> [*]
    CHECKED_OUT --> [*]

Allowed state transitions:

  • PENDING → CONFIRMED: VALID (payment success)
  • PENDING → CANCELLED: VALID (payment fail, timeout, user cancel)
  • CONFIRMED → CHECKED_IN: VALID (guest arrives)
  • CONFIRMED → CANCELLED: VALID (guest cancels before check-in date, subject to cancellation policy)
  • PENDING → CHECKED_IN: INVALID (khong the check-in khi chua thanh toan)
  • CHECKED_OUT → CONFIRMED: INVALID (khong the quay lai trang thai truoc)

3.2 Reservation Flow — Luong dat phong chi tiet

Two-Phase Reservation: Tentative Hold → Confirmed

Reservation khong phai la mot buoc duy nhat. No la 2 phases:

PhaseMo taThoi gianInventory impact
Phase 1: Tentative HoldUser click “Dat phong” → he thong tam giu phong (PENDING)10-15 phutInventory giam (hold)
Phase 2: ConfirmPayment thanh cong → reservation chuyen CONFIRMEDSau paymentInventory confirmed

Tai sao can 2 phases? Vi giua luc user click “Dat phong” va luc payment hoan tat co the mat 5-10 phut (nhap thong tin the, OTP, 3D Secure). Trong thoi gian do, phai “giu” phong de nguoi khac khong dat mat. Nhung neu user khong thanh toan trong 10-15 phut → release hold → tra phong lai inventory.

Reservation Sequence Diagram

sequenceDiagram
    participant U as User
    participant FE as Frontend
    participant RS as Reservation Service
    participant IS as Inventory Service
    participant PS as Payment Service
    participant DB as PostgreSQL
    participant NS as Notification Service

    U->>FE: Click "Dat phong Deluxe"<br/>Check-in: 31/12, Check-out: 02/01
    FE->>RS: POST /reservations<br/>{hotel_id, room_type_id, dates, guest_info}

    Note over RS: Generate reservation_id<br/>(cung la idempotency key)

    RS->>IS: Check availability<br/>{hotel_id, room_type_id, dates}
    IS->>DB: SELECT total_available<br/>FROM room_type_inventory<br/>WHERE date IN (31/12, 01/01)

    alt Con phong (available >= 1)
        IS-->>RS: Available = YES

        RS->>IS: Reserve (tentative hold)
        IS->>DB: UPDATE room_type_inventory<br/>SET total_reserved += 1<br/>WHERE date IN (31/12, 01/01)<br/>AND total_available > 0

        Note over IS: Inventory giam 1 cho moi dem

        IS-->>RS: Hold confirmed

        RS->>DB: INSERT reservation<br/>(status = PENDING)
        RS-->>FE: Reservation PENDING<br/>Redirect to payment

        Note over FE: Timer: 10 phut de thanh toan

        U->>FE: Nhap thong tin thanh toan
        FE->>PS: Process payment<br/>{reservation_id, amount}
        PS-->>FE: Payment SUCCESS

        FE->>RS: Confirm reservation<br/>{reservation_id, payment_id}
        RS->>DB: UPDATE reservation<br/>SET status = CONFIRMED

        RS-->>FE: Booking CONFIRMED!
        RS->>NS: Send confirmation email
        NS-->>U: Email: "Dat phong thanh cong"

    else Het phong (available = 0)
        IS-->>RS: Available = NO
        RS-->>FE: Sorry, het phong!
    end

Hold Expiration — Xu ly khi user khong thanh toan

sequenceDiagram
    participant CRON as Scheduler<br/>(chay moi phut)
    participant RS as Reservation Service
    participant IS as Inventory Service
    participant DB as PostgreSQL

    CRON->>RS: Check expired holds

    RS->>DB: SELECT reservations<br/>WHERE status = PENDING<br/>AND created_at < NOW() - 10 min

    Note over RS: Tim thay 5 reservations<br/>da qua 10 phut chua thanh toan

    loop Moi reservation het han
        RS->>DB: UPDATE reservation<br/>SET status = CANCELLED
        RS->>IS: Release hold
        IS->>DB: UPDATE room_type_inventory<br/>SET total_reserved -= 1<br/>WHERE date IN (reservation dates)
        Note over IS: Tra phong lai inventory
    end

Aha Moment: Hold expiration la critical. Neu khong co mechanism nay, user co the “giu” phong mai ma khong bao gio thanh toan → het phong ao (phong trong nhung khong ai dat duoc). Phai co background job chay moi phut de release expired holds.

3.3 Concurrency Control — THE Core Problem

Day la bai toan kho nhat cua hotel reservation system. Khi 200 nguoi cung click “Dat phong” cho cung 1 room type vao cung 1 ngay, va chi con 3 phong, lam sao dam bao chi co 3 nguoi dat thanh cong?

Van de: Race Condition

Thread A: Read available = 3 → Reserve 1 → Write available = 2
Thread B: Read available = 3 → Reserve 1 → Write available = 2 (SAI! Phai la 1)
Thread C: Read available = 3 → Reserve 1 → Write available = 2 (SAI! Phai la 0)

Ket qua: 3 nguoi dat nhung inventory chi giam 1 → Overbooking!

Co 3 approaches chinh de giai quyet:

Approach 1: Pessimistic Locking (SELECT FOR UPDATE)

Co che: Lock row truoc khi doc. Cac transaction khac phai cho cho den khi lock duoc release.

Flow:

Transaction A:
  BEGIN;
  SELECT total_reserved, total_available
  FROM room_type_inventory
  WHERE hotel_id = 'H001' AND room_type_id = 'RT001' AND date = '2026-12-31'
  FOR UPDATE;  -- Lock row!
  -- total_reserved = 47, total_available = 3

  UPDATE room_type_inventory
  SET total_reserved = 48, total_available = 2
  WHERE inventory_id = '...';
  COMMIT;  -- Release lock

Transaction B: (cho cho den khi A commit)
  BEGIN;
  SELECT ... FOR UPDATE;  -- Now available = 2
  UPDATE ... SET total_reserved = 49, total_available = 1;
  COMMIT;

Transaction C: (cho cho den khi B commit)
  BEGIN;
  SELECT ... FOR UPDATE;  -- Now available = 1
  UPDATE ... SET total_reserved = 50, total_available = 0;
  COMMIT;

Transaction D: (cho cho den khi C commit)
  BEGIN;
  SELECT ... FOR UPDATE;  -- Now available = 0
  -- Khong du phong → ROLLBACK, bao user "het phong"
  ROLLBACK;
Uu diemNhuoc diem
Don gian, de hieuGiam throughput — cac transaction phai xep hang cho
Chac chan khong overbookingCo the deadlock neu lock nhieu rows sai thu tu
Phu hop khi contention caoLatency tang khi nhieu nguoi cung dat

Approach 2: Optimistic Locking (Version Column)

Co che: Khong lock khi doc. Khi write, kiem tra version co thay doi khong. Neu thay doi → conflict → retry.

Flow:

Transaction A:
  -- Step 1: Read (KHONG lock)
  SELECT total_reserved, total_available, version
  FROM room_type_inventory
  WHERE hotel_id = 'H001' AND room_type_id = 'RT001' AND date = '2026-12-31';
  -- total_reserved = 47, total_available = 3, version = 10

  -- Step 2: Update voi version check
  UPDATE room_type_inventory
  SET total_reserved = 48, total_available = 2, version = 11
  WHERE inventory_id = '...' AND version = 10;
  -- affected_rows = 1 → SUCCESS

Transaction B: (doc cung luc voi A)
  -- Step 1: Read
  SELECT ... -- total_reserved = 47, total_available = 3, version = 10

  -- Step 2: Update voi version check
  UPDATE ... SET total_reserved = 48, version = 11
  WHERE ... AND version = 10;
  -- affected_rows = 0 → CONFLICT! (A da update version len 11)

  -- Step 3: RETRY tu Step 1
  SELECT ... -- total_reserved = 48, total_available = 2, version = 11
  UPDATE ... SET total_reserved = 49, version = 12
  WHERE ... AND version = 11;
  -- affected_rows = 1 → SUCCESS
Uu diemNhuoc diem
Khong blocking — read khong bi lockNhieu retry khi contention cao (hot room, peak season)
Throughput cao hon pessimisticRetry storm: 200 nguoi cung retry → chi 1 nguoi thanh cong moi lan
Phu hop khi conflict itLatency khong du doan (phu thuoc so lan retry)

Approach 3: Database Constraints (CHECK Constraint)

Co che: Dung database constraint de enforce rule. Let DB handle concurrency.

Flow:

-- Tao constraint khi tao table:
ALTER TABLE room_type_inventory
ADD CONSTRAINT chk_no_overbooking
CHECK (total_reserved <= total_inventory);

-- Moi reservation chi can:
UPDATE room_type_inventory
SET total_reserved = total_reserved + 1
WHERE hotel_id = 'H001'
  AND room_type_id = 'RT001'
  AND date = '2026-12-31';

-- Neu total_reserved + 1 > total_inventory
-- → CHECK constraint violation → DB tu reject
-- → Application nhan error → bao user "het phong"
Uu diemNhuoc diem
Don gian nhat — chi can 1 UPDATE statementDua hoan toan vao DB — kho customize logic
DB tu xu ly concurrency (row-level lock cua UPDATE la atomic)Error handling: phai catch constraint violation error
Khong can version column, khong can explicit lockKho implement overbooking percentage (can phuc tap hon)
Reliable — DB engine da duoc test ky luongPerformance phu thuoc vao DB engine

So sanh 3 approaches

Tieu chiPessimistic LockingOptimistic LockingDB Constraints
Do phuc tapTrung binhCao (retry logic)Thap
ThroughputThap (blocking)Cao (no blocking)Cao
ConsistencyStrongEventual (retry)Strong
Contention caoOK nhung chamNhieu retry → chamOK
Deadlock riskCo (multi-row lock)KhongKhong
Overbooking preventionChac chanChac chan (sau retry)Chac chan
Khi nao dungInventory update quan trong, moderate trafficRead-heavy, low contentionKhi muon don gian, trust DB
Hotel reservationPhu hop cho peak seasonPhu hop cho ngay thuongRecommended — don gian va hieu qua

Recommendation tu Alex Xu: Dung Database Constraints (Approach 3) lam primary strategy. Ly do: don gian nhat, DB engine da toi uu cho concurrent updates, va CHECK constraint dam bao khong bao gio overbooking (tru khi co tinh). Ket hop voi Optimistic Locking (version column) cho cac truong hop can retry logic.

3.4 Overbooking Strategy — Chien luoc ban qua

Overbooking la gi?

Overbooking la viec co tinh ban nhieu phong hon so phong thuc te. Nghe nhu bug nhung thuc ra la business decision.

IndustryOverbooking rateLy do
Airlines5-15%~5% hanh khach no-show. Ban 105 ve cho 100 ghe → toi uu doanh thu
Hotels5-10%~10% khach cancel muon hoac no-show
Car rental10-20%Cao hon vi khach thuong thay doi ke hoach

Tai sao hotel can overbooking?

Tinh huongKhong overbookingCo overbooking
100 phong, 10% no-showBan 100 phong, 10 khach no-show → 90% occupancyBan 110 phong, 10 no-show → 100% occupancy
Doanh thuMat 10% doanh thuToi da doanh thu
Rui roKhong co rui roNeu it no-show hon du kien → phai “relocate” khach

Implementation: Configurable Overbooking Threshold

Them cot overbooking_percentage vao room_type_inventory:

FieldTypeMo ta
overbooking_percentageDECIMAL(5,2)% overbooking cho phep. Default = 0 (khong overbooking)

Logic kiem tra availability:

Vi du: Hotel co 100 phong Deluxe, overbooking 10%:

CHECK constraint voi overbooking:

CHECK (total_reserved <= FLOOR(total_inventory * (1 + overbooking_percentage / 100.0)))

Aha Moment: Overbooking KHONG phai la bug — no la business decision duoc cau hinh boi hotel manager. Moi khach san co overbooking rate khac nhau. Luxury hotel (Ritz-Carlton) thuong overbooking 0-2% vi cost cua relocation rat cao. Budget hotel co the overbooking 10-15%.

Xu ly khi overbooking xay ra (khach den nhung het phong)

BuocHanh dong
1He thong phat hien: so khach check-in > so phong thuc te
2Tim khach san doi tac (partner hotel) co phong trong
3Upgrade khach len phong tot hon (neu con)
4Relocate khach sang partner hotel + chiu chi phi
5Compensation: refund + voucher cho lan sau
6Ghi nhan metric: overbooking_relocation_count

3.5 Idempotency — Chong dat phong trung lap

Van de: Client Retry → Double Booking

User click "Dat phong" → Network cham → Khong nhan response
→ User click "Dat phong" lan 2
→ Server nhan 2 request → Tao 2 reservation → Charge 2 lan!

Day la van de kinh dien trong moi transaction system. Giai phap: Idempotency Key.

Implementation: reservation_id la Idempotency Key

BuocMo ta
1Frontend generate reservation_id (UUID v4) truoc khi gui request
2Gui request: POST /reservations voi reservation_id trong body
3Server check: SELECT * FROM reservations WHERE reservation_id = ?
4aNeu khong ton tai → tao reservation moi
4bNeu da ton tai → tra ve reservation cu (KHONG tao moi)

Database enforcement:

UNIQUE INDEX ON reservations(reservation_id)

Neu 2 request cung reservation_id den cung luc:

  • Request 1: INSERT thanh cong
  • Request 2: UNIQUE constraint violation → catch error → return existing reservation

Tai sao frontend generate ID? Vi neu server generate ID, khi response bi mat (network timeout), client khong biet ID → khong the retry an toan. Khi frontend generate ID, client luon gui cung ID khi retry → server nhan ra request trung → tra ve ket qua cu.

Idempotency cho Payment

Tuong tu, payment cung can idempotency:

FieldVai tro
reservation_idIdempotency key cho reservation
payment_idempotency_keyIdempotency key gui cho PSP (Stripe Idempotency-Key header)
POST /payments
Headers: Idempotency-Key: {reservation_id}
Body: {amount: 2000000, currency: "VND"}

→ PSP (Stripe) se khong charge 2 lan voi cung Idempotency-Key

Aha Moment: Idempotency key ngan double charge — mot trong nhung loi nghiem trong nhat trong booking system. Khach hang bi charge 2 lan = mat uy tin + refund process phuc tap + review xau.

3.6 Handling High Concurrency During Flash Sales

Van de: 1000 nguoi cung dat 10 phong

Trong flash sales (gia soc, Black Friday), co the co hang ngan request dong thoi cho 1 hotel voi so phong rat han che. Luc nay:

  • Optimistic locking: retry storm — 1000 nguoi retry, chi 1 thanh cong moi vong → 999 retry → latency bung
  • Pessimistic locking: 1000 transaction xep hang cho → timeout → user experience te
  • DB constraint: 1000 UPDATE dong thoi → DB row-level lock → van bottleneck

Giai phap: Queue-Based Reservation

Thay vi de 1000 request truc tiep vao DB, dung message queue de serialize requests:

flowchart LR
    subgraph "Incoming Requests"
        R1[Request 1]
        R2[Request 2]
        R3[Request 3]
        R4[Request ...]
        R5[Request 1000]
    end

    subgraph "Queue"
        MQ[Message Queue<br/>Kafka / Redis Stream<br/>FIFO]
    end

    subgraph "Consumer"
        C1[Reservation Worker<br/>Process sequentially]
    end

    subgraph "Database"
        DB[(PostgreSQL<br/>Inventory)]
    end

    subgraph "Result"
        S[SUCCESS<br/>Phong da dat]
        F[FAILED<br/>Het phong]
    end

    R1 --> MQ
    R2 --> MQ
    R3 --> MQ
    R4 --> MQ
    R5 --> MQ
    MQ --> C1
    C1 --> DB
    C1 --> S
    C1 --> F

Flow:

BuocMo ta
11000 requests den → tat ca duoc dua vao message queue
2API tra ve ngay: “Yeu cau cua ban dang duoc xu ly” (202 Accepted)
3Consumer doc tu queue, xu ly tuan tu (1 request mot luc)
4Consumer check inventory → con phong → reserve → tra ket qua qua WebSocket/polling
5Het phong → cac request con lai bi reject
6Notification gui cho user: “Dat phong thanh cong” hoac “Het phong”

Trade-off: Chuyen tu synchronous (click → ket qua ngay) sang asynchronous (click → cho → ket qua sau). User experience thay doi: hien thi “Dang xu ly…” thay vi ket qua lien. Nhung dam bao khong overbooking va khong crash khi traffic spike.

Redis cho Fast Inventory Check

Truoc khi dua request vao queue, dung Redis de pre-check inventory:

BuocMo ta
1Khi inventory thay doi → update Redis: SET inv:H001:RT001:2026-12-31 3 (con 3 phong)
2Request den → check Redis: GET inv:H001:RT001:2026-12-31
3Neu Redis = 0 → tra ve “Het phong” ngay, KHONG can vao queue
4Neu Redis > 0 → dua vao queue de xu ly
5Sau khi reserve thanh cong → DECR inv:H001:RT001:2026-12-31

Luu y quan trong: Redis chi la pre-check (approximate), KHONG phai source of truth. Source of truth luon la PostgreSQL. Redis co the sai (stale data) → nhung DB constraint se bat loi cuoi cung.

Multi-layer protection: Redis reject 90% request nhanh (het phong) → Queue handle 10% con lai tuan tu → DB constraint bao ve cuoi cung. Ba layer nay ket hop dam bao zero overbooking voi high throughput.

3.7 Caching Strategy

Hotel & Room Data — Cache-Friendly

Du lieuCache strategyTTLLy do
Hotel info (ten, dia chi, amenities)Cache-aside voi Redis1 gioThay doi it, read nhieu
Room type info (mo ta, hinh anh)Cache-aside voi Redis1 gioTuong tu hotel info
Hotel imagesCDN cache24 gioStatic content, rat it thay doi
Hotel reviews/ratingsCache-aside15 phutThay doi vua phai
Search resultsCache-aside voi Elasticsearch5 phutThay doi theo inventory

Inventory Data — NGUY HIEM khi cache

Van deGiai thich
Stale inventoryCache noi “con 2 phong” nhung thuc te da het → user dat phong → fail → bad UX
Cache invalidationMoi khi co reservation/cancellation → phai invalidate cache ngay
Race conditionInvalidate cache → 100 requests doc tu DB cung luc → cache stampede
Flash saleInventory thay doi lien tuc → cache luon bi invalidate → cache hit rate ~ 0%

Ket luan: KHONG nen cache inventory data cho real-time availability check. Ly do:

  1. Inventory thay doi qua thuong xuyen (moi reservation → thay doi)
  2. Sai lech inventory = overbooking hoac lost revenue
  3. Cache invalidation phuc tap va error-prone

Aha Moment: “Not everything should be cached”. Inventory la write-heavy, accuracy-critical data. Cache no se tao nhieu van de hon giai quyet. Doc truc tiep tu DB (voi proper indexing) la an toan hon.

Ngoai le: Redis cho flash sale (section 3.6) la approximate pre-check, khong phai cache cho accurate availability. No chi de reject request nhanh khi chac chan het phong.

Du lieuCache?Ly do
Hotel infoCoRead-heavy, rarely changes
Room typeCoRead-heavy, rarely changes
Inventory (real-time)KHONGWrite-heavy, accuracy-critical
Price/RateCo (short TTL)Thay doi hang ngay nhung khong lien tuc
Search resultsCo (short TTL)Chap nhan slightly stale

3.8 Database Choice

ServiceDatabaseLy do
Reservation + InventoryPostgreSQLACID required, transaction support, CHECK constraints, strong consistency
Hotel SearchElasticsearchFull-text search, geo-spatial queries, faceted search (filter theo gia, rating, amenities)
CachingRedisIn-memory, sub-millisecond latency, data structures (String, Hash, Sorted Set)
SessionRedisFast session lookup, auto-expiry (TTL)
Hotel ImagesS3 + CDNObject storage cho hinh anh, CDN cho fast delivery
AnalyticsClickHouse / BigQueryPhan tich booking trends, revenue, occupancy rates
Message QueueKafkaHigh throughput, durability, replay capability

Tai sao PostgreSQL cho reservation? Vi reservation can ACID transactions — Atomicity (dat phong + giam inventory phai cung thanh cong hoac cung fail), Consistency (CHECK constraint), Isolation (concurrent updates), Durability (khong mat data). NoSQL (MongoDB, DynamoDB) khong co native ACID transaction phu hop cho bai toan nay.

3.9 Microservices Decomposition

flowchart TB
    subgraph "Public-Facing"
        SEARCH[Search Service<br/>Elasticsearch queries<br/>Stateless · Horizontally scalable]
        HOTEL[Hotel Service<br/>Hotel & Room CRUD<br/>Read-heavy · Cacheable]
    end

    subgraph "Core Transaction"
        RESV[Reservation Service<br/>Booking lifecycle<br/>Stateful · ACID required]
        INV[Inventory Service<br/>Room availability<br/>Hot path · Concurrency control]
        PAY[Payment Service<br/>PSP integration<br/>Idempotent · Retryable]
    end

    subgraph "Supporting"
        RATE[Rate Service<br/>Dynamic pricing<br/>Read-heavy · Cacheable]
        NOTIFY[Notification Service<br/>Email · SMS · Push<br/>Async · Fire-and-forget]
        LOYALTY[Loyalty Service<br/>Points · Rewards<br/>Eventually consistent]
    end

    SEARCH --> HOTEL
    SEARCH --> INV
    RESV --> INV
    RESV --> PAY
    RESV --> RATE
    RESV --> NOTIFY
    RESV --> LOYALTY

    style INV fill:#e53935,color:#fff
    style RESV fill:#1e88e5,color:#fff
    style PAY fill:#ff6f00,color:#fff

Scaling strategy cho tung service — tham chiếu Tuan-11-Microservices-Pattern:

ServiceScaling strategyLy do
Search ServiceHorizontal scale (nhieu instance)Stateless, read-heavy
Hotel ServiceHorizontal scale + cacheStateless, read-heavy, cacheable
Rate ServiceHorizontal scale + cacheRead-heavy, rate data cached
Inventory ServiceVertical scale (strong DB) + read replicasStateful, write-heavy, can strong consistency
Reservation ServiceHorizontal scale (stateless logic) + shared DBBusiness logic stateless, DB la bottleneck
Payment ServiceHorizontal scale, idempotentStateless, PSP xu ly state
Notification ServiceHorizontal scale + queueAsync, tolerant of delay

Key insight: Inventory Service la bottleneck cua he thong. Scale no = scale DB (vertical + replication). Cac service khac co the horizontal scale de dang vi stateless.

3.10 Data Consistency — Saga Pattern cho Cross-Service Transaction

Van de: Distributed Transaction

Khi user dat phong, can thuc hien 3 buoc o 3 service khac nhau:

  1. Inventory Service: Giam so phong
  2. Payment Service: Charge user
  3. Reservation Service: Confirm booking

Neu buoc 2 (Payment) fail sau khi buoc 1 (Inventory) da thanh cong → inconsistency: phong da bi giam nhung khong co booking.

Saga Pattern — Choreography-Based

sequenceDiagram
    participant RS as Reservation Service
    participant IS as Inventory Service
    participant PS as Payment Service
    participant NS as Notification Service
    participant MQ as Kafka

    RS->>IS: 1. Reserve inventory (hold)
    IS-->>RS: Inventory held

    RS->>PS: 2. Process payment

    alt Payment SUCCESS
        PS-->>RS: Payment confirmed
        RS->>RS: 3. Update reservation → CONFIRMED
        RS->>MQ: Publish: BookingConfirmed
        MQ->>NS: 4. Send confirmation
        NS-->>RS: Email sent
    else Payment FAILED
        PS-->>RS: Payment failed
        RS->>IS: COMPENSATE: Release inventory
        IS-->>RS: Inventory released
        RS->>RS: Update reservation → CANCELLED
        RS->>MQ: Publish: BookingCancelled
        MQ->>NS: Send cancellation notice
    end

Saga Steps va Compensating Actions

StepServiceForward ActionCompensating Action (khi fail)
1Inventory ServiceReserve rooms (hold)Release hold → tra phong lai
2Payment ServiceCharge card / Auth holdRefund / void authorization
3Reservation ServiceConfirm reservationCancel reservation
4Notification ServiceSend confirmation emailSend cancellation email

Failure scenarios:

ScenarioXay ra giCompensating actions
Step 1 fail (het phong)Bao user “het phong”Khong can compensate (chua lam gi)
Step 2 fail (payment declined)Payment failCompensate Step 1: release inventory hold
Step 3 fail (DB error)Reservation khong luu duocCompensate Step 2: refund payment. Compensate Step 1: release inventory
Step 4 fail (email fail)Email khong gui duocKhong can compensate (non-critical) — retry email later

Quan trong: Thu tu compensating actions la nguoc lai voi thu tu forward actions. Compensate tu buoc gan nhat nguoc ve buoc dau tien. Tham khao chi tiet tai Tuan-11-Microservices-Pattern.


Capacity Estimation — Uoc luong nang luc

Assumptions

Thong soGia triGiai thich
So khach san5,000Quy mo medium platform
Tong so phong1,000,000 (1M)200 phong/khach san trung binh
Room types / khach san20Standard, Deluxe, Suite, etc.
Reservation/ngay100,000 (100K)~10% occupancy change per day
Search queries/ngay5,000,000 (5M)50x reservation volume
Average booking duration2.5 demBusiness + leisure mix
Peak-to-average ratio10xTet, Noel, summer
Average reservation payload1 KBJSON with guest info
Average search payload2 KBResponse with hotel list

Reservation QPS

Nhan xet: 11.6 TPS peak — day la moderate scale. PostgreSQL co the xu ly hang ngan TPS. Reservation khong phai bottleneck ve throughput. Concurrency control tren cung 1 row moi la van de chinh.

Search QPS

Nhan xet: 579 QPS peak cho search. Elasticsearch co the xu ly hang ngan QPS. Nhung moi query co the fan-out ra nhieu index → can toi uu query va cache.

Inventory Table Size

So records trong room_type_inventory:

Kich thuoc moi record:

Nhan xet: 3.65 GB — vua du cho single PostgreSQL instance. Nhung can partitioning theo date de toi uu query (chi query cac ngay trong tuong lai, khong can scan ngay da qua). Partition theo month la hop ly.

Reservation Storage

Nhan xet: 182.5 GB cho 5 nam — PostgreSQL xu ly thoai mai. Co the archive reservations cu hon 2 nam sang cold storage.

Cache Sizing

Nhan xet: 325 MB — Redis default max memory la 0 (unlimited), nhung 325 MB la rat nho. Mot Redis instance 1 GB la du.

Tom tat Estimation

MetricValue
Reservation QPS (peak)~12/s
Search QPS (peak)~580/s
Inventory table size~3.65 GB
Reservation storage/year~36.5 GB
5-year reservation storage~182.5 GB
Redis cache~325 MB
Inventory records~36.5M

Security — Bao mat

Payment Data Protection (PCI-DSS)

Tham khao chi tiet tai Case-Design-Payment-System va Tuan-15-Data-Security-Encryption.

Nguyen tacAp dung cho Hotel Reservation
KHONG luu card numberDung PSP (Stripe, VNPay) hosted payment page. Chi luu token
TokenizationCard data → token. Em chi luu token + last 4 digits
TLS 1.2+Moi API call phai qua HTTPS. Khong bao gio truyen card data qua HTTP
PCI-DSS scope reductionDung hosted payment page → giam PCI-DSS compliance scope

Prevent Price Manipulation

Tan congMo taPhong chong
Price tamperingUser sua gia tren frontend (inspect element, intercept request)Server-side price validation: luon tinh gia tu DB, KHONG tin gia tu client
Race condition exploitDat phong voi gia cu sau khi gia da tangLock gia tai thoi diem tao reservation, gia duoc tinh tren server
Coupon abuseDung coupon nhieu lan hoac coupon cua nguoi khacUnique coupon per user, server-side validation, rate limiting

Price validation flow:

BuocMo ta
1Client gui: {hotel_id, room_type_id, dates} — KHONG gui price
2Server tinh gia tu Rate Service: base_price x nights x tax
3Server tra ve gia chinh thuc cho client hien thi
4Client confirm → Server tinh gia LAI lan nua truoc khi charge
5Neu gia thay doi giua luc hien thi va luc confirm → thong bao user gia moi

Rule: KHONG BAO GIO tin gia tu client. Luon tinh gia tren server tai moi buoc.

Rate Limiting — Chong Inventory Scraping

Tan congMo taPhong chong
Inventory scrapingBot crawl tat ca availability de ban lai (OTA arbitrage)Rate limiting: 100 requests/phut/IP
Search abuseBot search lien tuc de theo doi giaCAPTCHA sau 50 searches, rate limit per user
Reservation botBot tu dong dat phong khi thay gia thapDevice fingerprinting, behavioral analysis
DDoSTan cong lam sap he thongWAF (Web Application Firewall), CDN protection (Cloudflare)

Rate limiting strategy — tham khao Tuan-09-Rate-Limiter:

EndpointRate limitLy do
/hotels/search100 req/min/IPChong scraping
/hotels/{id}/rooms/availability60 req/min/IPChong inventory scraping
/reservations (POST)10 req/min/userChong booking bot
/reservations/{id}/cancel5 req/min/userChong abuse

User Data Privacy (GDPR / PDPA)

Du lieuPhan loaiBao ve
Ten, email, SDTPII (Personally Identifiable Information)Encrypt at rest (AES-256), access control
Passport/CCCDSensitive PIIEncrypt + restricted access, auto-delete sau 30 ngay
Payment tokenPayment dataPCI-DSS compliant storage
Booking historyPersonal dataAccessible only by user + authorized staff
IP address, device infoTechnical dataLog rotation, anonymize after 90 ngay
GDPR RightImplementation
Right to accessAPI cho user xem toan bo data cua ho
Right to deletionSoft delete + anonymize PII sau retention period
Right to portabilityExport booking history dang JSON/CSV
Consent managementExplicit opt-in cho marketing emails

DevOps & Monitoring — Van hanh va giam sat

Key Metrics to Monitor

MetricMo taAlert ThresholdSeverity
Reservation Success Rate% dat phong thanh cong (khong tinh het phong)< 95% → alertP1 (Critical)
Overbooking Rate% khach bi relocate do overbooking> 2% → alertP1
Inventory AccuracyInventory trong DB vs thuc te (sau reconciliation)Discrepancy > 0.1% → alertP1
Search Latency P99Thoi gian search 99th percentile> 500ms → alertP2
Reservation Latency P99Thoi gian dat phong E2E> 3s → alertP2
Payment Failure Rate% thanh toan that bai> 10% → alertP1
Hold Expiration Rate% reservation PENDING bi timeout> 30% → investigateP3
Cache Hit Rate% request duoc serve tu cache< 80% → investigateP3
DB Connection PoolSo connection hien tai / max> 80% → alertP2
Queue DepthSo message trong Kafka waiting> 10,000 → alertP2

Dashboard Layout

PanelMetricsVisualization
Booking HealthSuccess rate, volume, error breakdownTime series (last 24h)
InventoryOccupancy rate per city, overbooking eventsHeatmap + counter
Search PerformanceQPS, latency P50/P95/P99Line chart + histogram
PaymentSuccess/failure rate, PSP latencyPie chart + time series
InfrastructureCPU, memory, DB connections, cache hit rateGauge + sparkline
BusinessRevenue, ADR (Average Daily Rate), RevPARCounter + trend

Alerting Rules

AlertConditionAction
Overbooking detectedKhach check-in > so phong availablePage on-call, tim phong thay the
Payment gateway downPSP error rate > 50% cho 5 phutFailover sang PSP backup, page team
Inventory discrepancyDB inventory khac actual > thresholdFreeze booking cho hotel do, investigate
Search degradationP99 > 2s cho 10 phutScale Elasticsearch nodes, check query performance
Expired hold spikeHold expiration rate > 50% trong 1 gioCheck payment flow, PSP latency

SLA Monitoring

SLATargetMeasurement
Uptime99.99% (52.6 phut downtime/nam)Synthetic monitoring moi 30 giay
Search availability99.95%Health check endpoint
Booking availability99.99%End-to-end booking test moi 5 phut
Data durability99.999999999% (11 nines)DB replication + backup verification

Mermaid Diagrams — Tong hop

Diagram 1: High-Level Architecture (da co o Section 2.2)

Diagram 2: Reservation Flow (da co o Section 3.2)

Diagram 3: Concurrency Control Comparison

flowchart TB
    subgraph "Approach 1: Pessimistic Locking"
        P1[Transaction A<br/>SELECT ... FOR UPDATE]
        P2[Row LOCKED]
        P3[Transaction B<br/>WAITING...]
        P4[A commits → B proceeds]

        P1 --> P2
        P2 --> P3
        P3 -.->|wait| P4
    end

    subgraph "Approach 2: Optimistic Locking"
        O1[Transaction A<br/>Read version=10]
        O2[Transaction B<br/>Read version=10]
        O3[A: UPDATE WHERE version=10<br/>SUCCESS → version=11]
        O4[B: UPDATE WHERE version=10<br/>CONFLICT → RETRY]

        O1 --> O3
        O2 --> O4
    end

    subgraph "Approach 3: DB Constraint"
        D1[Transaction A<br/>UPDATE reserved += 1]
        D2[Transaction B<br/>UPDATE reserved += 1]
        D3[DB: CHECK reserved <= total<br/>A: OK · B: OK or REJECT]

        D1 --> D3
        D2 --> D3
    end

    style P2 fill:#e53935,color:#fff
    style O4 fill:#ff6f00,color:#fff
    style D3 fill:#43a047,color:#fff

Diagram 4: Saga Pattern cho Reservation

flowchart TB
    START([User click Dat Phong]) --> S1

    subgraph "Forward Flow"
        S1[Step 1: Reserve Inventory<br/>Inventory Service]
        S2[Step 2: Process Payment<br/>Payment Service]
        S3[Step 3: Confirm Booking<br/>Reservation Service]
        S4[Step 4: Send Notification<br/>Notification Service]
    end

    subgraph "Compensating Flow"
        C1[Compensate: Release Inventory<br/>Inventory Service]
        C2[Compensate: Refund Payment<br/>Payment Service]
        C3[Compensate: Cancel Booking<br/>Reservation Service]
    end

    S1 -->|Success| S2
    S2 -->|Success| S3
    S3 -->|Success| S4
    S4 --> DONE([Booking Confirmed!])

    S1 -->|Fail| FAIL1([Het phong])
    S2 -->|Fail| C1
    S3 -->|Fail| C2
    C2 --> C1
    C1 --> FAIL2([Booking Failed<br/>User notified])

    style S1 fill:#1e88e5,color:#fff
    style S2 fill:#ff6f00,color:#fff
    style S3 fill:#43a047,color:#fff
    style S4 fill:#7b1fa2,color:#fff
    style C1 fill:#e53935,color:#fff
    style C2 fill:#e53935,color:#fff
    style C3 fill:#e53935,color:#fff

Diagram 5: Data Flow Overview

flowchart LR
    subgraph "Read Path"
        U1[User] -->|Search| GW1[API Gateway]
        GW1 -->|Query| ES[(Elasticsearch)]
        GW1 -->|Hotel details| CACHE[(Redis Cache)]
        CACHE -.->|Cache miss| DB1[(PostgreSQL)]
    end

    subgraph "Write Path"
        U2[User] -->|Reserve| GW2[API Gateway]
        GW2 -->|Create booking| RESV[Reservation Service]
        RESV -->|Check + Reserve| INV[Inventory Service]
        INV -->|UPDATE| DB2[(PostgreSQL)]
        RESV -->|Charge| PAY[Payment Service]
        PAY -->|API call| PSP[Stripe / VNPay]
    end

    subgraph "Async Path"
        DB2 -.->|CDC / Event| KAFKA[Kafka]
        KAFKA -.->|Update index| ES
        KAFKA -.->|Notification| NOTIFY[Email/SMS]
        KAFKA -.->|Analytics| DW[(Data Warehouse)]
    end

    style DB2 fill:#43a047,color:#fff
    style ES fill:#1e88e5,color:#fff
    style KAFKA fill:#ff6f00,color:#fff

Aha Moments & Pitfalls — Nhung dieu rut ra

Aha Moments

#InsightGiai thich
1DB constraint thuong la duKhong can implement lock phuc tap. CHECK (reserved <= total) + atomic UPDATE la du cho hau het truong hop. DB engine da duoc toi uu cho viec nay
2Overbooking la business decision, khong phai bugAirlines, hotels deu lam viec nay. Cau hinh overbooking percentage la feature, khong phai defect
3Inventory caching la nguy hiemCache stale inventory → overbooking hoac lost revenue. Inventory nen doc truc tiep tu DB voi proper indexing
4Idempotency ngan double chargeKhong co idempotency → client retry → 2 bookings + 2 charges. reservation_id la idempotency key tu nhien
5Two-phase reservation la bat buocPhai hold phong truoc khi payment. Khong hold → nguoi khac dat mat trong luc dang thanh toan
6Hold expiration la criticalKhong co hold expiration → “ghost bookings” chiem inventory mai mai. Background job release expired holds
7Queue la giai phap cho flash saleSerialize requests qua queue → xu ly tuan tu → khong concurrency issue. Trade-off: async UX
8Saga pattern cho distributed transactionReserve → Pay → Confirm. Moi buoc co compensating action. Khong dung 2PC vi blocking va fragile

Common Pitfalls

#PitfallHau quaCach tranh
1Cache inventory va hien thi nhu source of truthUser thay “con phong” nhung dat thi het → bad UX, mat uy tinDoc inventory tu DB cho availability check, chi cache hotel info
2Khong co hold expirationUser tao reservation nhung khong thanh toan → phong bi “giu” maiBackground job release PENDING reservations sau 10-15 phut
3Tin gia tu clientAttacker sua gia 5,000,000 VND → 500 VNDLuon tinh gia tren server, KHONG tin request body
4Khong co idempotency keyDouble booking, double charge khi client retryFrontend generate reservation_id truoc khi gui request
5Lock qua nhieu rows cung lucDeadlock khi 2 transactions lock cac rows theo thu tu khac nhauLock theo thu tu co dinh (sort by date), hoac dung optimistic locking
6Single point of failure o Inventory ServiceInventory Service die → toan bo booking dieMulti-instance + DB replication + circuit breaker
7Khong co Saga compensating actionPayment fail nhung inventory van bi holdMoi forward action phai co compensating action tuong ung
8Khong partition inventory table36.5M records → query chamPartition theo date (monthly), chi query tuong lai

Interview Tips

Cau hoi interviewer co the hoiCach tra loi
”Lam sao xu ly 1000 nguoi dat cung 1 phong?”Trinh bay 3 concurrency approaches, recommend DB constraint + queue cho flash sale
”Neu payment fail giua chung, lam gi?”Saga pattern voi compensating actions. Release inventory hold, notify user
”Overbooking thi sao?”La business decision, configurable. Giai thich effective_capacity formula
”Cache inventory duoc khong?”Giai thich tai sao nguy hiem, chi cache hotel/room info, khong cache real-time inventory
”Lam sao scale?”Stateless services horizontal scale. Inventory/DB la bottleneck → vertical scale + partitioning + read replicas

LinkLien quan
Tuan-07-Database-Sharding-ReplicationInventory table partitioning, DB replication cho read scalability
Tuan-11-Microservices-PatternSaga pattern, service decomposition, inter-service communication
Case-Design-Payment-SystemPayment flow chi tiet, PCI-DSS, idempotency pattern
Tuan-08-Message-QueueKafka cho async processing, queue-based reservation
Tuan-06-Cache-StrategyCache-aside pattern cho hotel data, tai sao khong cache inventory
Tuan-09-Rate-LimiterRate limiting chong scraping va booking bot
Tuan-14-AuthN-AuthZ-SecurityAuthentication, authorization cho admin va user
Tuan-15-Data-Security-EncryptionEncryption at rest/transit, PII protection
Tuan-02-Back-of-the-envelopeCapacity estimation methodology
Tuan-13-Monitoring-ObservabilityMonitoring, alerting, SLA tracking

Final takeaway: Hotel Reservation System la bai toan concurrency control tren shared inventory. Core problem khong phai scale (QPS thap), ma la accuracy — khong duoc ban qua so phong, khong duoc charge 2 lan, khong duoc mat booking. Ba ky thuat quan trong nhat: DB constraints (chong overbooking), Idempotency (chong double booking), va Saga pattern (chong inconsistency). Master 3 dieu nay, em co the giai quyet bat ky bai toan inventory nao — tu hotel den e-commerce den ticketing.