# As-built design — Lab 501

This is the service **as the repo ships it**. Open `Order.java`,
`IdempotencyRecord.java`, `OrderService.java`, `OrderController.java`, and
`GlobalExceptionHandler.java` while you read.

It is **not** the staff story. There is no `inventory` table, no `outbox` table,
no broker, no Resilience4j, and no Spring Security.

HTTP shapes also live in [api-notes.md](api-notes.md). Interview *why* lives in
[design-notes.md](design-notes.md).

## Runtime

| | |
| --- | --- |
| Language / build | Java 21, Maven Wrapper 3.9.9 |
| Framework | Spring Boot 3.3, Spring Data JPA, Bean Validation |
| Default store | H2 in-memory `jdbc:h2:mem:orders`, `MODE=PostgreSQL` |
| Optional store | PostgreSQL 16 via `SPRING_PROFILES_ACTIVE=postgres` |
| Schema | `spring.jpa.hibernate.ddl-auto=update` on both profiles |
| OSIV | `spring.jpa.open-in-view=false` |
| Clock | Hibernate JDBC `time_zone=UTC`. Jackson writes ISO-8601 instants, not epoch millis |
| HTTP | `http://localhost:8080`, base path `/api/v1` |
| Health | `/actuator/health` (`health`, `info`; probes on; details never) |
| H2 console | `/h2-console` on the default profile only (`jdbc:h2:mem:orders`, user `sa`, blank password) |

Tests always use H2. They never start Postgres.

## Layering

```text
HTTP  OrderController     mapping, @Valid, headers. No persistence. No status rules.
  →   OrderService        @Transactional unit of work, idempotency, status machine, event publish
        → OrderRepository              Spring Data JPA + @EntityGraph("items")
        → IdempotencyRecordRepository  Spring Data JPA
        → OrderMapper                  entity ↔ DTO (explicit, no MapStruct)
        → ApplicationEventPublisher    OrderCreatedEvent
Advice  GlobalExceptionHandler         one error JSON shape
Filter  CorrelationIdFilter            X-Correlation-Id → MDC + response header
```

Constructor injection only. Controllers never return `Order` / `OrderItem`.

## Data model

Three tables. Hibernate names them from `@Table`. There is no Flyway/Liquibase
script — `ddl-auto=update` creates them.

```text
orders 1 ──< order_items
idempotency_keys   (no FK to orders — stores a serialized OrderResponse)
```

### `orders` → `Order`

`@Entity` `@Table(name = "orders", indexes = @Index(name = "idx_orders_customer", columnList = "customer_id"))`

| Column | Mapping | Type | Null | Notes |
| --- | --- | --- | --- | --- |
| `id` | `@Id` `@GeneratedValue(UUID)` | UUID PK | no | Assigned on persist |
| `customer_id` | `@Column(nullable = false)` | UUID | no | Indexed. No `customers` table |
| `status` | `@Enumerated(STRING)` length 32 | VARCHAR(32) | no | See status machine |
| `total_amount` | precision 19, scale 2 | DECIMAL(19,2) | no | `qty * unit_price` summed, `HALF_UP` 2 dp |
| `created_at` | `updatable = false` | timestamp | no | `@PrePersist` |
| `updated_at` | | timestamp | no | `@PrePersist` and `@PreUpdate` |
| `version` | `@Version` | BIGINT | no | Optimistic lock. First persist → `0` |

`@OneToMany(mappedBy = "order", cascade = ALL, orphanRemoval = true)` `List<OrderItem> items`.
Adding a line calls `item.setOrder(this)`.

`recalculateTotal()` runs in the mapper before persist and in `@PrePersist` if
`totalAmount` is still null. There is no DB generated column.

There is **no inventory column** and no unique constraint on `customer_id`.

### `order_items` → `OrderItem`

`@Entity` `@Table(name = "order_items")`

