Commit d748160b authored by Shouib's avatar Shouib

docs: finalize banking architecture and design

parent 2eb567ae
# API Contract: Banking Transaction API
## Communication Protocol
- **Transport**: HTTP/1.1
- **Format**: JSON
- **Method**: `POST /withdraw`
## Request Structure
**Endpoint**: `/withdraw`
**Content-Type**: `application/json`
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `accountId` | `String` | Yes | Unique identifier of the bank account. |
| `amount` | `BigDecimal` | Yes | The amount to withdraw. Must be positive. |
| `sequenceKey` | `Long` | Yes | Positive numeric value, monotonically increasing for idempotency. |
| `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.
- `INVALID_ACCOUNT`: Account not found.
**Example Success Response**:
```json
{
"status": "SUCCESS",
"balance": 80.00,
"message": "Withdrawal successful"
}
```
**Example Rejection Response**:
```json
{
"status": "INSUFFICIENT_FUNDS",
"balance": 50.00,
"message": "Insufficient funds for withdrawal"
}
```
# 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.
| Attribute | Type | Constraints | Description |
|-----------|------|-------------|-------------|
| `id` | `Long` | Primary Key, Auto-increment | Internal ledger ID. |
| `account_id` | `String` | Not Null, Foreign Key to Account | The account associated with the transaction. |
| `sequence_key` | `Long` | Not Null | The client-provided sequence key. |
| `amount` | `BigDecimal` | Not Null | The requested withdrawal amount. |
| `outcome` | `String` | Not Null | Result: `SUCCESS`, `INSUFFICIENT_FUNDS`. |
| `balance_after` | `BigDecimal` | Not Null | The account balance immediately after the transaction was processed. |
| `response_message` | `String` | Not Null | The original response message sent to the client. |
| `timestamp` | `Timestamp` | Not Null | When the transaction was recorded. |
**Constraints**:
- Composite Unique Constraint: `(account_id, sequence_key)` ensures a sequence key is only persisted once per account.
## State Transitions
### Transaction Processing Flow
1. **Database Initialization**:
- Begin JDBC transaction.
- Disable `autoCommit`.
2. **Concurrency Control**:
- Lock account using `SELECT FOR UPDATE` based on `accountId`.
3. **Validation**:
- **Account Existence**: If `Account` not found $\rightarrow$ Rollback and return `INVALID_ACCOUNT`.
- **Idempotency Check**: Search `TransactionLedger` for `(accountId, sequenceKey)`.
- **Match found** $\rightarrow$ Compare `amount`.
- Exact match $\rightarrow$ Return original `outcome`, `balance_after`, and `response_message`.
- Mismatch $\rightarrow$ Rollback and return `CONFLICTING_TRANSACTION`.
- **Sequence Key Validation**:
- If `sequenceKey <= 0` $\rightarrow$ Rollback and return `INVALID_SEQUENCE_KEY`.
- Compare `sequenceKey` with `Account.last_processed_seq_key`.
- If `sequenceKey <= last_processed_seq_key` $\rightarrow$ Rollback and return `STALE_KEY`.
- **Amount Validation**: If `amount <= 0` $\rightarrow$ Rollback and return `INVALID_AMOUNT`.
- **Funds Validation**: If `balance < amount` $\rightarrow$ Process as `INSUFFICIENT_FUNDS`.
4. **Execution & Persistence**:
- If `SUCCESS`: Deduct `amount` from `balance`.
- Update `Account.last_processed_seq_key = sequenceKey`.
- Insert entry into `TransactionLedger` with `outcome` (`SUCCESS` or `INSUFFICIENT_FUNDS`), `balance_after`, and `response_message`.
5. **Completion**:
- **Commit**: Persist all changes atomically.
- **Failure**: If any exception occurs during the process $\rightarrow$ Rollback.
# Implementation Plan: Fault-Tolerant Distributed Banking Transaction
**Branch**: `001-fault-tolerant-banking-transaction` | **Date**: 2026-11-02 | **Spec**: [specs/001-fault-tolerant-banking-transaction/spec.md](specs/001-fault-tolerant-banking-transaction/spec.md)
**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).
**Project Type**: Client-Server Application.
**Performance Goals**:
- Guaranteed financial consistency (Correctness > Throughput).
- Support for concurrent requests for independent accounts.
**Constraints**:
- No negative account balances.
- No duplicate withdrawals (Effectively-once execution).
- Persistence across server restarts.
- Bounded retries with exponential backoff on the client.
**Scale/Scope**: Simulation environment with multiple independent bank accounts.
## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
| Principle | Requirement | Status | Verification/Justification |
|-----------|-------------|--------|---------------------------|
| I. Effectively-Once | Prevent duplicate deductions | PASS | Enforced by sequence keys and durable transaction ledger. |
| II. Atomic Transitions | Atomic balance/key/ledger updates | PASS | All state changes wrapped in a single JDBC transaction. |
| III. Deterministic Fault Tolerance | Handle retries/timeouts/crashes | PASS | Client retry logic and server-side fault injection. |
| IV. Monetary Precision | No float/double for money | PASS | `BigDecimal` used for all financial calculations. |
| V. SDD | Specification-driven | PASS | Following Spec Kit workflow. |
## Project Structure
### Documentation (this feature)
```text
specs/001-fault-tolerant-banking-transaction/
├── plan.md # This file
├── research.md # Phase 0 output
├── data-model.md # Phase 1 output
├── quickstart.md # Phase 1 output
├── contracts/ # Phase 1 output (API definitions)
└── tasks.md # Phase 2 output
```
### Source Code (repository root)
```text
pom.xml
src/
├── main/
│ ├── java/
│ │ └── com/banking/
│ │ ├── client/ # Banking Client implementation
│ │ │ ├── BankingClient.java
│ │ │ └── RetryHandler.java
│ │ ├── server/ # Banking Server implementation
│ │ │ ├── HttpServerApp.java
│ │ │ ├── RequestHandler.java
│ │ │ └── ValidationService.java
│ │ ├── service/ # Business Logic
│ │ │ ├── TransactionService.java
│ │ │ ├── AccountService.java
│ │ │ └── IdempotencyManager.java
│ │ ├── persistence/ # Data Access Layer
│ │ │ ├── DatabaseManager.java
│ │ │ ├── AccountRepository.java
│ │ │ └── TransactionLedgerRepository.java
│ │ ├── models/ # Shared Entities & DTOs
│ │ │ ├── Account.java
│ │ │ ├── Transaction.java
│ │ │ ├── RequestDTO.java
│ │ │ └── ResponseDTO.java
│ │ ├── fault/ # Fault Simulation
│ │ │ └── FaultInjector.java
│ │ └── config/ # Application Configuration
│ │ └── AppConfig.java
│ └── resources/ # Config files (e.g., db.properties)
└── test/
└── java/
└── com/banking/
├── unit/
├── integration/
├── concurrency/
└── fault/ # Fault injection verification tests
```
**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.
## Complexity Tracking
No violations of the constitution identified.
# Quickstart Validation Guide: Fault-Tolerant Banking Transaction
This guide provides the scenarios required to validate that the implementation satisfies the functional requirements (FR-001 through FR-019).
## Setup
1. **Build**: `mvn clean compile`
2. **Run Server**: Start the `HttpServerApp`.
3. **Initialize Data**: Ensure at least one account exists in the H2 database (e.g., `ACC-100` with `$100`).
## Validation Scenarios
### 1. Happy Path (FR-001, FR-002, FR-017)
- **Setup**: New account `ACC-100` with `$100`.
- **Action**: Submit `withdraw(accountId="ACC-100", amount=20, sequenceKey=10)`.
- **Expected**: Response `SUCCESS`, balance `$80`.
### 2. Insufficient Funds (FR-017)
- **Setup**: New account `ACC-200` with `$50`.
- **Action**: Submit `withdraw(accountId="ACC-200", amount=200, sequenceKey=20)`.
- **Expected**: Response `INSUFFICIENT_FUNDS`, balance `$50`. Sequence key 20 is advanced and result persisted.
### 3. Idempotency: Duplicate Request (FR-006)
- **Setup**: New account `ACC-300` with `$100`.
- **Action**:
1. Submit `withdraw(accountId="ACC-300", amount=20, sequenceKey=10)`.
2. Submit `withdraw(accountId="ACC-300", amount=20, sequenceKey=10)` again.
- **Expected**: First response `SUCCESS`, second response `SUCCESS` (replayed), balance `$80`.
### 4. Idempotency: Conflicting Transaction (FR-007)
- **Setup**: New account `ACC-400` with `$100`.
- **Action**:
1. Submit `withdraw(accountId="ACC-400", amount=20, sequenceKey=10)`.
2. Submit `withdraw(accountId="ACC-400", amount=50, sequenceKey=10)`.
- **Expected**: First response `SUCCESS`, second response `CONFLICTING_TRANSACTION`. Balance `$80`.
### 5. Idempotency: Stale Sequence Key (FR-016)
- **Setup**: New account `ACC-500` with `$100`.
- **Action**:
1. Submit `withdraw(accountId="ACC-500", amount=10, sequenceKey=20)`.
2. Submit `withdraw(accountId="ACC-500", amount=10, sequenceKey=15)`.
- **Expected**: First response `SUCCESS`, second response `STALE_KEY`. Balance `$90`.
### 6. Atomic Recovery (FR-018)
- **Setup**: New account `ACC-600` with `$100`.
- **Action**:
1. Submit a successful withdrawal (`sequenceKey=10`).
2. Force-kill the server process.
3. Restart server.
4. Submit a retry of the same transaction (`sequenceKey=10`).
- **Expected**: Original response `SUCCESS` replayed, balance remains correct.
### 7. Concurrent Requests (FR-013)
- **Setup**: New account `ACC-700` with `$100`.
- **Action**: Use `CountDownLatch` to ensure sequence key 11 enters processing before sequence key 12. Submit both for `$60`.
- **Expected**: Key 11 `SUCCESS`, Key 12 `INSUFFICIENT_FUNDS`.
- **Verification**: If Key 12 is committed first, Key 11 must then be rejected as `STALE_KEY`.
### 8. Invalid Withdrawal Amount
- **Setup**: New account `ACC-800` with `$100`.
- **Action**: Submit `withdraw(accountId="ACC-800", amount=-10, sequenceKey=10)`.
- **Expected**: Response `INVALID_AMOUNT`, balance `$100`. No ledger entry.
### 9. Nonexistent Account
- **Setup**: Ensure `ACC-999` does not exist.
- **Action**: Submit `withdraw(accountId="ACC-999", amount=10, sequenceKey=10)`.
- **Expected**: Response `INVALID_ACCOUNT`.
### 10. Database Failure and Rollback
- **Setup**: New account `ACC-1000` with `$100`.
- **Action**:
1. Trigger a database connection failure (via mock or fault injector) during the balance update step of a withdrawal.
2. Attempt to query the account balance and ledger for `ACC-1000` after the failure.
- **Expected**: Transaction rolled back. Balance remains `$100`. No ledger entry for the failed transaction.
### 11. Bounded Retries and UNKNOWN_OUTCOME
- **Setup**: New account `ACC-1100` with `$100.00`.
- **Action**:
1. Submit `withdraw(accountId="ACC-1100", amount=25.00, sequenceKey=10)`.
2. Simulate server crash after database `COMMIT` but before the HTTP response is sent.
3. Keep the server unavailable until the client's bounded retries are exhausted.
- **Expected**: Client reports `UNKNOWN_OUTCOME`.
- **Verification**: Database balance for `ACC-1100` must be `$75.00`.
### 12. Recovery after UNKNOWN_OUTCOME
- **Setup**: Continuing from Scenario 11.
- **Action**:
1. Restart the server.
2. Submit `withdraw(accountId="ACC-1100", amount=25.00, sequenceKey=10, isRetry=true)`.
- **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.
# Research: Fault-Tolerant Distributed Banking Transaction
## Technical Decisions
### 1. Database Locking & Concurrency
- **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).
- Match $\rightarrow$ Return stored result.
- Mismatch $\rightarrow$ Return `CONFLICTING_TRANSACTION`.
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.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment