A practical project for a Distributed Systems course, developed using the **Spec-Driven Development (SDD)** methodology.
## 1. Selected Project
**Option 1: Implementing a Fault-Tolerant Distributed Banking Transaction.**
A client sends an HTTP withdrawal request to a banking server. The connection may be interrupted, or the server may crash before the response reaches the client—even after the withdrawal has already been committed. The system is designed to provide **effectively-once execution**: a transaction is not lost, and the same amount is never deducted twice when a request is retried.
## 2. Technology Stack and Development Tools
| Component | Technology |
|---|---|
| Programming language | Java 27 (as specified in `pom.xml` and the project constitution) |
| Build and testing | Maven + JUnit 5 |
| Database | Embedded H2 via JDBC, using a persistent database file in `./data` |
| HTTP server | JDK HTTP Server API |
| JSON processing | Jackson |
| SDD framework | GitHub Spec Kit (`/speckit.constitution`, followed by `specify`, `plan`, `tasks`, and `implement`) |
| Coding agent | Claude Code |
## 3. Repository Structure
```text
.specify/memory/constitution.md
# Phase 1: Project constitution
specs/001-fault-tolerant-banking-transaction/
spec.md # Phase 2: Feature specification
plan.md # Phase 3: Implementation plan
research.md
data-model.md
contracts/api.md
quickstart.md
tasks.md # Phase 4: Task breakdown
specs/002-banking-web-interface/ # Additional feature: Web interface
src/test/java/com/banking/ # Unit, integration, concurrency,
# and fault-injection tests
```
## 4. How the System Works
### Request Format
The client sends a request containing:
```json
{
"accountId":"ACC-100",
"amount":20,
"sequenceKey":10,
"isRetry":false
}
```
The `sequenceKey` is monotonically increasing for each account. The client generates a new key for every new transaction and reuses the same key and request data when retrying that transaction.
### Server-Side Processing
The server processes each request within a single JDBC transaction:
1.**Check the transaction ledger (`TRANSACTION_LEDGER`)** for the pair `(accountId, sequenceKey)`:
- If the entry exists and the amount matches, return the **original stored result** without executing the transaction again.
- If the entry exists but the amount differs, return `CONFLICTING_TRANSACTION`.
- If no entry exists and the key is less than or equal to the account's last processed key, return `STALE_KEY`.
2.**Lock the account row** using `SELECT ... FOR UPDATE`.
3.**Process the withdrawal**:
- Deduct the amount if sufficient funds are available.
- Otherwise, record an `INSUFFICIENT_FUNDS` result.
- Update `last_processed_seq_key` and insert the transaction record into the ledger.
4.**Commit the transaction**, then send the HTTP response.
The database constraints `CHECK (balance >= 0)` and `UNIQUE (account_id, sequence_key)` provide an additional layer of protection against negative balances and duplicate transaction records.
### Client-Side Retry Logic
The `RetryHandler` retries failed requests using exponential backoff:
- First retry delay: 100 ms
- Second retry delay: 200 ms
- Third retry delay: 400 ms
- Maximum number of attempts: 3
Every retry uses **the exact same sequence key and request data** as the original request. This allows the server to recognize a repeated request and return its previously stored result instead of processing the withdrawal again.
### Fault Simulation (FR-019)
The `FaultInjector` supports the four required failure scenarios. Faults are triggered per request through two HTTP headers sent to `POST /withdraw` (see `specs/003-fault-simulator/contracts/faults.md`).
| `X-Fault-Mode` | Behavior | Injection Point |
|---|---|---|
| `LOST_REQUEST` | Closes the connection without processing the request; the database remains unchanged. | At the beginning of `RequestHandler.handle`, before reading the request body. |
| `SERVER_CRASH` | Rolls back the transaction and terminates the server without sending a response; no partial changes are committed. | After processing but before `commit`. |
| `RESPONSE_LOSS` | Commits the transaction, then drops the response. | After `commit`. |
| `DELAY` | Delays the response by 7 seconds, exceeding the client's 5-second timeout. | Immediately before sending the response. |
The `X-Fault-Count` header contains the attempt number and is sent by the **client**. A fault is injected only when this value is `1`. Therefore, the second attempt—using the same sequence key—follows the normal processing path.
The server does not maintain any fault-injection state, so fault counters are not reset by a server restart and faults are not unintentionally repeated after recovery. Unknown values in `X-Fault-Mode` are ignored.
The default action for `SERVER_CRASH` is `Runtime.halt(1)`, which immediately terminates the process. During tests, this behavior is replaced with an in-JVM server shutdown through `FaultInjector.setCrashAction(...)`. The test harness acts as an external coordinator and is responsible for restarting the server.
## 5. Running the Application and Tests
### Requirements
- JDK 27
- Maven
### Build and Test
```bash
# Clean, build, and run all verification checks
mvn clean verify
# Run the test suite
mvn test
# Run a specific test (response-loss scenario)
mvn -Dtest=ResponseLossTest test
```
### Start the Server
The default server port is `8080`. It can be changed using the `server.port` property in `db.properties`.
Repeat the same withdrawal request. The server returns the same `SUCCESS` result, and the account balance remains `80`; the amount is not deducted a second time.
| `InsufficientFundsTest` | Insufficient-funds rejection is returned and recorded. |
| `IdempotencyTest`, `IdempotencyManagerTest` | Repeating the same request returns the original result without a second deduction. |
| `ConflictTest` | Reusing a sequence key with a different amount is rejected. |
| `ConcurrentWithdrawalTest` | Concurrent withdrawals from the same account are handled safely, without race conditions or negative balances. |
| `ResponseLossTest` | Recovery after the response is lost. |
| `RequestLossTest` | A lost request has no effect before the retry; the subsequent retry results in exactly one execution and preserves the expected final balance. |
| `CrashBeforeExecutionTest` | A crash before commit leaves no balance change, processed key, or ledger entry; after restart, the transaction is executed once. |
| `ServerCrashTest` | A committed transaction remains persisted after the server stops and is restarted. |
| `ExhaustedRetryTest` | The client reports failure after exhausting its attempts and can retry later using the same key. |
| `HardeningTest` | Input validation, including invalid amounts and account identifiers. |
### How SDD Helped Identify Problems Before Implementation
1.**Distinguishing a stale key from a legitimate retry.**
A simplistic rule that rejects every key lower than the last processed key would incorrectly reject a request that had already been executed but whose response was lost. This is precisely the failure scenario the system is intended to handle. Defining edge cases in `spec.md` forced me to specify the **correct validation order**: check the transaction ledger first, then check whether the key is stale, as required by FR-016. Had implementation started before this behavior was specified, the defect might have been discovered much later.
2.**A rejected request is also a result that must be persisted.**
Specifying the insufficient-funds scenario raised an important question: if a withdrawal is rejected and the account is funded later, should retrying the same request succeed? The specification defines the expected behavior: the original rejection must be returned. Consequently, rejected transactions are recorded in the ledger, and their sequence keys are advanced as well.
3.**Atomicity involves four operations, not just the balance update.**
FR-009 specifies that updating the balance, advancing the sequence key, inserting the ledger entry, and storing the transaction result must all take place in one database transaction. Including this requirement in the project constitution (Principle II) prevented the design from relying solely on in-memory synchronization.
4.**An unknown outcome is a distinct state.**
Defining `Unknown Outcome` in the specification prevented an uncertain result from being treated as a confirmed failure. It also required the client to reuse the same transaction identity when recovering from an uncertain outcome (User Story 8).
5.**Failure scenarios were defined before coding.**
Specifying the four failure scenarios in FR-019 made `FaultInjector` part of the initial design rather than an afterthought added later.
6.**Keeping fault-injection attempts consistent across restarts (Feature 003).**
During the `clarify` phase, an important question emerged: where should the fault-injection counter be stored if the injected fault causes the server to crash? If the counter were kept in server memory, it would reset after a crash and could cause the same fault to be injected repeatedly. The chosen solution was to have the client send the attempt number in an HTTP header. This means the server does not need to maintain fault-injection state. The issue was identified and resolved during specification, before implementation began.
### How I Guided the Coding Agent and Corrected Its Direction
- I started by defining the project constitution and establishing strict constraints—using `BigDecimal` for monetary values, requiring database-level atomicity, and avoiding shared in-memory state for financial data—before writing the feature specifications.
- I did not ask the coding agent to generate the entire project in one step. Instead, I followed the Spec Kit workflow and reviewed each output in sequence: specification, implementation plan, and task breakdown.
- I reviewed the specifications against a checklist (`checklists/requirements.md`) before moving on to planning.
- I ensured that implemented behavior could be traced back to a specification requirement. For example, task identifiers such as `T013` and `T029` are referenced in code comments.
### Key Design Decisions
| Decision | Rationale |
|---|---|
| Use a persistent H2 database instead of an in-memory map. | Allows the system to recover from server crashes (FR-018). |
| Lock the account row using `SELECT ... FOR UPDATE`. | Prevents race conditions between requests affecting the same account while allowing operations on different accounts to proceed independently (SC-005). |
| Add a `UNIQUE` constraint on `(account_id, sequence_key)`. | Provides a final database-level safeguard against duplicate transaction records. |
| Use `DECIMAL(20,2)` in the database and `BigDecimal` in Java. | Preserves monetary precision. |
| Use `isRetry` for diagnostic purposes only. | Duplicate prevention relies on the transaction key and request data, as defined in the specification. |
### Known Limitations
- There is no dedicated automated test for the timeout scenario (`DELAY`); it is currently tested manually using `quickstart.md`.
- Retry settings and timeout values are hard-coded.
- The client does not return an explicit `UNKNOWN_OUTCOME` result. Instead, it throws an exception after all retry attempts have been exhausted.
- Duplicate detection takes place before the account row is locked. Therefore, handling two concurrent requests with the same key relies on the database `UNIQUE` constraint.
- Concurrent requests are processed in the order in which they acquire the account lock, which is not necessarily the order of their sequence keys.