| Column | Mapping | Type | Null | Notes |
| --- | --- | --- | --- | --- |
| `id` | `@Id` `@GeneratedValue(UUID)` | UUID PK | no | |
| `order_id` | `@ManyToOne(LAZY)` `@JoinColumn(nullable = false)` | UUID FK → `orders.id` | no | Inverse of `Order.items` |
| `product_id` | `@Column(nullable = false)` | UUID | no | Catalog id. No `products` table |
| `quantity` | `int` | INT | no | DTO enforces `>= 1` |
| `unit_price` | precision 19, scale 2 | DECIMAL(19,2) | no | DTO enforces `>= 0.01`, `≤ 2` fraction digits |

No unique `(order_id, product_id)` — two lines may share a product. No line-level
`@Version`.

### `idempotency_keys` → `IdempotencyRecord`

`@Entity` `@Table(name = "idempotency_keys")`

| Column | Mapping | Type | Null | Notes |
| --- | --- | --- | --- | --- |
| `idempotency_key` | `@Id` length 128 | VARCHAR(128) PK | no | Exact `Idempotency-Key` header. Unique **is** the PK |
| `request_hash` | length 64 | VARCHAR(64) | no | Lowercase hex SHA-256 of the JSON request bytes |
| `response_status` | `int` | INT | no | Written as `201` |
| `response_body` | `columnDefinition = TEXT` | TEXT | no | Jackson `OrderResponse`. `""` means reserved, not complete |
| `created_at` | `updatable = false` | timestamp | no | Set in the constructor |

No FK to `orders`. Replay is a deserialize of `response_body`, not a second
`SELECT` of the order (the stored JSON already has `id` / `version`).

PK collision is the concurrency control for two in-flight creates with the same
key (`saveAndFlush` + `DataIntegrityViolationException`).

### Approximate DDL (Postgres-shaped)

H2 `MODE=PostgreSQL` produces the same shapes. Types may differ slightly
(`UUID` vs `BINARY` vs `varchar`) under H2; treat this as the contract, not a
checked-in migration.

```sql
CREATE TABLE orders (
  id            UUID PRIMARY KEY,
  customer_id   UUID           NOT NULL,
  status        VARCHAR(32)    NOT NULL,
  total_amount  NUMERIC(19, 2) NOT NULL,
  created_at    TIMESTAMP      NOT NULL,
  updated_at    TIMESTAMP      NOT NULL,
  version       BIGINT         NOT NULL
);
CREATE INDEX idx_orders_customer ON orders (customer_id);

CREATE TABLE order_items (
  id          UUID PRIMARY KEY,
  order_id    UUID           NOT NULL REFERENCES orders (id),
  product_id  UUID           NOT NULL,
  quantity    INTEGER        NOT NULL,
  unit_price  NUMERIC(19, 2) NOT NULL
);

CREATE TABLE idempotency_keys (
  idempotency_key  VARCHAR(128) PRIMARY KEY,
  request_hash     VARCHAR(64)  NOT NULL,
  response_status  INTEGER      NOT NULL,
  response_body    TEXT         NOT NULL,
  created_at       TIMESTAMP    NOT NULL
);
```

Hibernate `@Version` UPDATE looks like:

```sql
UPDATE orders
   SET status = ?, updated_at = ?, version = version + 1
 WHERE id = ? AND version = ?;
-- 0 rows → OptimisticLockingFailureException
```

## HTTP surface

All JSON. All success bodies are DTOs. Dates are ISO-8601 UTC instants.

### Headers on every request

| Header | Required | Behavior |
| --- | --- | --- |
| `Content-Type: application/json` | write endpoints | Missing/unreadable body → `400 MALFORMED_REQUEST` |
| `Idempotency-Key` | `POST /orders` only | 1–128 chars after trim. Blank/missing → `400 MISSING_IDEMPOTENCY_KEY` |
| `X-Correlation-Id` | no | Echoed on **every** response. If blank/absent, filter generates a UUID |

### `POST /api/v1/orders` → `201 Created`

