DEV Community

JongHwa
JongHwa

Posted on

Part 1: Reliable Payment & Transaction

Intro

In e-commerce, the checkout process must be atomic. If one step fails, everything must roll back. Here is how I built a reliable payment system using Spring Boot.


1. The Core Workflow

When a user buys an item, three things must happen as a single unit:

  • Balance: Withdraw money from the wallet.
  • Stock: Decrease quantity. If 0, set status to SOLD_OUT.
  • Points:
    • Spend: Users decide the exact amount (Min 1).
    • Earn: Get 2.5% back from the final payment.

2. Implementation: @Transactional

I used Spring's transaction management to ensure Data Integrity. If the stock reduction fails, the money withdrawal is automatically canceled.

@Transactional
public void processOrder(OrderRequest request) {
    // 1. Validation (Check Sold Out)
    // 2. Point Usage & Balance Deduction
    // 3. Stock Reduction (Atomic)
    // 4. Point Accrual (2.5% Reward)
}
Enter fullscreen mode Exit fullscreen mode

3. Solving the "Logical Gap"

In Step 1, simple subtraction was enough. But in a real system, Concurrency is the enemy.

  • The Problem: If two users buy the last item at the same time, we might get "Negative Stock."

  • The Solution: I researched Database Locking to ensure only one process can update the stock at a time, preventing over-selling.


4. Failure Recovery

  • Validation First: Always check stock status before touching the balance.

  • Rollback: If an exception occurs during point accrual, the entire transaction is reverted by the @Transactional manager.


Conclusion

Data consistency is more important than speed in payments. Using @Transactional and strict validation is the first step toward a professional e-commerce backend.

Top comments (0)