Sobes.tech
Senior

The client clicked 'Withdraw funds' twice. How to prevent double deduction at the microservice and Kafka level?

sobes.tech AI

Answer from AI

To prevent double charging when the "Withdraw Funds" button is pressed again at the microservice and Kafka level, the following approaches can be used:

  1. Idempotency of operations
  • Assign a unique identifier (e.g., UUID or transaction business ID) to each withdrawal request.
  • The microservice checks whether an operation with this ID has already been processed, and if so, ignores the repeated request.
  1. Storing transaction state
  • The status of each operation (e.g., "processing", "successful", "cancelled") is stored in the database.
  • On a repeated request, the status is checked to avoid re-initiating the withdrawal.
  1. Message processing in Kafka
  • Use the message key equal to the unique operation ID to ensure order and idempotency during processing.
  • Implement logic in the consumer to check and update the transaction status atomically (e.g., through database transactions).
  1. Transactions and locks
  • Use locking mechanisms or transactions during request processing to prevent race conditions.

An example of simplified Java logic:

public void processWithdrawal(String operationId, BigDecimal amount) {
    if (transactionExists(operationId)) {
        return; // already processed
    }
    beginTransaction();
    try {
        reserveFunds(amount);
        saveTransaction(operationId, amount, "SUCCESS");
        commitTransaction();
    } catch (Exception e) {
        rollbackTransaction();
        throw e;
    }
}

Thus, the unique operation identifier and its status check are key to preventing double charges on repeated requests and message reprocessing from Kafka.