```http
POST /api/v1/orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: checkout-42
X-Correlation-Id: demo-1

{
  "customerId": "11111111-1111-1111-1111-111111111111",
  "items": [
    { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
  ]
}
```

Response headers: `Location: /api/v1/orders/{id}`, `X-Correlation-Id: …`

```json
{
  "id": "…",
  "customerId": "11111111-1111-1111-1111-111111111111",
  "status": "CREATED",
  "items": [
    { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
  ],
  "totalAmount": 39.98,
  "createdAt": "2026-09-11T21:00:00Z",
  "updatedAt": "2026-09-11T21:00:00Z",
  "version": 0
}
```

Replay (same key + same body) is still `201` + the **original** `Location` and body.
It does not insert a second order. It does not publish a second `OrderCreatedEvent`.

### `GET /api/v1/orders/{id}` → `200` or `404 ORDER_NOT_FOUND`

Same `OrderResponse` as create. Items come from `@EntityGraph(attributePaths = "items")`
on `OrderRepository.findById`. Mapping runs inside `@Transactional(readOnly = true)`.

Bad UUID in the path → `400 VALIDATION_ERROR` (`MethodArgumentTypeMismatch`).

### `GET /api/v1/orders?page=0&size=20` → `200`

| Query | Default | Constraint |
| --- | --- | --- |
| `page` | `0` | `@Min(0)` |
| `size` | `20` | `@Min(1)` `@Max(100)` |

Sort: `createdAt DESC`. `findAll(Pageable)` also uses the items entity graph, so
a page of N orders is not `1 + N` line queries.

```json
{
  "content": [ "OrderResponse…" ],
  "page": 0,
  "size": 20,
  "totalElements": 1,
  "totalPages": 1,
  "first": true,
  "last": true
}
```

There is no `customerId` filter in this lab.

### `PATCH /api/v1/orders/{id}/status` → `200`

```json
{ "status": "CONFIRMED", "version": 0 }
```

Both fields required. Success body is `OrderResponse` with `version` incremented
(0 → 1 on the first confirm). No `Idempotency-Key` on PATCH.

## Validation (request DTO)

`CreateOrderRequest`:

| Field | Rules |
| --- | --- |
| `customerId` | `@NotNull` — `"customerId is required"` |
| `items` | `@NotEmpty` `@Valid` — `"items must not be empty"` |

`OrderItemRequest`:

| Field | Rules |
| --- | --- |
| `productId` | `@NotNull` |
| `quantity` | `@NotNull` `@Min(1)` |
| `unitPrice` | `@NotNull` `@DecimalMin("0.01")` `@Digits(integer=17, fraction=2)` |

`UpdateOrderStatusRequest`:

| Field | Rules |
| --- | --- |
| `status` | `@NotNull` — must be an `OrderStatus` enum name |
| `version` | `@NotNull` |

`Idempotency-Key` header: `@NotBlank` `@Size(max = 128)`.

Failures → `400 VALIDATION_ERROR`, `errors: [{ "field", "message" }]`.

## Error catalog

Every error body:

```json
{
  "timestamp": "2026-09-11T21:00:00Z",
  "status": 409,
  "code": "IDEMPOTENCY_KEY_CONFLICT",
  "message": "…",
  "correlationId": "demo-1",
  "errors": []
}
```

`correlationId` is the MDC value from the filter. If MDC is empty, the handler
generates a UUID so the client still gets one.

| HTTP | `code` | When |
| --- | --- | --- |
| 400 | `MISSING_IDEMPOTENCY_KEY` | `POST` without `Idempotency-Key` |
| 400 | `MISSING_HEADER` | any other required header missing |
| 400 | `VALIDATION_ERROR` | Bean Validation, constraint violation, or bad path/query type |
| 400 | `MALFORMED_REQUEST` | unreadable JSON |
| 404 | `ORDER_NOT_FOUND` | unknown order id |
| 409 | `IDEMPOTENCY_KEY_CONFLICT` | same key, different SHA-256 body |
| 409 | `OPTIMISTIC_LOCK_CONFLICT` | PATCH `version` mismatch, **or** Hibernate `OptimisticLockingFailureException` on flush |
| 409 | `ORDER_STATE_CONFLICT` | illegal status transition |
| 500 | `INTERNAL_ERROR` | anything else (message is generic; stack goes to logs only) |

