jeudi 12 octobre 2023

Overlapping reservations in hotel with variable number of rooms

So I am creating a MERN app where people can book a room in a hotel for a given date range. So the schema looks like this

Table Hotel {
  id: bigint,
  numberOfRooms: int,
}

Table Room {
  id: bigint,
  hotelId: bigint,
}

Table Booking {
  id: bigint,
  hotelId: bigint,
  roomId: bigint,
  checkIn: Date,
  checkOut: Date
}

Now the javascript code that I wrote is

async function bookRoomInHotel(hotelId, from_date, to_date) {
  const availableRooms = await findAvailableRooms(hotelId, from_date, to_date);
  if (!availableRooms) {
    throw new Error('No room available');
  }

  const bookRoom = availableRooms[0];

  const booking = await createBooking(bookRoom._id, from_date, to_date, hotelId);

  return booking;
}

Now because of the nature of how Javascript handles promises, it can be seen that 2 different users making a resevation for overlapping date range can result in confirming booking for the same room. And in other cases, it is possible that there are more confirmed bookings in a hotel than the available rooms.

Solutions I found:

  1. Use a bull queue to handle booking requests one by one. Cons: Reservations for different hotels will get delayed and too many queue jobs when there are many users.
  2. Row lock the hotel. Cons: High chances of dead locks
  3. Fetch list of all available rooms in the hotel and try booking them one by one. The booking table will have a constraint for avoiding overlapping dates like shown here. Cons: First come, first serve basis will not be followed as responses from database may come in different orders. Deadlocks may arise (as said in the comments in the link).
  4. Distributed locks can be used. Cons: First come, first serve basis will be not followed again as client request will be rejected if lock is already acquired and the waiting clients will keep retrying to get the lock.

How should I design my backend if I want to successfullt implement anything near as good as Airbnb and other websites.

Aucun commentaire:

Enregistrer un commentaire