Sobes.tech
Middle

Bookstore: a customer puts a book in the cart and clicks 'Buy'. How to guarantee that only one order is created when clicking multiple times? What method will we use to create the order and what parameters will we pass?

sobes.tech AI

Answer from AI

To guarantee that only one order is created when the "Buy" button is pressed multiple times, it is necessary to implement idempotency of the order creation operation.

Main approaches:

  • Block the button on the client after the first click, but this is not reliable.
  • Use a unique session or cart identifier on the server and check if an order has already been created for this cart.
  • Use a transaction and check for the existence of an order with the same identifier.

The order creation method usually looks something like createOrder(cartId, userId, paymentDetails).

Parameters:

  • cartId — a unique identifier for the cart or session to check if an order has already been created.
  • userId — the buyer's identifier.
  • paymentDetails — payment data.

Example in pseudocode:

public Order createOrder(String cartId, String userId, PaymentDetails payment) {
    // Check if an order already exists for this cart
    Order existingOrder = orderRepository.findByCartId(cartId);
    if (existingOrder != null) {
        return existingOrder; // Return the existing order
    }
    // Create a new order
    Order order = new Order(userId, cartId, payment);
    orderRepository.save(order);
    return order;
}

Thus, repeated clicks will not lead to duplicate creation.

Bookstore: a customer puts a book in the cart and… - sobes.tech