Domain exceptions log `warn` with `code`. Unhandled exceptions log `error`.

## Create algorithm (`OrderService.create`)

One `@Transactional` (default `REQUIRED`, read-write).

1. **Hash.** `ObjectMapper.writeValueAsBytes(request)` then `SHA-256` hex
   (`HexFormat`). The hash is of the **parsed DTO as re-serialized JSON**, not
   the raw request string. Extra unknown JSON fields are dropped by Jackson
   before the hash. Key order in the stored DTO follows the record components.
2. **Lookup** `idempotency_keys` by PK.
   - Hit + `request_hash` matches → deserialize `response_body` → return
     (replay). No new order. No new event.
   - Hit + hash differs → `409 IDEMPOTENCY_KEY_CONFLICT`.
3. **Reserve.** `saveAndFlush` a row `(key, hash, 201, "")`.
   - Unique violation → `findById` the winner. If that row now has a body,
     replay (or conflict on hash). If it is still empty, the winner is still
     inserting — the loser treats a completed body on the next read.
4. **Aggregate.** `OrderMapper.toNewEntity`: status `CREATED`, add lines, `recalculateTotal()`.
5. **`orderRepository.save`.** INSERT `orders` (`version = 0`) and INSERT each
   `order_items` row in the same persistence context.
6. **Map to `OrderResponse`** (needs generated `id` + `version`).
7. **`reservation.complete(201, json)`** — UPDATE the key row with the serialized
   response. Still the same transaction.
8. **`publishEvent(new OrderCreatedEvent(orderId, customerId))`** — recorded
   *inside* the transaction. Delivery is after commit (below).
9. Log `order.create.completed orderId=… totalAmount=…`.
10. Controller wraps the DTO in `201` + `Location`.

If any step throws before commit, the reserved key row rolls back. A retry with
the same key starts clean.

Logs on the happy path: `order.create.started` (customerId, itemCount),
`order.create.completed` (orderId, totalAmount). Replay logs
`order.create.replayed`.

## Status machine + optimistic lock (`updateStatus`)

```text
CREATED     → CONFIRMED, CANCELLED
CONFIRMED   → PROCESSING, CANCELLED
PROCESSING  → SHIPPED, CANCELLED
SHIPPED     → (none)
CANCELLED   → (none)
```

`OrderStatus.canTransitionTo` is an `EnumMap`. Same-status PATCH is illegal
(`CREATED → CREATED` is a `409 ORDER_STATE_CONFLICT`).

Locking is **two layers**:

1. Service: `if (!request.version().equals(order.getVersion()))` →
   `OptimisticLockConflictException` (`409`, message includes order id and
   expected version).
