Skip to content

About

Event-driven inventory reservation system — Java 21 / Spring Kafka / React + TypeScript

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

22 Commits

Folders and files

Repository files navigation

Stock Reservation Service

An event-driven inventory reservation system built around one invariant:

For every SKU: reserved >= 0, on_hand >= 0, and reserved <= on_hand. Available stock (on_hand - reserved) can never go negative.

It holds that invariant under thousands of concurrent reservation requests and through database failures, broker retries, and dropped network calls.

Why this project matters

This is not a toy inventory app. It models the kind of concurrency and failure handling that shows up in real operational systems: stock availability, hold creation, retries, idempotency, and reconciliation when the outside world is not perfectly reliable.

The project is useful for three reasons:

  • It demonstrates how a reservation system protects the invariant that stock can never be oversold under concurrency.
  • It shows how event-driven integration behaves under partial failure, retries, and dead-letter handling.
  • It gives a concrete example of operational thinking: the system has to stay correct even when the database or broker is under pressure.

Quick proof of behavior

A recruiter or technical reviewer should be able to understand the project in a minute without cloning the whole stack. The core flows are:

  1. Open a SKU with initial stock.
  2. Create a reservation against that SKU.
  3. Reject over-reservation with an explicit stock rule error.
  4. Reconcile warehouse movement events through Kafka.
  5. Observe the system state through the console and metrics.
API=http://localhost:8080/api/v1

curl -s -XPOST $API/stock -H 'Content-Type: application/json' \
  -d '{"sku":"DEMO-1","onHand":8}'

curl -s -XPOST $API/reservations -H 'Content-Type: application/json' \
  -d '{"sku":"DEMO-1","quantity":3,"idempotencyKey":"demo-key-1"}'

curl -s -XPOST $API/reservations -H 'Content-Type: application/json' \
  -d '{"sku":"DEMO-1","quantity":99,"idempotencyKey":"demo-key-2"}'

The second request should stop with the expected insufficient-stock outcome, while the first one maintains the invariant without overselling.

Visual quick look

The fastest way to evaluate the project is to look at the console and then run the quick demo flow.

Stock Reservation Console (demo mode) Stock Reservation Console unknown SKU recovery state

Layer Stack
Backend Java 21 · Spring Boot 3 · Spring Kafka · PostgreSQL · Flyway
Frontend React 19 · TypeScript (strict) · Vite · TanStack Query v5
Infra Docker Compose — PostgreSQL, Kafka (KRaft), Kafka UI, Prometheus, Grafana

Design in one picture

 React console ──POST /reservations (201 / 409)──►  REST adapter ─┐
                                                                  ▼
 Warehouse (WMS) ──wms.stock-movements.v1──► Kafka ──► Stock consumer ──► Reservation core ──► PostgreSQL
                    (retry topics + .dlt)                                     │  invariant     stock_level
                                                                             │  optimistic    reservation
                                                                             │  lock, ledger  stock_ledger
                                                                             ▼                outbox / inbox
                                                          outbox relay ──► inventory.events.v1
  • Synchronous path for customer reservations — an immediate 201 or 409 INSUFFICIENT_STOCK, guarded by optimistic locking with bounded in-transaction retry.
  • Asynchronous path for the warehouse feed — a Kafka consumer with non-blocking retry topics (exponential backoff), an explicit dead-letter topic, an idempotent inbox, and a failure classifier that separates transient errors (retry) from permanent ones (dead-letter immediately).
  • Transactional outbox so a domain event is published if and only if its transaction committed.

What's implemented

Area Detail
Concurrency Optimistic @Version locking + bounded retry; a 200-caller race test asserts zero oversell
Event consumer @RetryableTopic non-blocking retry (≈10s → 50s → 4m) → .dlt; queryable dead-letter store with one-call redrive
DB-failure handling PersistenceExceptionClassifier → CONTENTION / TRANSIENT / PERMANENT; unknown failures fail closed
Idempotency Client Idempotency-Key (unique constraint) · consumer inbox de-dup · transactional outbox
Correctness backstop CHECK (reserved >= 0 AND on_hand >= 0 AND reserved <= on_hand) at the database
Observability /actuator/prometheus — inventory_oversell_total (must be 0), reservation rate by outcome, movement processing p99, outbox lag, dead-letter depth; provisioned Grafana dashboard
Frontend Optimistic reserve/release with snapshot + rollback; failure classification; reconcile on settled
Tests 36 backend (JUnit + Testcontainers: Postgres + Kafka) · 4 frontend (Vitest + MSW)
CI GitHub Actions — backend build+test, frontend lint/types/test/build, container image build

