| `isRetry` | `Boolean` | Yes | Flag indicating if this is a retry of a previous request. Note: This flag is excluded from transaction identity comparison. |
**Example Request**:
```json
{
"accountId":"ACC-12345",
"amount":20.00,
"sequenceKey":101,
"isRetry":false
}
```
## Response Structure
**Status Codes**:
-`200 OK`: Terminal business outcomes (`SUCCESS`, `INSUFFICIENT_FUNDS`). Original results are replayed for retries.
-`400 Bad Request`: Malformed JSON, invalid request structure, or validation failure (`INVALID_AMOUNT`, `INVALID_SEQUENCE_KEY`). These are terminal and should not be retried.
-`404 Not Found`: `INVALID_ACCOUNT`. This is terminal.
-`409 Conflict`: `STALE_KEY` or `CONFLICTING_TRANSACTION`. These are terminal.
-`5xx Server Error`: Transient server or database failures. These responses trigger retries according to the client retry policy.
**Recovery & Timeouts**:
- Transport timeouts or lost connections produce an `UNKNOWN_OUTCOME` client-side state. This is not a committed server transaction outcome.
- All recovery attempts must reuse the original transaction identity (`accountId`, `amount`, `sequenceKey`).
**Response Body**:
| Field | Type | Description |
|-------|------|-------------|
| `status` | `String` | The outcome of the transaction. |
| `balance` | `BigDecimal` | The remaining balance after processing. Absent or `null` if no valid account balance is available. |
| `message` | `String` | Human-readable explanation of the result.
**Outcome Values (`status`)**:
-`SUCCESS`: Withdrawal completed.
-`INSUFFICIENT_FUNDS`: Balance too low.
-`CONFLICTING_TRANSACTION`: Sequence key reused with different data.
-`STALE_KEY`: Sequence key is not monotonically increasing.
-`INVALID_AMOUNT`: Amount must be positive.
-`INVALID_SEQUENCE_KEY`: Sequence key must be positive. This outcome is not persisted in the transaction ledger.
# Data Model: Fault-Tolerant Distributed Banking Transaction
## Entities
### 1. Account
Represents a bank account with a balance and the last processed transaction marker.
| Attribute | Type | Constraints | Description |
|-----------|------|-------------|-------------|
| `account_id` | `String` | Primary Key, Not Null | Unique identifier for the account. |
| `balance` | `BigDecimal` | Not Null, $\ge 0$ | Current available funds. |
| `last_processed_seq_key` | `Long` | Not Null, $\ge 0$ | The highest sequence key successfully processed or rejected for this account. Initial value for new accounts is 0. |
### 2. TransactionLedger
Durable record of terminal transaction outcomes to ensure idempotency.
**Input**: Feature specification from `/specs/001-fault-tolerant-banking-transaction/spec.md`
## Summary
The goal is to implement a distributed banking system that guarantees effectively-once financial transaction outcomes for withdrawals, despite network failures, server crashes, and client retries. The solution uses a client-server architecture communicating via HTTP/JSON, with a server-side persistent transaction ledger in an H2 database to enforce idempotency through monotonically increasing sequence keys. Atomicity is guaranteed via database transactions and row-level locking to prevent race conditions during concurrent requests.
## Technical Context
**Language/Version**: Java 27
**Primary Dependencies**:
- Apache Maven (Build System)
- Jackson (JSON Processing)
- JUnit 5 & Mockito (Testing)
- JDK built-in `HttpServer` (HTTP Server)
**Storage**: Embedded H2 Database (Persistent file-based storage) accessed via JDBC.
**JDBC Transaction Strategy**:
- Begin one JDBC transaction.
-`connection.setAutoCommit(false)`.
- Account row locking using `SELECT ... FOR UPDATE`.
- If the account does not exist, return `INVALID_ACCOUNT` without inserting a ledger record.
- Search the transaction ledger using `(account_id, sequence_key)`.
- If found, compare the original transaction data and return the stored result or `CONFLICTING_TRANSACTION`.
- If not found, validate the sequence key against `last_processed_seq_key`.
- Validate the transaction amount.
- Check available balance.
- Update balance when applicable.
- Update `last_processed_seq_key`.
- Insert the terminal transaction outcome.
-`COMMIT` only after all required operations succeed; `ROLLBACK` on any failure.
- Connections and statements closed safely in `finally` blocks.
**Testing**: JUnit 5, Mockito, and a custom Fault Injection framework.
**Target Platform**: Cross-platform (Windows and WSL).
**Structure Decision**: A single Maven project structure is selected, separating the Client and Server into distinct packages under `com.banking`. The `fault` and `config` packages are siblings. This maintains a clear separation of concerns while sharing the `models` package for the communication contract (DTOs). The project includes a standard `pom.xml` and `src/main/resources` for database configuration.
-**Expected**: Original `SUCCESS` result is returned.
-**Verification**: Balance remains `$75.00`.
## Fault Injection Tests (FR-019)
Enable the `FaultInjector` in the server configuration to verify:
-**Request Delivery Failure**: Simulate failure before request reaches server $\rightarrow$ Client retries $\rightarrow$ Server processes as new transaction.
-**Server Crash (Pre-Commit)**: Use separate process to crash server before DB commit $\rightarrow$ Client retries $\rightarrow$ Server processes as new transaction.
-**Response Loss (Post-Commit)**: Server commits DB but fails to send HTTP response $\rightarrow$ Client retries $\rightarrow$ Server returns original stored result.
-**Response Timeout**: Server delays response beyond client timeout $\rightarrow$ Client retries $\rightarrow$ Server returns original stored result.
-**Decision**: Use `SELECT ... FOR UPDATE` (Pessimistic Locking) on the `Account` row at the start of the transaction.
-**Rationale**: To prevent race conditions during concurrent requests for the same account, we must ensure that only one thread can read the balance and update the sequence key at a time. Row-level locking in H2 prevents "lost updates" and ensures that the sequence key check and balance update are atomic relative to other requests for the same account.
-**Concurrency Note**: `SELECT FOR UPDATE` serializes modifications to the same account but does not automatically guarantee that requests are acquired in ascending sequence-key order. If a higher key is committed first, a subsequent request with a lower key must be rejected as stale.
-**Alternatives Considered**: Optimistic locking (versioning). Rejected because high-contention on a single account could lead to excessive retries/failures; pessimistic locking is safer for financial state transitions in this simulation.
### 2. Idempotency Logic Implementation
-**Decision**: Implement a strict check order:
1. Begin one JDBC transaction and disable AutoCommit.
2. Find and lock the existing account row using `SELECT ... FOR UPDATE`.
3. If the account does not exist, return `INVALID_ACCOUNT` without inserting a ledger record.
4. Search the transaction ledger using `(accountId, sequenceKey)`.
5. If found, compare original transaction data (amount) using exact decimal comparison (ignoring scale).
6. If not found, validate `sequenceKey` against `Account.last_processed_seq_key`.
7. Validate the transaction amount (must be positive).
8. Check available balance.
9. Update balance when applicable.
10. Update `last_processed_seq_key`.
11. Insert the terminal transaction outcome (only `SUCCESS` or `INSUFFICIENT_FUNDS`) into the ledger.
12. Commit.
13. Rollback on any failure.
-**Rationale**: This ensures a consistent, race-condition-free execution flow that strictly adheres to functional requirements (FR-006, FR-007, FR-016) and prevents ledger pollution by request validation errors.
### 3. Fault Injection Mechanism
-**Decision**: Use a `FaultInjector` component that the `RequestHandler` calls before and after the `TransactionService` execution. Fault injection must be disabled by default and explicitly enabled via configuration for testing.
-**Fault-to-Component Mapping**:
-**Request Delivery Failure**: Simulate client-side failure before the request reaches the server (e.g., network timeout or dropped packet).
-**Server Failure before Execution**: Use a separate server process for actual process-crash integration testing. Never call `System.exit()` inside the Maven test JVM.
-**Response Loss (Post-Commit)**: Simulated in `RequestHandler` by ensuring the database transaction has committed, then closing the HTTP exchange without sending a response.
-**Response Delay (Timeout)**: Simulated in `RequestHandler` by ensuring the database transaction has committed, then calling `Thread.sleep()` beyond the client's configured timeout.
-**Rationale**: Placing the injector in the `RequestHandler` allows it to intercept the flow at the exact boundaries required to simulate network and server-level failures, ensuring we test the system's ability to recover from "unknown outcomes."
### 4. Client Retry Strategy
-**Decision**: Implement a `RetryHandler` using a `ScheduledExecutorService` for exponential backoff.
-**Rationale**: Prevents the "thundering herd" problem and gives the server time to recover from crashes.
-**Backoff Formula**: $delay = base \times 2^{retry\_count}$ (with a maximum cap).
### 5. Cross-Platform Storage
-**Decision**: Configure H2 with a relative path (e.g., `./data/banking_db`) in the JDBC connection string.
-**Rationale**: Ensures that the project runs seamlessly on both Windows (IntelliJ) and WSL without hardcoded absolute paths.
## Summary of Resolved Clarifications
-**Race Condition Prevention**: Solved via JDBC `FOR UPDATE` locking on accounts.
-**Idempotency Order**: Strictly defined as Ledger Search $\rightarrow$ Sequence Key Validation $\rightarrow$ Execution.
-**Fault Simulation**: Mapped to specific intercept points in the `RequestHandler`.
-**Monetary Precision**: `BigDecimal` confirmed for all fields.