Pull Request #7231
Add idempotent payment retry handling
Prevents duplicate charges on merchant retries by checking an idempotency key before processing each payment. Returns a cached result for duplicate requests.
Ready to merge
service/PaymentService.java+44 additions
Viewed1
@Service
2
public class PaymentService {
3
@Autowired private IdempotencyRepository idempotencyRepo;
4
@Autowired private PaymentGateway gateway;
5
@Autowired private PaymentRepository paymentRepo;
7
+ public PaymentResult processPayment(
8
+ PaymentRequest request, String idempotencyKey) {
9
+
10
+ // Return cached result if we've seen this key
11
+ Optional<IdempotencyRecord> existing =
12
+ idempotencyRepo.findByKey(idempotencyKey);
13
+
14
+ if (existing.isPresent()) {
15
+ return existing.get().getCachedResult();
16
+ }
17
+
18
+ // Process the payment
19
+ Payment payment = new Payment(
20
+ request.getAmount(),
21
+ request.getCurrency(),
22
+ request.getCustomerId()
23
+ );
24
+ PaymentResult result = gateway.charge(payment);
25
+
26
+ // Save the idempotency record
27
+ IdempotencyRecord record = new IdempotencyRecord(
28
+ idempotencyKey, result
29
+ );
30
+ idempotencyRepo.save(record);
31
+
32
+ return result;
33
+ }
34
+ }
SL
samir_lead
Approved review
The flow is correct โ check key, return cached result, otherwise process and cache. Clean implementation of the idempotency pattern. LGTM.