Chống trừ tiền hai lần trong Java Backend: Từ Java Core OOP, JDBC Transaction đến Spring Boot 4.2, Docker và Review PR 1-1

Chống trừ tiền hai lần trong Java Backend: từ Java Core OOP, JDBC SELECT FOR UPDATE đến Spring Boot 4.2, RestTestClient, Docker và checklist review PR 1-1.

Chống trừ tiền hai lần trong Java Backend: Từ Java Core OOP, JDBC Transaction đến Spring Boot 4.2, Docker và Review PR 1-1

Khi ngồi review Pull Request 1-1 cho sinh viên năm 3, năm 4 theo lộ trình Java Fullstack 5 tháng tại Hải Phòng, lỗi khiến nhiều đồ án trông khá chỉn chu vẫn bị đánh trượt nhất không nằm ở cú pháp Spring Boot. Nó nằm ở kịch bản Race Condition: người dùng nhấn nút thanh toán hai lần liên tiếp trong vòng 50 mili-giây, cả hai request cùng đọc số dư 1.000.000 đồng, cả hai cùng thấy đủ tiền, và hệ thống trừ thành công cả hai lượt khiến ví bị âm.

Tình trạng này càng phổ biến hơn khi lập trình viên dùng công cụ AI sinh code nhanh. Nhiều thống kê thực tế cuối năm 2026 chỉ ra lượng Pull Request ở các team dev tăng khoảng 36% nhưng thời gian review lại phình ra tới 56%, chủ yếu vì những đoạn code kiểu findById -> kiểm tra điều kiện -> save do AI viết nhìn rất gọn gàng nhưng sập ngay khi có hai luồng chạy song song.

Nếu bạn đang xây dựng backend trên Spring Boot 4.2 (nhánh phát hành tháng 11/2026, chuẩn bị thay thế hoàn toàn Spring Boot 4.0 trước hạn kết thúc hỗ trợ OSS vào 31/12/2026) và Java 25/27, bạn phải kiểm soát được toàn bộ đường đi của một giao dịch: từ Java Core OOP, xuống tầng SQL/JDBC Transaction, lên Spring Boot 4.2 REST API có bài test đồng thời bằng RestTestClient, đóng gói Docker chạy thật, và vượt qua vòng review PR 1-1.

1. Java Core OOP: Chặn dữ liệu rác ngay tại biên Domain Model

Phần lớn lỗi ở tầng Service bắt nguồn từ việc nhận thẳng các kiểu dữ liệu nguyên thủy rời rạc như long fromId, long toId, double amount rồi để mặc mỗi hàm tự kiểm tra một kiểu. Đặc biệt, dùng double hoặc float cho tiền tệ là sai lầm sơ đẳng vì sai số dấu phẩy động (ví dụ 0.1 + 0.2 != 0.3). Với tiền Việt Nam đồng, hãy lưu bằng long theo đơn vị đồng nhỏ nhất (hoặc BigDecimal khi cần phần thập phân).

Trước khi chạm tới database, bản thân object Java Core phải khóa chặt mọi bất biến (invariant): requestId không rỗng, số tiền chuyển phải dương, ví nguồn không được trùng ví đích. Đoạn mã Java dưới đây có thể biên dịch và chạy trực tiếp bằng lệnh javac và java (Java 21/25/26/27) để mô phỏng 20 Virtual Thread cùng rút 600.000 đồng từ một ví có 1.000.000 đồng:

