Prevent Multiple Users from Booking the Same Table at the Same Time in Django

I have a Booking model where users can book a restaurant table for a specific date and time. However, I want to ensure that multiple users cannot book the same table at the same time. Here’s my model:

class Booking(TimeStampWithCreatorModel, TerminalMixin, SoftDeletableModel):
    table = models.ManyToManyField(RestaurantTable, related_name="booking_table")
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="booking_customer")
    no_of_people = models.IntegerField()
    booking_date = models.DateField()
    booking_time = models.TimeField(null=True, blank=True)
    note = models.TextField(blank=True)
    accept_terms_and_conditions = models.BooleanField(default=False)
    receive_emails = models.BooleanField(default=False)

    class Meta:
        ordering = ("-created",)

What I've Tried I attempted to use select_for_update to lock the rows while making a booking, but when multiple users try to book the same table at the exact same time, duplicate bookings are still created in some instances.

Here’s the approach I used:

from django.db import transaction

def create_booking(customer, table_ids, booking_date, booking_time, no_of_people):
    with transaction.atomic():
        tables = RestaurantTable.objects.filter(id__in=table_ids).select_for_update()

        if Booking.objects.filter(table__in=tables, booking_date=booking_date, booking_time=booking_time).exists():
            raise ValueError("Table already booked for this time slot.")

        booking = Booking.objects.create(
            customer=customer,
            no_of_people=no_of_people,
            booking_date=booking_date,
            booking_time=booking_time
        )
        booking.table.set(tables)

        return booking

The Problem Despite using select_for_update, when multiple instances try to book at the same time, the check Booking.objects.filter(...) does not prevent race conditions properly. I assume this happens because Django’s ManyToManyField does not lock relationships the same way ForeignKey does.

Expected Outcome Prevent multiple users from booking the same table for the same date and time. Ensure that transactions handle concurrency properly without race conditions. Questions How can I ensure that bookings are atomic and prevent duplicate bookings at the same time slot? Is there a better approach, such as database-level constraints or using F() expressions? Should I implement a custom database constraint to enforce uniqueness for table + date + time? Would really appreciate any suggestions or best practices! 🚀

You can use the Serializable isolation level in your transactions. Ex) Two threads, T1 and T2, are trying to book the same table at the same time. T2 is blocked as soon as it tries to perform any operation (whether read or write) that conflicts with T1’s ongoing transaction.

Вернуться на верх