Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions docs/LEARNINGS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
# Learnings: Async Payment Migration & Transactional Safety

This document captures key technical insights from migrating the BankApp's synchronous payment flows to async patterns while maintaining transactional integrity.

---

## 1. Spring @Async Internals

### How Spring Proxies Async Methods

Spring's `@Async` works through AOP proxying. When a bean method is annotated with `@Async`, Spring wraps the bean in a proxy that intercepts calls and submits them to a `TaskExecutor` instead of executing on the caller's thread. The actual method runs on a thread from the configured executor pool.

**Critical gotcha — self-invocation doesn't work with @Async.** If `ServiceA.methodA()` calls `this.methodB()` where `methodB()` is `@Async`, the call bypasses the proxy and executes synchronously. This is because `this` refers to the raw bean, not the proxy. The solution is to inject the service into itself or extract async methods into a separate service (which is what we did with `TransactionLoggingService`).

### TaskExecutor Thread Pool Management

The `ThreadPoolTaskExecutor` configured in `AsyncConfig` manages a pool with:
- **Core pool size (5):** Threads kept alive even when idle
- **Max pool size (10):** Upper bound when queue is full
- **Queue capacity (25):** Buffered tasks before spawning beyond core

Thread naming via `setThreadNamePrefix("payment-async-")` is critical for debugging — it lets you trace in logs which operations are running asynchronously vs. synchronously. When we see log lines from the `payment-async-1` thread, we know the transaction logging is correctly offloaded.

---

## 2. @Transactional + @Async Interaction

### Why You Cannot Combine Both on the Same Method

Spring's `@Transactional` binds a transaction to the **current thread** via `ThreadLocal`. When `@Async` moves execution to a different thread, the transaction context does **not** propagate. This means:

```
@Transactional
@Async
public void doWork() {
// The @Transactional has NO effect here because @Async
// runs this on a new thread with no transaction context
repository.save(entity); // runs without transactional protection
}
```

If both annotations are on the same method, one of two things happens depending on proxy ordering:
1. If `@Async` is processed first, the method runs on a new thread without the caller's transaction
2. If `@Transactional` is processed first, it creates a transaction on the new async thread — but this is a **separate** transaction from the caller, defeating the purpose of atomicity

### The Pattern: Sync Writes + Async Audit

The correct architecture separates concerns:
- **Critical path (balance updates):** Synchronous + `@Transactional` in `AccountService`. The `deposit()`, `withdraw()`, and `transferAmount()` methods mutate balances and save accounts within a single transaction.
- **Audit trail (transaction logging):** Asynchronous in `TransactionLoggingService`. Creating `Transaction` records is non-critical and can be offloaded to the thread pool. If async logging fails, the balance is still correct.

This separation means a failed transaction log doesn't roll back a successful balance update, which is the correct business behavior for a banking application — the balance is the source of truth, and the audit trail is eventually consistent.

---

## 3. CompletableFuture Patterns

### Composing Async Results

`CompletableFuture` enables non-blocking composition:

```java
// Sequential composition
CompletableFuture<Transaction> result = logDepositAsync(account, amount)
.thenApply(tx -> { tx.setStatus(COMPLETED); return tx; });

// Parallel composition
CompletableFuture.allOf(
logTransferAsync(sender, amount, "Transfer Out"),
logTransferAsync(recipient, amount, "Transfer In")
).join();
```

### Exception Handling in Async Chains

Exceptions in `CompletableFuture.supplyAsync()` are wrapped in `CompletionException`. In the REST controller, we catch `RuntimeException` inside the supplier to return proper HTTP error responses:

```java
CompletableFuture.supplyAsync(() -> {
try {
accountService.withdraw(account, amount);
} catch (RuntimeException e) {
return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
}
return ResponseEntity.ok(response);
}, paymentTaskExecutor);
```

### Testing Async Code

Key testing insight: `@Transactional` test annotations don't work with async endpoints because the test transaction lives on the test thread, while the async handler runs on the executor thread (which can't see uncommitted data). The fix is to **not** use `@Transactional` on async integration tests and instead use explicit `@BeforeEach`/`@AfterEach` cleanup.

For MockMvc async tests, the pattern is:
```java
MvcResult result = mockMvc.perform(post("/api/deposit").param("amount", "500"))
.andExpect(request().asyncStarted())
.andReturn();

mockMvc.perform(asyncDispatch(result))
.andExpect(status().isOk())
.andExpect(jsonPath("$.newBalance").value(1500.00));
```

---

## 4. Race Conditions in Financial Systems

### The Lost Update Problem

Without `@Transactional`, the `transferAmount()` method performed 4 separate DB writes:
1. Debit sender account
2. Save sender
3. Credit recipient account
4. Save recipient

If two concurrent transfers happen simultaneously, both could read the same initial balance, compute new balances independently, and write back — causing one transfer to be "lost." This is the classic lost update anomaly.

### How @Transactional Prevents Lost Updates

Adding `@Transactional` wraps all 4 operations in a single database transaction. With the default isolation level (`READ_COMMITTED` on most databases), this provides:
- **Atomicity:** Either all 4 writes succeed or none do. If saving the recipient fails, the sender's debit is rolled back.
- **Row-level locking:** When Hibernate loads and modifies an account, the row is locked until the transaction commits, preventing concurrent modifications.

For higher-contention scenarios, you could escalate to `SERIALIZABLE` isolation or use optimistic locking with `@Version`, but `READ_COMMITTED` + `@Transactional` is sufficient for this application's concurrency profile.

### SecurityContext and Thread Boundaries

A subtle but critical finding: `SecurityContextHolder` stores the authentication context in a `ThreadLocal`. When using `CompletableFuture.supplyAsync()`, the async thread does **not** inherit the security context. The solution is to capture the username synchronously on the HTTP request thread and pass it as a closure variable to the async supplier:

```java
// Capture on request thread (has SecurityContext)
String username = SecurityContextHolder.getContext().getAuthentication().getName();

// Use captured value on async thread (no SecurityContext)
return CompletableFuture.supplyAsync(() -> {
Account account = accountService.findAccountByUsername(username);
// ...
}, paymentTaskExecutor);
```

### H2 Reserved Keywords

