# Fault-Tolerant Distributed Banking System Constitution
## Core Principles
## Core Principles
### [PRINCIPLE_1_NAME]
### I. Persistence & ACID Compliance
<!-- Example: I. Library-First -->
The system MUST use SQLite file-based persistence. All transactions MUST adhere to ACID properties. To handle SQLite's lack of row-level locking, the system MUST use `IMMEDIATE` transaction mode and a configured `busy_timeout` to ensure concurrent requests wait instead of failing.
[PRINCIPLE_1_DESCRIPTION]
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
### [PRINCIPLE_2_NAME]
### II. Client-Driven Sequencing
<!-- Example: II. CLI Interface -->
Sequence keys for transactions MUST be generated by the client, per account, and MUST be monotonically increasing to ensure idempotency and ordering.
[PRINCIPLE_2_DESCRIPTION]
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
### [PRINCIPLE_3_NAME]
### III. Fault-Tolerant Server Design
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
The server MUST be designed to handle concurrent identical requests without duplicating transactions. Specifically, the debit operation and the update of `key_sequence_last` MUST occur within a single, atomic transaction.
[PRINCIPLE_3_DESCRIPTION]
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
### [PRINCIPLE_4_NAME]
### IV. Deterministic Fault Injection
<!-- Example: IV. Integration Testing -->
Fault injection MUST be implemented as configurable hook points within the server (pre-execution, mid-transaction, post-commit) and via middleware for request drops. Faults MUST be deterministic (e.g., "drop the first reply") to allow for reproducible testing.
[PRINCIPLE_4_DESCRIPTION]
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
### [PRINCIPLE_5_NAME]
### V. Test-First Acceptance
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
No feature is accepted until it passes the defined testing policy. Automated tests, specifically covering fault scenarios, are a non-negotiable prerequisite for feature completion.
The system MUST implement a layered testing approach:
1.**Unit Tests**: For core business logic and utility functions.
2.**Integration Tests**: To verify the interaction between the REST API, Hibernate, and the SQLite database.
3.**Fault-Injection Suite**: Dedicated tests that exercise the fault-injector hooks to verify system resilience.
4.**Concurrency Validation**: A specific test scenario involving many identical simultaneous requests MUST be implemented to prove that only one debit occurs.
### Concurrency & Error Handling
-**Concurrency**: Strict Locking (using `synchronized` blocks or `java.util.concurrent.locks`) MUST be used in conjunction with SQLite's `IMMEDIATE` transactions to ensure thread-safety.
-**Error Handling**: An exception-based (`try-catch`) strategy MUST be used, coupled with a global REST middleware to translate internal failures into standardized JSON error responses.
## Governance
## Governance
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
[GOVERNANCE_RULES]
This constitution serves as the highest authority for project technical decisions. Any amendments to these principles MUST be documented, approved by stakeholders, and include a migration plan for existing implementations.
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
The system follows a classic client-server architecture. The server acts as the authoritative source of truth for account balances and transaction sequences, utilizing a local SQLite database for ACID-compliant persistence.
### 1.1 Component Responsibilities
#### Client
-**Request Generation**: Constructs transaction requests with monotonically increasing sequence keys.
-**Retry Logic**: Manages timeouts and retry attempts using a backoff strategy.
-**State Tracking**: Tracks pending transactions and manages the `retry_is` flag.
-**Validation**: Parses server acknowledgments to determine if a debit succeeded or if a retry is needed.
#### Server
-**Request Handling**: Validates transaction identity and sequence ordering.
-**Concurrency Control**: Uses Java synchronization (optimization) and SQLite `IMMEDIATE` transactions (primary mechanism) to prevent race conditions.
-**Business Logic**: Performs fund verification and executes debits.
-**Persistence**: Manages the account state, transaction history, and idempotency metadata.
-**Fault Injection**: Provides hooks to simulate failures (drop, crash, delay).
2. Server $\rightarrow$ SQLite: `BEGIN IMMEDIATE` $\rightarrow$ Validate $\rightarrow$ Debit $\rightarrow$ Update Sequence $\rightarrow$ Record History $\rightarrow$ `COMMIT`.
3. Server $\rightarrow$ Client: `TransactionAcknowledgment` (Status, BalanceSnapshot, SequenceKey, Error).
## 2. Technical Design
### 2.1 Technology Stack
-**Language**: Java 21.
-**Build System**: Maven.
-**Persistence**: Hibernate 6 with `sqlite-jdbc`.
-**Database**: SQLite (File-based).
-**Testing**: JUnit 5.
### 2.2 Database Schema Design
#### Account Table
-`account_id` (PK): Unique identifier.
-`balance`: Current funds.
-`key_sequence_last`: The last successfully committed sequence key.
#### Transaction History Table
-`transaction_id` (PK): Auto-increment.
-`account_id` (FK): Reference to Account.
-`sequence_key`: The sequence key processed.
-`idempotency_key`: The key provided by the client.
-`amount`: Debited amount.
-`balance_snapshot`: The balance immediately after the debit.
-`timestamp`: Execution time.
-**Constraint**: Unique constraint on `{account_id, sequence_key}`.
#### Idempotency Metadata Table
-`account_id` (PK/FK): Reference to Account.
-`sequence_key` (PK): The sequence key.
-`idempotency_key`: The bound idempotency key.
-**Constraint**: Unique constraint on `{account_id, idempotency_key}`.
-*Note*: This table tracks the binding of `Sequence Key` $\rightarrow$ `Idempotency Key` for all attempts.
### 2.3 Transaction Processing Strategy
#### Transaction Workflow
The entire validation and execution sequence MUST be wrapped in a single SQLite `BEGIN IMMEDIATE` transaction to prevent state changes between validation and commit.
1.**Identity Check (Read-only)**: Check if `{AccountID, SequenceKey}` exists in `Transaction History`.
-**If exists**: Return the original result and `balance_snapshot` (Historical Retry).
-**Creation**: A mapping is created in `Idempotency Metadata` the first time a `{Account ID, Sequence Key}` is processed.
-**Persistence**: This mapping is preserved regardless of whether the transaction succeeds (Commit) or fails (Insufficient Funds).
-**Commitment**: Once a transaction is committed to `Transaction History`, the metadata mapping remains as the authoritative link for that sequence key.
### 2.4 SQLite Concurrency and Lock Handling
#### Lock Acquisition
-**Hibernate Integration**: To execute `BEGIN IMMEDIATE`, the server MUST use a native SQL query (`session.createNativeQuery("BEGIN IMMEDIATE").executeUpdate()`) before any Hibernate-managed operations occur, ensuring Hibernate does not start a default `DEFERRED` transaction.
-**Timeout Configuration**: `busy_timeout` is configured via the JDBC connection string (e.g., `jdbc:sqlite:bank.db?busy_timeout=5000`) to ensure consistency across all database connections.
#### Lock Timeout Behavior
-**Error Handling**: If the lock cannot be acquired within the timeout, the server returns a "Database Busy" error.
-**Safety**: Since no state changes occur before the `COMMIT`, retries after a lock timeout are naturally idempotent.
## 3. Fault Tolerance & Recovery
| Failure | Recovery Mechanism |
| :--- | :--- |
| **Dropped Request** | Client timeout $\rightarrow$ Retry $\rightarrow$ Server treats as first-time request. |
| **Crash Before Commit** | SQLite ensures the transaction is rolled back. Retry $\rightarrow$ Server treats as first-time request. |
| **Crash After Commit** | Transaction is durable in SQLite. Retry $\rightarrow$ Server finds sequence in `Transaction History` $\rightarrow$ returns cached result. |
| **Delayed Response** | Client retries while original is processing. Server's `synchronized` block/`IMMEDIATE` lock ensures sequential processing $\rightarrow$ Retry finds committed result. |
## 4. Testing Strategy
### 4.1 Test Levels
-**Unit Tests**: Logic for sequence validation and identity matching.
-**Integration Tests**: Hibernate $\rightarrow$ SQLite interaction and `IMMEDIATE` lock behavior.
-**Concurrency Tests**: Using `CompletableFuture` to fire $N$ identical requests.
-**Fault-Injection Tests**: Using a `FaultInjector` class that can be configured to throw exceptions or drop responses at specific hook points.
-**Process-Level Tests**: Testing server restarts by starting/stopping the application process.
### 4.2 Mapping Specification Scenarios to Tests
-**Scenario 1-4**: Fault-injection suite simulating drops, crashes, and delays.
-**Scenario 5-6**: Concurrency suite verifying single-debit and consistent failure outcomes.
-**Scenario 7**: Functional test for funding $\rightarrow$ retry $\rightarrow$ amount change.
-**Scenario 8**: Integration test verifying historical record retrieval.
-**Scenario 9-10**: Validation tests for mismatched payloads and out-of-order keys.
-**Test Case**: Start a transaction that holds the lock $\rightarrow$ Fire a second request $\rightarrow$ Verify "Database Busy" error $\rightarrow$ Release first lock $\rightarrow$ Retry second request $\rightarrow$ Verify exactly one debit.
-**Scenario 13**: Validation test for Idempotency Key mapping conflicts.
### 5. Engineering Considerations
-**Locking Granularity**: Java `synchronized` blocks are an optimization to reduce database contention and prevent multiple threads from attempting to start an `IMMEDIATE` transaction for the same account. SQLite `IMMEDIATE` locking remains the primary concurrency mechanism.
-**Snapshotting**: The `balance_snapshot` must be captured inside the same transaction as the debit.
-**Fault Injection Points**:
-**Application Exception**: Throwing a `RuntimeException` inside the business logic (simulates app crash).
-**Process Crash**: Killing the JVM process (simulates OS/hardware crash after commit).
-**Response Drop**: Dropping the HTTP response before it reaches the client (simulates network failure).
| **Successful Debit** | P0 | Client requests a debit from an account. | Balance decreased; result acknowledged. |
| **Retry after Network Failure** | P0 | Client retries a request after the previous attempt failed due to network issues. | Only one debit occurs; consistent acknowledgment returned. |
| **Crash before Execution** | P1 | Server crashes after receiving a request but before committing the transaction. | No debit occurs; retry results in successful debit. |
| **Crash/Loss after Commit** | P0 | Server commits the transaction but crashes or loses the response before the client receives it. | Debit occurred; retry returns the same acknowledgment without re-debiting. |
| **Delayed Response** | P1 | Server processes the request, but the response arrives after the client's timeout. | Client treats as failure and retries; system handles retry idempotently. |
| **Concurrent Identical Requests** | P0 | Multiple identical requests (same account, same sequence key) arrive simultaneously. | Exactly one debit occurs; all requests receive a consistent response. |
## 2. Functional Requirements
### 2.1 Transaction Identity and Idempotency
-**Transaction Identity**: A transaction is uniquely identified by the tuple: `{Account ID, Sequence Key}`.
-**Identity Relationship**:
-**Sequence Key**: Primary anchor for monotonicity and idempotency per account.
-**Idempotency Key**: An auxiliary identifier provided by the client to assist in request matching.
-**Conflict Rules**:
-**Same Account + Same Sequence + Different Idempotency Key**: MUST be rejected. Only one unique idempotency key can be associated with a specific account sequence key.
-**Same Idempotency Key + Different Sequence Key**: MUST be rejected. An idempotency key is bound to a specific sequence key for a given account.
-**Same Identity + Different Payload**: If a request arrives using an existing transaction identity but with a different amount or payload, it MUST be rejected as a "Mismatched Payload" error.
-**Idempotency Key Enforcement**:
- The system MUST ensure that an idempotency key is uniquely bound to a specific `{Account ID, Sequence Key}` tuple.
- To detect conflicts for failed attempts (e.g., Insufficient Funds) that do not create committed transaction records, the system MUST maintain a persistent metadata log of `{Account ID, Sequence Key, Idempotency Key}` mappings.
- This metadata log MUST be cleaned up or updated only when a transaction for that sequence key is finally committed or when the sequence key is explicitly invalidated.
-**Idempotency Enforcement**: Idempotency MUST be enforced using the persistent transaction identity and transaction history. The server MUST NOT rely on the `retry_is` flag to prevent duplicate debits.
-**`retry_is` Semantics**:
- Client MUST set `retry_is: false` for the initial attempt.
- Client MUST set `retry_is: true` for all subsequent retry attempts.
-**Consistent Acknowledgment**: A duplicate request MUST return the original transaction result, including the account balance snapshot recorded at the moment that specific transaction succeeded, rather than the current account balance.
### 2.2 Sequence Ordering Policy
-**Strict Monotonicity**: Every account MUST maintain a `key_sequence_last`.
-**Next Transaction**: The next new transaction request MUST use exactly `key_sequence_last + 1`.
-**Historical Recognition**: The server MUST recognize and return results for previously processed sequence keys (historical retries), even if newer transactions have already been processed.
-**Stale Keys**: Sequence keys that are unknown and less than the expected next key MUST be rejected as stale.
-**Future Keys**: Requests that skip the expected sequence (Key > `key_sequence_last + 1`) MUST be rejected.
### 2.3 Financial Integrity
-**Funds Verification**: A debit MUST only occur if the account has sufficient funds.
-**Insufficient Funds Behavior**:
- A failed attempt due to insufficient funds MUST NOT consume the sequence key and MUST NOT create a committed transaction record in the history.
- The client MAY retry using the same sequence key and idempotency key after the account is funded.
- Changing the transaction amount during such a retry IS permitted, as the sequence key was not consumed.
- The system distinguishes a legitimate retry from a conflict because no transaction record exists for that sequence key in the persistent history.
-**Atomic Updates**: The debit of funds and the update of the account's `key_sequence_last` MUST happen as a single atomic operation (using `IMMEDIATE` transaction mode per Constitution v1.0.1).
-**Persistence & Retention**: Transaction results, original balance snapshots, and sequence states MUST be preserved permanently in the transaction history. No arbitrary retention period shall be applied; records must remain available for historical retry recognition.
### 2.4 SQLite Concurrency and Lock Handling
-**Locking Mode**: The server MUST use `IMMEDIATE` transaction mode to acquire a write lock at the start of the transaction.
-**Wait Behavior**: A configured `busy_timeout` MUST be used to make concurrent requests wait for the lock instead of failing immediately.
-**Lock Timeout Handling**: If the lock cannot be acquired within the timeout, the server MUST return a "Database Busy" or "Lock Timeout" error.
-**Retry Policy**: Clients may retry after a lock timeout. Since no state changes occur during a lock timeout, such retries are safe and will be handled by the standard idempotency rules.
## 3. Failure Scenarios (Fault-Injection)
| Fault Scenario | System Behavior |
| :--- | :--- |
| **Request Dropped (Pre-Server)** | Request never reaches the server. Client times out $\rightarrow$ retries $\rightarrow$ server processes first-time request $\rightarrow$ Success. |
| **Server Failure (Pre-Execution)** | Server receives request but crashes before commit. No state change. Client retries $\rightarrow$ server processes as new request $\rightarrow$ Success. |
| **Commit Successful, Response Lost** | Server commits debit and updates sequence $\rightarrow$ crashes/drops response. Client times out $\rightarrow$ retries $\rightarrow$ server identifies duplicate sequence $\rightarrow$ returns cached result $\rightarrow$ Success (No second debit). |
| **Response Delayed (Post-Timeout)** | Server commits $\rightarrow$ response delayed. Client times out $\rightarrow$ retries. Server receives retry while original is still processing or finished $\rightarrow$ handles idempotently $\rightarrow$ Success (No second debit). |
## 4. Concurrency and Idempotency
### 4.1 Simultaneous Identical Requests
When multiple identical requests (same account, same sequence key) hit the server simultaneously:
- The system MUST synchronize access to the account state.
- Only one request MUST be allowed to execute the debit logic.
- All simultaneous identical requests MUST receive the same consistent transaction outcome (the result of the one successful execution), regardless of whether the outcome was a Success (Debit) or a Failure (e.g., Insufficient Funds).
- Concurrent duplicate requests MUST NOT produce conflicting results or multiple debits.
### 4.2 Acceptance Criteria for Concurrency
-**Proof of Single Debit**: A test executing $N$ simultaneous identical requests MUST result in exactly one debit from the account balance and exactly one increment of the sequence key.
## 5. API Expectations
### 5.1 Transaction Request
The request must convey the intent to debit an account, providing:
- Account Identifier.
- Monotonically increasing sequence key.
- Idempotency key.
-`retry_is` (Boolean).
- Amount to be debited.
### 5.2 Transaction Acknowledgment
The response must convey the outcome of the operation:
-**Status**: Success or Failure.
-**Balance**:
-**For Success**: Balance Snapshot (The balance as it was immediately after the transaction succeeded).
-**For Failure**: Current account balance at the time of failure.
-**Sequence Information**:
-**Submitted Sequence Key**: The sequence key provided by the client.
-**Account's Last Committed Sequence Key**: The current `key_sequence_last` for the account.
**Given** an account with balance \$100 and last sequence key 5
**When** a request for sequence key 6 to debit \$20 is sent but dropped before reaching the server
**And** the client times out and retries the request for sequence key 6
**Then** the account balance should be \$80
**And** the sequence key should be 6
**And** exactly one debit must have occurred.
### Scenario 2: Server Crash Before Execution/Commit
**Given** an account with balance \$100 and last sequence key 5
**When** a request for sequence key 6 to debit \$20 is received by the server, but the server crashes before committing
**And** the server restarts and the client retries the request for sequence key 6
**Then** the account balance should be \$80
**And** the sequence key should be 6
**And** exactly one debit must have occurred.
### Scenario 3: Commit Successful, Response Lost
**Given** an account with balance \$100 and last sequence key 5
**When** a request for sequence key 6 to debit \$20 is processed and committed, but the response is lost
**And** the client retries the request for sequence key 6
**Then** the account balance should be \$80
**And** the sequence key should be 6
**And** exactly one debit must have occurred.
**And** the server should return the original balance snapshot of \$80 twice.
### Scenario 4: Server Response Delayed (Post-Timeout)
**Given** an account with balance \$100 and last sequence key 5
**When** a request for sequence key 6 to debit \$20 is processed, but the response is delayed
**And** the client times out and retries the request for sequence key 6
**Then** the account balance should be \$80
**And** the sequence key should be 6
**And** exactly one debit must have occurred.
### Scenario 5: Prevention of Double Debit under Concurrency
**Given** an account with balance \$100 and last sequence key 5
**When** 10 identical requests for sequence key 6 to debit \$20 arrive simultaneously
**Then** the account balance should be \$80
**And** the account sequence key should be 6
**And** exactly one transaction must have been committed to the database.
**And** all 10 requests must receive the same success acknowledgment.
### Scenario 6: Concurrent Insufficient Funds
**Given** an account with balance \$10 and last sequence key 5
**When** 10 identical requests for sequence key 6 to debit \$20 arrive simultaneously
**Then** the server should return "Insufficient Funds" for all 10 requests
**And** the account balance should remain \$10
**And** the account sequence key should remain 5
**And** no transaction record should be created in the history.
### Scenario 7: Successful Retry after Funding and Amount Change
**Given** an account with balance \$100 and last sequence key 5
**When** a request arrives for sequence key 6 to debit \$20 $\rightarrow$ Returns "Insufficient Funds"
**And** the account is funded to \$100
**And** the client retries the request for sequence key 6 to debit \$10 (Amount changed)
**Then** the account balance should be \$90
**And** the sequence key should be 6
**And** exactly one debit must have occurred.
### Scenario 8: Historical Retry after Newer Transaction
**Given** an account with balance \$100 and last sequence key 5
**When** a request arrives for sequence key 6 to debit \$20 (Success, balance \$80, sequence 6)
**And** a request arrives for sequence key 7 to debit \$10 (Success, balance \$70, sequence 7)
**And** a retry for sequence key 6 arrives
**Then** the server should return the original result for sequence key 6 (Success, balance snapshot \$80)
**And** the account balance should remain \$70.
### Scenario 9: Mismatched Payload for Existing Sequence
**Given** an account with balance \$100 and last sequence key 5
**When** a request arrives for sequence key 6 to debit \$20 (Success)
**And** a second request arrives for sequence key 6 to debit \$50
**Then** the server should return a "Mismatched Payload" error.
### Scenario 10: Out-of-Order Sequence Keys
**Given** an account with balance \$100 and last sequence key 5
**When** a request arrives for sequence key 7 (skipping 6)
**Then** the server should return an "Out-of-Order Sequence Key" error.
### Scenario 11: Server Restart Recovery
**Given** an account with balance \$100 and last sequence key 5
**When** a request arrives for sequence key 6 to debit \$20, the server commits but then crashes
**And** the server restarts
**And** the client retries the request for sequence key 6
**Then** the server should recognize the transaction in history and return the original result.
### Scenario 12: Database Lock Timeout
**Given** an account with balance \$100 and last sequence key 5
**When** a request for sequence key 6 to debit \$20 is sent, but the database write lock is held by another process for longer than the configured `busy_timeout`
**Then** the server should return a "Database Busy" or "Lock Timeout" error
**And** the account balance should remain \$100
**And** the account sequence key should remain 5
**And** no partial changes should have occurred to the account state.
### Scenario 13: Idempotency Key Conflict
**Given** an account with balance \$100 and last sequence key 5
**Given** a request for sequence key 6 to debit \$20 arrives and fails due to "Insufficient Funds" (But idempotency key "ID-1" is provided)
**When** a new request for sequence key 6 arrives with a different idempotency key "ID-2"
**Then** the server should return an idempotency conflict error.
-[x]**T2.4**: Verify schema creation and both uniqueness constraints (Sequence $\rightarrow$ ID and ID $\rightarrow$ Sequence) using integration tests.
## Phase 3: Core Transaction Foundation
-[x]**T3.1**: **Investigation**: Verify compatibility of `BEGIN IMMEDIATE` with Hibernate transaction lifecycle.
- Research JDBC connection identity and Hibernate's transaction start behavior.
- Verify that `BEGIN IMMEDIATE` occurs before any database reads/writes.
- Test commit/rollback behavior and ensure no conflicting transaction management.
-[x]**T3.2**: Implement the chosen atomic transaction wrapper based on T3.1 findings.
-[x]**T3.3**: Implement the atomic debit and `key_sequence_last` update logic. (Constitution III)
-[x]**T3.4**: Implement balance snapshot capture within the atomic transaction. (Plan 2.3)
-[x]**T3.5**: Verify atomic updates: a failed commit must rollback both balance and sequence key. (Verification)
## Phase 4: Idempotency and Sequence Validation
-[x]**T4.1**: Implement the `Transaction Identity` lookup in `Transaction History`. (Spec 2.1)