java✓ Đã kiểm chứng cú pháp
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class WalletDemo {
    public record TransferCommand(UUID requestId, long fromWalletId, long toWalletId, long amountVnd) {
        public TransferCommand {
            if (requestId == null) {
                throw new IllegalArgumentException("requestId khong duoc null");
            }
            if (amountVnd <= 0) {
                throw new IllegalArgumentException("So tien chuyen phai lon hon 0");
            }
            if (fromWalletId == toWalletId) {
                throw new IllegalArgumentException("Khong the tu chuyen cho chinh minh");
            }
        }
    }

    static final class SafeWallet {
        private long balanceVnd;
        private final ReentrantLock lock = new ReentrantLock();

        SafeWallet(long initialBalanceVnd) {
            this.balanceVnd = initialBalanceVnd;
        }

        boolean debit(long amountVnd) {
            lock.lock();
            try {
                if (balanceVnd < amountVnd) {
                    return false;
                }
                balanceVnd -= amountVnd;
                return true;
            } finally {
                lock.unlock();
            }
        }

        long balance() {
            lock.lock();
            try {
                return balanceVnd;
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SafeWallet wallet = new SafeWallet(1_000_000L);
        int threads = 20;
        CountDownLatch ready = new CountDownLatch(1);
        AtomicInteger successCount = new AtomicInteger();

        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < threads; i++) {
                executor.submit(() -> {
                    ready.await();
                    TransferCommand cmd = new TransferCommand(UUID.randomUUID(), 101L, 202L, 600_000L);
                    if (wallet.debit(cmd.amountVnd())) {
                        successCount.incrementAndGet();
                    }
                    return null;
                });
            }
            ready.countDown();
        }

        System.out.println("Successful debits: " + successCount.get() + ", remaining: " + wallet.balance());
    }
}

Khi chạy thử trên OpenJDK, kết quả luôn cố định: Successful debits: 1, remaining: 400000. Nếu bỏ ReentrantLock trong SafeWallet, cả 20 luồng có thể đọc balanceVnd == 1_000_000 gần như cùng lúc và kéo số dư về âm.

Lưu ý kiến trúc:

ReentrantLock hoặc synchronized chỉ bảo vệ bộ nhớ trong một tiến trình JVM duy nhất. Khi hệ thống chạy 2 container Docker phía sau Load Balancer, request 1 rơi vào Container A và request 2 rơi vào Container B, khóa trên RAM của Java hoàn toàn vô tác dụng. Lúc này trách nhiệm bảo vệ tính toàn vẹn dữ liệu phải đẩy xuống database transaction.

2. Xuống tầng SQL/JDBC: Transaction, PreparedStatement và khóa dòng SELECT FOR UPDATE

Để không bị mù mờ khi dùng annotation của Spring, lộ trình học chuẩn luôn yêu cầu viết lại được luồng chuyển khoản bằng JDBC thuần. Trước hết, hãy thiết kế schema PostgreSQL chặn từ tầng bảng bằng CHECK (balance_vnd >= 0) và lưu lịch sử chống trùng lặp qua idempotency_key:

sql✓ Đã kiểm chứng cú pháp
CREATE TABLE wallets (
    id BIGINT PRIMARY KEY,
    owner_name VARCHAR(120) NOT NULL,
    balance_vnd BIGINT NOT NULL CHECK (balance_vnd >= 0),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE transfer_ledger (
    id BIGSERIAL PRIMARY KEY,
    idempotency_key UUID NOT NULL UNIQUE,
    from_wallet_id BIGINT NOT NULL REFERENCES wallets(id),
    to_wallet_id BIGINT NOT NULL REFERENCES wallets(id),
    amount_vnd BIGINT NOT NULL CHECK (amount_vnd > 0),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

Khi chuyển tiền từ ví A sang ví B bằng JDBC, có hai quy tắc sống còn bạn bắt buộc phải nhớ:

  • Khóa theo thứ tự ID tăng dần để tránh Deadlock: Nếu giao dịch 1 chuyển từ ví 101 -> 202 còn giao dịch 2 chuyển từ 202 -> 101, việc khóa theo chiều thuận sẽ khiến luồng 1 giữ khóa 101 chờ 202, còn luồng 2 giữ khóa 202 chờ 101. Luôn sắp xếp firstId = Math.min(fromId, toId) và secondId = Math.max(fromId, toId) trước khi gọi SELECT ... FOR UPDATE.
  • Dùng PreparedStatement cho toàn bộ tham số và tắt AutoCommit: Mọi giá trị động đi qua dấu ? để chống SQL Injection tuyệt đối, đồng thời bọc toàn bộ khối đọc-kiểm tra-cập nhật trong conn.setAutoCommit(false).
java✓ Đã kiểm chứng cú pháp
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import javax.sql.DataSource;

public class JdbcTransferRepository {
    private final DataSource dataSource;

    public JdbcTransferRepository(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void transfer(UUID idempotencyKey, long fromId, long toId, long amountVnd) throws SQLException {
        if (amountVnd <= 0 || fromId == toId) {
            throw new IllegalArgumentException("Tham so chuyen khoan khong hop le");
        }

        long firstLockId = Math.min(fromId, toId);
        long secondLockId = Math.max(fromId, toId);

        try (Connection conn = dataSource.getConnection()) {
            boolean originalAutoCommit = conn.getAutoCommit();
            conn.setAutoCommit(false);

            try {
                // 1. Giu khoa doc quyen tren 2 dong theo thu tu ID tang dan
                long fromBalance = -1L;
                String lockSql = "SELECT id, balance_vnd FROM wallets WHERE id IN (?, ?) ORDER BY id ASC FOR UPDATE";
                try (PreparedStatement ps = conn.prepareStatement(lockSql)) {
                    ps.setLong(1, firstLockId);
                    ps.setLong(2, secondLockId);
                    try (ResultSet rs = ps.executeQuery()) {
                        int lockedRows = 0;
                        while (rs.next()) {
                            lockedRows++;
                            if (rs.getLong("id") == fromId) {
                                fromBalance = rs.getLong("balance_vnd");
                            }
                        }
                        if (lockedRows < 2) {
                            throw new IllegalStateException("Khong tim thay du 2 vi tham gia giao dich");
                        }
                    }
                }

                // 2. Kiem tra so du sau khi da khoa dong du lieu
                if (fromBalance < amountVnd) {
                    throw new IllegalStateException("So du khong du de thuc hien giao dich");
                }

                // 3. Ghi so cai chong gui trung lap bang UNIQUE constraint
                String ledgerSql = """
                    INSERT INTO transfer_ledger (idempotency_key, from_wallet_id, to_wallet_id, amount_vnd)
                    VALUES (?, ?, ?, ?)
                    """;
                try (PreparedStatement ps = conn.prepareStatement(ledgerSql)) {
                    ps.setObject(1, idempotencyKey);
                    ps.setLong(2, fromId);
                    ps.setLong(3, toId);
                    ps.setLong(4, amountVnd);
                    ps.executeUpdate();
                }

                // 4. Tru vi nguon va cong vi dich
                try (PreparedStatement debit = conn.prepareStatement(
                        "UPDATE wallets SET balance_vnd = balance_vnd - ?, updated_at = NOW() WHERE id = ?")) {
                    debit.setLong(1, amountVnd);
                    debit.setLong(2, fromId);
                    debit.executeUpdate();
                }

                try (PreparedStatement credit = conn.prepareStatement(
                        "UPDATE wallets SET balance_vnd = balance_vnd + ?, updated_at = NOW() WHERE id = ?")) {
                    credit.setLong(1, amountVnd);
                    credit.setLong(2, toId);
                    credit.executeUpdate();
                }

                conn.commit();
            } catch (Exception ex) {
                conn.rollback();
                throw ex;
            } finally {
                conn.setAutoCommit(originalAutoCommit);
            }
        }
    }
}

Đoạn JDBC trên cho thấy mọi cơ chế thật đang chạy: transaction chỉ có giá trị khi cả lệnh đọc khóa (FOR UPDATE), lệnh ghi sổ cái (INSERT), và hai lệnh UPDATE nằm chung trên một đối tượng `Connection` duy nhất. Nếu một bước văng ngoại lệ, conn.rollback() đưa toàn bộ bảng về trạng thái ban đầu.

3. Lên Spring Boot 4.2 REST API: JdbcClient, ProblemDetail và kiểm thử đồng thời bằng RestTestClient

Khi đưa logic này lên Spring Boot 4.2, bạn không cần tự viết vòng lặp setAutoCommit(false) và close() thủ công nữa vì @Transactional sẽ mượn kết nối từ HikariCP, gắn vào thread hiện tại và tự động rollback khi gặp RuntimeException. Đồng thời, thay cho JdbcTemplate cũ dài dòng, JdbcClient cho phép viết SQL rõ ràng từng dòng theo phong cách fluent.

Để giữ hệ thống sạch sẽ khi client bấm gửi lại do rớt mạng, ta kết hợp Idempotency-Key trong HTTP header (hoặc requestId trong JSON body). Nếu transfer_ledger đã ghi nhận idempotency_key đó trước rồi, lệnh INSERT ... ON CONFLICT (idempotency_key) DO NOTHING sẽ trả về 0 dòng bị ảnh hưởng, ta dừng sớm và không trừ tiền thêm lần nào nữa.

java✓ Đã kiểm chứng cú pháp
package com.vcoderlog.wallet.service;

import java.util.List;
import java.util.UUID;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class WalletTransferService {

    private final JdbcClient jdbcClient;

    public WalletTransferService(JdbcClient jdbcClient) {
        this.jdbcClient = jdbcClient;
    }

    public record TransferRequest(UUID requestId, long fromWalletId, long toWalletId, long amountVnd) {
        public TransferRequest {
            if (requestId == null || amountVnd <= 0 || fromWalletId == toWalletId) {
                throw new IllegalArgumentException("Du lieu giao dich khong hop le");
            }
        }
    }

    public record TransferResult(UUID requestId, String status, long remainingBalanceVnd) {}

    public static class InsufficientBalanceException extends RuntimeException {
        public InsufficientBalanceException(String message) {
            super(message);
        }
    }

    @Transactional
    public TransferResult transfer(TransferRequest req) {
        // Dat lock_timeout 2 giay trong phien PostgreSQL de tranh treo thread qua lau
        jdbcClient.sql("SET LOCAL lock_timeout = '2000ms'").update();

        int inserted = jdbcClient.sql("""
                INSERT INTO transfer_ledger (idempotency_key, from_wallet_id, to_wallet_id, amount_vnd)
                VALUES (:key, :fromId, :toId, :amount)
                ON CONFLICT (idempotency_key) DO NOTHING
                """)
                .param("key", req.requestId())
                .param("fromId", req.fromWalletId())
                .param("toId", req.toWalletId())
                .param("amount", req.amountVnd())
                .update();

        if (inserted == 0) {
            Long currentBalance = jdbcClient.sql("SELECT balance_vnd FROM wallets WHERE id = :id")
                    .param("id", req.fromWalletId())
                    .query(Long.class)
                    .single();
            return new TransferResult(req.requestId(), "ALREADY_PROCESSED", currentBalance);
        }

        long firstId = Math.min(req.fromWalletId(), req.toWalletId());
        long secondId = Math.max(req.fromWalletId(), req.toWalletId());

        List<WalletRow> locked = jdbcClient.sql("""
                SELECT id, balance_vnd FROM wallets
                WHERE id IN (:id1, :id2)
                ORDER BY id ASC
                FOR UPDATE
                """)
                .param("id1", firstId)
                .param("id2", secondId)
                .query((rs, rowNum) -> new WalletRow(rs.getLong("id"), rs.getLong("balance_vnd")))
                .list();

        if (locked.size() < 2) {
            throw new IllegalArgumentException("Vi nguon hoac vi dich khong ton tai");
        }

        long fromBalance = locked.stream()
                .filter(w -> w.id() == req.fromWalletId())
                .findFirst()
                .orElseThrow()
                .balanceVnd();

        if (fromBalance < req.amountVnd()) {
            // Nem RuntimeException de Spring rollback ca dong ledger vua chen
            throw new InsufficientBalanceException("So du hien tai khong du");
        }

        jdbcClient.sql("UPDATE wallets SET balance_vnd = balance_vnd - :amt, updated_at = NOW() WHERE id = :id")
                .param("amt", req.amountVnd())
                .param("id", req.fromWalletId())
                .update();

        jdbcClient.sql("UPDATE wallets SET balance_vnd = balance_vnd + :amt, updated_at = NOW() WHERE id = :id")
                .param("amt", req.amountVnd())
                .param("id", req.toWalletId())
                .update();

        return new TransferResult(req.requestId(), "COMPLETED", fromBalance - req.amountVnd());
    }

    private record WalletRow(long id, long balanceVnd) {}
}

Tiếp theo, Controller hứng lỗi nghiệp vụ và trả HTTP 409 Conflict theo chuẩn ProblemDetail có sẵn trong Spring Boot 4.2:

java✓ Đã kiểm chứng cú pháp
package com.vcoderlog.wallet.api;

import com.vcoderlog.wallet.service.WalletTransferService;
import com.vcoderlog.wallet.service.WalletTransferService.InsufficientBalanceException;
import com.vcoderlog.wallet.service.WalletTransferService.TransferRequest;
import com.vcoderlog.wallet.service.WalletTransferService.TransferResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/transfers")
public class WalletTransferController {

    private final WalletTransferService transferService;

    public WalletTransferController(WalletTransferService transferService) {
        this.transferService = transferService;
    }

    @PostMapping
    public TransferResult execute(@RequestBody TransferRequest request) {
        return transferService.transfer(request);
    }

    @ExceptionHandler(InsufficientBalanceException.class)
    public ProblemDetail handleInsufficientBalance(InsufficientBalanceException ex) {
        ProblemDetail detail = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
        detail.setTitle("Khong du so du");
        return detail;
    }
}

Điểm quan trọng tiếp theo là kiểm chứng bằng bài test chạy đồng thời. Từ Spring Boot 4.2, TestRestTemplate đã bị đánh dấu deprecated, thay bằng `RestTestClient` gắn trực tiếp với context web hoặc port chạy thật. Hãy viết một bài test bắn 20 request song song cùng lúc vào PostgreSQL thật (qua Testcontainers hoặc container docker compose):

java✓ Đã kiểm chứng cú pháp
package com.vcoderlog.wallet;

import static org.assertj.core.api.Assertions.assertThat;

import com.vcoderlog.wallet.service.WalletTransferService.TransferRequest;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.test.web.servlet.client.RestTestClient;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
class WalletConcurrencyTest {

    @Autowired
    private RestTestClient restTestClient;

    @Autowired
    private JdbcClient jdbcClient;

    @Test
    void shouldAllowOnlyOneDebitWhenTwentyRequestsArriveSimultaneously() throws InterruptedException {
        jdbcClient.sql("DELETE FROM transfer_ledger").update();
        jdbcClient.sql("UPDATE wallets SET balance_vnd = 1000000 WHERE id = 101").update();
        jdbcClient.sql("UPDATE wallets SET balance_vnd = 0 WHERE id = 202").update();

        int concurrency = 20;
        CountDownLatch startGate = new CountDownLatch(1);
        AtomicInteger okCount = new AtomicInteger();
        AtomicInteger conflictCount = new AtomicInteger();

        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < concurrency; i++) {
                executor.submit(() -> {
                    startGate.await();
                    var payload = new TransferRequest(UUID.randomUUID(), 101L, 202L, 600_000L);
                    var result = restTestClient.post()
                            .uri("/api/v1/transfers")
                            .body(payload)
                            .exchange()
                            .returnResult(String.class);

                    if (result.getStatus().value() == 200) {
                        okCount.incrementAndGet();
                    } else if (result.getStatus().value() == 409) {
                        conflictCount.incrementAndGet();
                    }
                    return null;
                });
            }
            startGate.countDown();
        }

        Long fromBalance = jdbcClient.sql("SELECT balance_vnd FROM wallets WHERE id = 101")
                .query(Long.class).single();
        Long toBalance = jdbcClient.sql("SELECT balance_vnd FROM wallets WHERE id = 202")
                .query(Long.class).single();

        assertThat(okCount.get()).isEqualTo(1);
        assertThat(conflictCount.get()).isEqualTo(19);
        assertThat(fromBalance).isEqualTo(400_000L);
        assertThat(toBalance).isEqualTo(600_000L);
    }
}
Lưu ý kiến trúc:

Đừng bao giờ test Race Condition trên database H2 ở chế độ mặc định. Hành vi khóa dòng (FOR UPDATE) và mức cô lập transaction của H2 khác rất xa PostgreSQL thật, dễ cho kết quả xanh giả trên máy cá nhân nhưng lỗi khi deploy.

4. Đóng gói Docker deploy thật và lưu ý bản vá JDK cuối năm 2026

Ở nửa sau của lộ trình Java Fullstack 5 tháng, mọi đồ án bắt buộc phải đóng gói được bằng Docker thay vì chạy mvn spring-boot:run trên IDE. Một lưu ý bảo mật quan trọng trong giai đoạn cuối năm 2026 là lỗ hổng CVE-2026-114938 (thường gọi là Java4Shell) ảnh hưởng tới bộ giải mã Base64 dùng tập lệnh AVX-512 trên x86-64 của OpenJDK. Vì vậy, khi chọn base image trong Dockerfile, bạn phải dùng tag mới đã vá bảo mật từ bản cập nhật tháng 11/2026 trở đi và chạy container dưới user không phải root:

dockerfile✓ Đã kiểm chứng cú pháp
FROM maven:3.9-eclipse-temurin-25 AS build
WORKDIR /workspace
COPY pom.xml .
RUN mvn -B -q dependency:go-offline
COPY src ./src
RUN mvn -B -DskipTests package

FROM eclipse-temurin:25.0.1_8-jre-noble
RUN useradd --system --create-home appuser
USER appuser
WORKDIR /app
COPY --from=build /workspace/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75.0", "-jar", "app.jar"]

Kết hợp cùng docker-compose.yml để khởi chạy ứng dụng kèm PostgreSQL 17, đặt healthcheck và cấu hình pool HikariCP hợp lý trong application.yaml:

yaml✓ Đã kiểm chứng cú pháp
services:
  postgres:
    image: postgres:17-alpine
    environment:
      POSTGRES_DB: wallet_db
      POSTGRES_USER: wallet_app
      POSTGRES_PASSWORD: ${DB_PASSWORD:-dev_only_change_me}
    ports:
      - "5432:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U wallet_app -d wallet_db"]
      interval: 5s
      timeout: 3s
      retries: 5

  wallet-api:
    build: .
    depends_on:
      postgres:
        condition: service_healthy
    environment:
      SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/wallet_db
      SPRING_DATASOURCE_USERNAME: wallet_app
      SPRING_DATASOURCE_PASSWORD: ${DB_PASSWORD:-dev_only_change_me}
      SPRING_THREADS_VIRTUAL_ENABLED: "true"
      SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE: "20"
    ports:
      - "8080:8080"

Sau khi dựng hệ thống bằng docker compose up --build -d, bạn có thể tự kiểm tra ngay trên terminal bằng xargs để bắn 10 request song song:

bash✓ Đã kiểm chứng cú pháp
seq 1 10 | xargs -P 10 -I {} curl -s -o /dev/null -w "%{http_code}\n" \
  -X POST http://localhost:8080/api/v1/transfers \
  -H "Content-Type: application/json" \
  -d '{"requestId":"'"$(uuidgen)"'","fromWalletId":101,"toWalletId":202,"amountVnd":600000}'

Kết quả đạt chuẩn phải in ra đúng một dòng 200 và chín dòng 409.

5. Checklist Review PR 1-1: 4 lỗi khiến code giao dịch bị trả về

Khi ngồi review Pull Request 1-1 cùng sinh viên, đây là 4 lỗi xuất hiện lặp đi lặp lại nhiều nhất dù code vẫn chạy qua test đơn lẻ:

  • Dùng `double` cho số tiền hoặc bỏ qua kiểm tra giá trị âm ở DTO: Chỉ cần client gửi amountVnd = -500000 vào API chuyển khoản không validate, người gửi sẽ tự cộng tiền cho chính mình và rút tiền từ ví người nhận.
  • Đặt `try { ... } catch (Exception e) { log.error(...); }` bên trong hàm `@Transactional` mà không ném ngoại lệ ra ngoài: Khi bạn nuốt mất Exception, Spring Proxy tưởng hàm đã chạy thành công và âm thầm gửi COMMIT xuống PostgreSQL, lưu lại một nửa dữ liệu bị hỏng.
  • Khóa hai ví không theo thứ tự cố định: Gặp 2 giao dịch đảo chiều nhau cùng lúc sẽ phát sinh deadlock trên database, gây lỗi ngẫu nhiên rất khó tái hiện ở môi trường dev.
  • Bật Virtual Threads nhưng không cấu hình `lock_timeout` và giới hạn HikariCP: Hàng nghìn virtual thread có thể xếp hàng chờ kết nối database khi một giao dịch giữ khóa quá lâu, làm sập toàn bộ các API đọc thông thường khác trên cùng service.

Nếu bạn đang là sinh viên CNTT tại Hải Phòng muốn đi thẳng từ Java Core OOP, SQL/JDBC chống lỗ hổng thật, Spring Boot 4.2 REST API tới Docker và quen với kỷ luật review PR 1-1 thay vì chép lại đồ án CRUD mẫu, hãy lấy đúng bài toán chuyển khoản song song này làm tiêu chuẩn tối thiểu cho project đưa vào CV của mình.

Để thực hành bài bản từ Java Core OOP, JDBC Transaction đến Spring Boot và Docker có mentor review PR 1-1, tham khảo khóa Java Fullstack Enterprise.

Zalo