The entity name `Transaction` maps to a table name `transaction`, which is a SQL reserved keyword. H2 in test mode rejects this. Renaming the table via `@Table(name = "bank_transaction")` resolves the issue without affecting MySQL in production (where `transaction` may be quoted automatically by the dialect).
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@
<version>8.0.33</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand Down
24 changes: 24 additions & 0 deletions src/main/java/com/example/bankapp/config/AsyncConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.example.bankapp.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncConfig {

@Bean(name = "paymentTaskExecutor")
public Executor paymentTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.setThreadNamePrefix("payment-async-");
executor.initialize();
return executor;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authz -> authz
.requestMatchers("/register").permitAll()
.requestMatchers("/api/**").authenticated()
.anyRequest().authenticated()
)
.formLogin(form -> form
Expand Down
114 changes: 114 additions & 0 deletions src/main/java/com/example/bankapp/controller/BankRestController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package com.example.bankapp.controller;

import com.example.bankapp.model.Account;
import com.example.bankapp.model.Transaction;
import com.example.bankapp.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@RestController
@RequestMapping("/api")
public class BankRestController {

@Autowired
private AccountService accountService;

@Autowired
@Qualifier("paymentTaskExecutor")
private Executor paymentTaskExecutor;

@PostMapping("/deposit")
public CompletableFuture<ResponseEntity<Map<String, Object>>> deposit(@RequestParam BigDecimal amount) {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
return CompletableFuture.supplyAsync(() -> {
Account account = accountService.findAccountByUsername(username);

try {
accountService.deposit(account, amount);
} catch (RuntimeException e) {
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("error", e.getMessage());
return ResponseEntity.badRequest().body(errorResponse);
}

Account updated = accountService.findAccountByUsername(username);
Map<String, Object> response = new HashMap<>();
response.put("message", "Deposit successful");
response.put("newBalance", updated.getBalance());
response.put("amount", amount);
return ResponseEntity.ok(response);
}, paymentTaskExecutor);
Comment on lines +37 to +54
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Deposit REST endpoint missing exception handling unlike withdraw and transfer

The deposit() endpoint in BankRestController does not wrap the service call in a try-catch block, unlike withdraw() (line 56-61) and transfer() (line 80-86) which catch RuntimeException and return a proper 400 response with an error message. If accountService.deposit() throws any RuntimeException (e.g., a database constraint violation, or a negative amount causing downstream issues), the CompletableFuture completes exceptionally and Spring returns an opaque 500 error instead of a structured error response.

Suggested change
return CompletableFuture.supplyAsync(() -> {
Account account = accountService.findAccountByUsername(username);
accountService.deposit(account, amount);
Account updated = accountService.findAccountByUsername(username);
Map<String, Object> response = new HashMap<>();
response.put("message", "Deposit successful");
response.put("newBalance", updated.getBalance());
response.put("amount", amount);
return ResponseEntity.ok(response);
}, paymentTaskExecutor);
return CompletableFuture.supplyAsync(() -> {
Account account = accountService.findAccountByUsername(username);
try {
accountService.deposit(account, amount);
} catch (RuntimeException e) {
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("error", e.getMessage());
return ResponseEntity.badRequest().body(errorResponse);
}
Account updated = accountService.findAccountByUsername(username);
Map<String, Object> response = new HashMap<>();
response.put("message", "Deposit successful");
response.put("newBalance", updated.getBalance());
response.put("amount", amount);
return ResponseEntity.ok(response);
}, paymentTaskExecutor);
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1216a1e. Added try-catch around accountService.deposit() matching the pattern used in withdraw() and transfer() endpoints.

}

@PostMapping("/withdraw")
public CompletableFuture<ResponseEntity<Map<String, Object>>> withdraw(@RequestParam BigDecimal amount) {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
return CompletableFuture.supplyAsync(() -> {
Account account = accountService.findAccountByUsername(username);

try {
accountService.withdraw(account, amount);
} catch (RuntimeException e) {
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("error", e.getMessage());
return ResponseEntity.badRequest().body(errorResponse);
}

Account updated = accountService.findAccountByUsername(username);
Map<String, Object> response = new HashMap<>();
response.put("message", "Withdrawal successful");
response.put("newBalance", updated.getBalance());
response.put("amount", amount);
return ResponseEntity.ok(response);
}, paymentTaskExecutor);
}

@PostMapping("/transfer")
public CompletableFuture<ResponseEntity<Map<String, Object>>> transfer(
@RequestParam String toUsername, @RequestParam BigDecimal amount) {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
return CompletableFuture.supplyAsync(() -> {
Account fromAccount = accountService.findAccountByUsername(username);

try {
accountService.transferAmount(fromAccount, toUsername, amount);
} catch (RuntimeException e) {
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("error", e.getMessage());
return ResponseEntity.badRequest().body(errorResponse);
}

Account updated = accountService.findAccountByUsername(username);
Map<String, Object> response = new HashMap<>();
response.put("message", "Transfer successful");
response.put("newBalance", updated.getBalance());
response.put("amount", amount);
response.put("recipient", toUsername);
return ResponseEntity.ok(response);
}, paymentTaskExecutor);
}

@GetMapping("/transactions")
public CompletableFuture<ResponseEntity<List<Transaction>>> transactions() {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
return CompletableFuture.supplyAsync(() -> {
Account account = accountService.findAccountByUsername(username);
List<Transaction> history = accountService.getTransactionHistory(account);
return ResponseEntity.ok(history);
}, paymentTaskExecutor);
}
}
15 changes: 15 additions & 0 deletions src/main/java/com/example/bankapp/model/Transaction.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.example.bankapp.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;

@Entity
@Table(name = "bank_transaction")
public class Transaction {

@Id
Expand All @@ -14,8 +16,12 @@ public class Transaction {
private String type;
private LocalDateTime timestamp;

@Enumerated(EnumType.STRING)
private TransactionStatus status = TransactionStatus.PENDING;

@ManyToOne
@JoinColumn(name = "account_id")
@JsonIgnore
private Account account;

public Transaction() {
Expand All @@ -27,6 +33,7 @@ public Transaction(BigDecimal amount, String type, LocalDateTime timestamp, Acco
this.type = type;
this.timestamp = timestamp;
this.account = account;
this.status = TransactionStatus.PENDING;
}

public Long getId() {
Expand Down Expand Up @@ -68,4 +75,12 @@ public Account getAccount() {
public void setAccount(Account account) {
this.account = account;
}

public TransactionStatus getStatus() {
return status;
}

public void setStatus(TransactionStatus status) {
this.status = status;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.bankapp.model;

public enum TransactionStatus {
PENDING,
COMPLETED,
FAILED
}
Loading