2. Hibernate: `UPDATE … WHERE id=? AND version=?`. Two writers who both read
   `version=0` and both pass step 1: the second flush throws
   `OptimisticLockingFailureException`, mapped to the same `code`
   `OPTIMISTIC_LOCK_CONFLICT` (generic message: *"The order was modified by
   another request"*).

PATCH is **not** idempotent. A retry with the old version after a success is a
`409`, not a replay.

Log: `order.status.updated orderId=… from=… to=… version=…`.

## Persistence / fetch plan

| Call | Repository | Graph | TX |
| --- | --- | --- | --- |
| create | `save(Order)` | cascade persist items | read-write |
| getById | `findById` | `items` | read-only |
| list | `findAll(Pageable)` | `items` | read-only |
| updateStatus | `findById` then `save` | `items` | read-write |

`open-in-view=false` means a lazy `items` touch **after** the service method
returns would throw. The graph + mapper-inside-the-TX is what makes GET/list
safe. That is the N+1 answer for this lab: entity graph, not `EAGER` on the
`@OneToMany`.

## Events

`OrderCreatedEvent(orderId, customerId, occurredAt=now)` is a Java record, not a
row.

Listener `OrderCreatedEventListener`:

- `@TransactionalEventListener(phase = AFTER_COMMIT)` — a throw in the listener
  cannot roll back the order.
- `@Async("orderEventExecutor")` — does not sit on the Tomcat thread.
- Body: one info log `order.event.created orderId=… customerId=… occurredAt=…`.
  No HTTP, no second DB write.

Executor `orderEventExecutor`: core 2, max 4, queue 100, prefix `order-event-`,
`MdcTaskDecorator` copies `correlationId` onto the async thread.

**Loss mode:** process crash after COMMIT and before the listener runs. The
order row is durable. The in-memory event is gone. The interview upgrade is an
`outbox` row in the **same** create transaction plus a relay. That table is not
in this repo.

## Correlation ID

`CorrelationIdFilter` at `Ordered.HIGHEST_PRECEDENCE`:

1. Read `X-Correlation-Id`. Blank/absent → `UUID.randomUUID()`.
2. `MDC.put("correlationId", …)`.
3. `response.setHeader("X-Correlation-Id", …)`.
4. `finally` `MDC.remove`.

Console pattern:

```text
%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} level=%-5level correlationId=%X{correlationId} logger=%logger{36} msg=%msg%n
```

Error JSON reuses the same id. The async listener keeps it via the task
decorator.

## Transactions (rules you say out loud)

- `@Transactional` is on the **service**, never the controller — the HTTP layer
  must not hold a JDBC connection while writing the response.
- Create, reserve-key, order insert, and key-complete are **one** commit.
- The event is registered before commit and delivered after.
- Read methods are `readOnly = true`.
- OSIV is off.

## Optional Postgres

```bash
docker compose up postgres
SPRING_PROFILES_ACTIVE=postgres ./mvnw spring-boot:run
```

or `docker compose up --build`. Credentials come from env
(`SPRING_DATASOURCE_URL` / `USERNAME` / `PASSWORD`). Compose defaults
`orders` / `orders` / `orders` are local only. Same entities, same
`ddl-auto=update`. H2 console is disabled on this profile.

## Tests that lock this contract

| Test | What it proves |
| --- | --- |
| `OrderApiIT` | create → GET → list → PATCH confirm (`version` 0→1) → stale PATCH `409 OPTIMISTIC_LOCK_CONFLICT`; `X-Correlation-Id` echoed |
| `OrderIdempotencyIT` | same key + body → one order row, one key row, one `OrderCreatedEvent`; same key + different body → `409` |
| `OrderOptimisticLockingTest` | `@Version` increment / conflict |
| `OrderValidationTest` / `OrderControllerTest` | missing key, empty items, bad qty/price |
| `OrderCreatedEventIT` | listener after commit |
| `OrderStatusTest` | legal / illegal transitions |
| `GlobalExceptionHandlerTest` | error JSON shape |

`./mvnw test` is the lab bar. BayLearn does not run these.

## What we left out on purpose

| Missing | Why | What you say next |
| --- | --- | --- |
| `inventory` | 35-minute accept path | `UPDATE inventory SET qty = qty - :n WHERE sku = :sku AND qty >= :n` |
| `outbox` | in-process event is enough to *talk* AFTER_COMMIT | same TX as `orders` + relay; consumer inbox PK |
| `customers` / `products` | ids only | those are other services |
| Authn / secrets | not the lab | no credentials in images or YAML beyond local Compose |
| Resilience4j | retries of *this* POST are the idempotency key | timeout + breaker on a *downstream* charge |
| Idempotent PATCH | status changes are not replays | client must send the version it last read |

**Say this:** the unique key and the version column are the correctness. The
happy-path service method is just the story that uses them.
