Build a service that processes financial transactions (like payments) with the following requirements:
Core Requirements:
- Idempotency: The same transaction should not be processed multiple times, even if the request is sent multiple times
- Double-charging prevention: Ensure a customer is never charged twice for the same transaction
- Transaction states: Track transaction lifecycle (PENDING → SUCCESS/FAILED)
- Concurrent request handling: Handle multiple simultaneous requests safely
Features to implement:
processTransaction(Transaction txn) - Process a new transaction
getTransactionStatus(String txnId) - Get status of a transaction
cancelTransaction(String txnId) - Cancel a pending transaction (optional)
Key considerations:
- Use idempotency keys (unique transaction IDs)
- Handle race conditions when same transaction is submitted concurrently
- Implement proper locking/synchronization
- Handle different failure scenarios
Go ahead and code your solution in Java
- Idempotency implementation
- Thread safety
- Design patterns used
- Edge case handling