Booking System admitting Overbooking
In the previous article, I described how you could build a booking service using pessimistic locks. Its key feature was that it did not allow overbooking.
Nevertheless, there are cases when overbooking is expected. For example, when booking a hotel room. Clients often cancel these reservations, so overbooking can help reduce the chance of idle rooms. And if suddenly no one canceled the reservation, the hotel can usually accommodate the guest in a better room.
Overbooking model
Let’s say we have 10 standard apartments and 10 deluxe suites. In this case, guests who booked standard rooms can be accommodated in a deluxe suite. It will be more profitable than if the room was just idle. Also suppose, we know that 15% of bookings are usually canceled.
First, we need to decide how many rooms of which type we are ready to allow booking — for example, 15 standard and 11 deluxe suites. In the real world, such a distribution, most likely, will be set by a Machine Learning model, taking into account how much in advance customers book rooms, profit maximization, and other parameters.
Implementation
Now solving the problem becomes very similar to booking without overbooking, including locks taking.
The algorithm can be like this:
- Acquire a lock to the hotel (with a maximum expiration time of 15–20 seconds) using
lock_until
column. - Get all active orders for the hotel in the customer’s date range using
period_start
andperiod_end
. - Check if the order fits into our limits based on the overbooking model.
- Create an order which will expect payment within 5 minutes.
- Release lock to the hotel.
If the payment has not been made in 5 minutes, the order status will be changed to expired.
You do not need to take locks to search which hotels are available for the selected dates.
Multiple feeds
The task may be complicated by the fact that users can book apartments in different systems. Let’s say someone is on our aggregation service, and someone is directly on the hotel website.
We cannot use distributed transactions when a third party system is involved in the process. Therefore, synchronization conflicts are inevitable. We should remember about it and the situation should be handled according to business requirements. For example, by accepting that the actual overbooking after synchronization may be greater than in the given model, and let the hotels handle it themselves. Or by adjusting overbooking limits to potential synchronization conflicts.