Run it

# 1. Infrastructure
docker compose -f infra/docker-compose.yml up -d postgres kafka kafka-ui prometheus grafana

# 2. Backend (Java 21 required)
cd backend && ./gradlew bootRun          # http://localhost:8080

# 3. Frontend
cd web && npm install && npm run dev      # http://localhost:5173

Fast UI demo (no backend required)

If you only want to inspect product behavior quickly, run the frontend with a stateful browser mock layer. This avoids the full Kafka/Postgres setup while keeping reserve/release interactions realistic.

cd web
npm install
npm run dev:demo -- --host 127.0.0.1 --port 5174

Open http://127.0.0.1:5174 and use SKU DEMO-1.

Or run the whole thing, backend included, in containers:

docker compose -f infra/docker-compose.yml up --build
Service URL
API http://localhost:8080/api/v1
Actuator / Prometheus scrape http://localhost:8080/actuator
Kafka UI http://localhost:8085
Prometheus http://localhost:9090
Grafana (anonymous admin) http://localhost:3001

Demo

API=http://localhost:8080/api/v1

# open a SKU with 8 units, reserve 3
curl -s -XPOST $API/stock -H 'Content-Type: application/json' -d '{"sku":"DEMO-1","onHand":8}'
curl -s -XPOST $API/reservations -H 'Content-Type: application/json' \
  -d '{"sku":"DEMO-1","quantity":3,"idempotencyKey":"demo-key-1"}'

# over-reserve -> 409 INSUFFICIENT_STOCK
curl -s -XPOST $API/reservations -H 'Content-Type: application/json' \
  -d '{"sku":"DEMO-1","quantity":99,"idempotencyKey":"demo-key-2"}'

# a warehouse goods receipt over Kafka
echo 'DEMO-1|{"eventId":"r-1","sku":"DEMO-1","type":"RECEIPT","quantity":25,"occurredAt":"2026-01-01T00:00:00Z"}' \
  | docker exec -i stock-reservation-kafka-1 /opt/kafka/bin/kafka-console-producer.sh \
      --bootstrap-server localhost:9092 --topic wms.stock-movements.v1 \
      --property parse.key=true --property key.separator='|'

curl -s $API/stock/DEMO-1        # on_hand is now 33
curl -s $API/dead-letters        # empty

Documentation

Auth rollout (phase 1)

JWT auth for operator routes is now implemented behind a feature flag.

  • inventory.security.enabled=false keeps current behavior unchanged.
  • inventory.security.enabled=true protects:
    • POST /api/v1/stock and POST /api/v1/stock/*
    • /api/v1/dead-letters/*
    • POST /api/v1/reservations/{id}/confirm
    • DELETE /api/v1/reservations/{id}
  • role claim path is configurable with inventory.security.roles-claim (default: roles).

When enabled, configure Spring Resource Server JWT settings under:

  • spring.security.oauth2.resourceserver.jwt.issuer-uri, or
  • spring.security.oauth2.resourceserver.jwt.jwk-set-uri

Scope

Single-warehouse; single Kafka broker locally (production notes call for 3+, min.insync.replicas=2, acks=all); the warehouse feed is driven by a kafka-console-producer one-liner rather than a real WMS; customer-facing auth is still out of scope.

License

MIT — see LICENSE.

Development improvements (shortlist)

Primary language: English. Spanish version below is for external consultation only.

  • Wire issuer-uri or jwk-set-uri for JWT validation in secured environments.
  • Add a reservation-expiry worker that releases stale PENDING holds.
  • Mark dead letters as redriven only after Kafka publish acknowledgement.
  • Add outbox claim/locking for safe multi-instance relay execution.
  • Enable branch protection and security checks in CI.

Consulta externa (ES)

  • Configurar issuer-uri o jwk-set-uri para validar JWT en entornos seguros.
  • Agregar un worker de expiracion de reservas que libere holds PENDING vencidos.
  • Marcar dead letters como redriven solo despues del acuse de publish en Kafka.
  • Agregar claim/locking del outbox para ejecucion segura en multiples instancias.
  • Habilitar branch protection y checks de seguridad en CI.

About

Event-driven inventory reservation system — Java 21 / Spring Kafka / React + TypeScript

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages