Skip to main content

Architecture

The service is hexagonal (ports & adapters) with one non-negotiable rule:

domain depends on nothing; application depends on domain; adapters depend on application/domain.

No framework type, no chi router, no pgx connection, and no SQL string ever appears inside internal/domain/.

Layout​

cmd/inventory/ main.go — composition root (OLTP REST API)
cmd/inventory-projector/ analytics writer (ADR 0011)
cmd/inventory-reports/ analytics read-only report REST (ADR 0011)
cmd/mcp/ MCP server, Streamable HTTP (ADR 0008)
internal/
domain/ pure Go — no framework, no SQL types
location/ Bin aggregate (capacity, occupancy)
stock/ StockUnit aggregate (SKU@bin, qty, state)
reservation/ Reservation aggregate (revocable, timeout)
product/ ProductClassification aggregate + DOT segregation
shared/ SKU, BinId, Quantity value objects; domain events
analytics/report/ analytics read-model region (imports no OLTP code)
application/
ports/ OUT interfaces (see Ports below)
usecases/ one struct per use case
adapters/
inbound/http/ chi handlers, DTOs, RFC 7807 error mapping; reports REST
inbound/kafka/ Kafka consumers: transfer commands, product-master,
inbound receipts, TaskCompleted, analytics (projector)
kafka/cloudevents/ CloudEvents 1.0 structured-mode envelope helpers
inbound/mcp/ MCP tools, resources and prompts
outbound/postgres/ pgxpool repos + golang-migrate migrations
outbound/memory/ thread-safe in-memory repos: unit/BDD test doubles only
outbound/events/ log, buffered and multi (fan-out) publishers: test doubles only (events leave through the outbox)
outbound/kafka/ integration + analytics publishers (kafka-go)
outbound/analyticsstore/ analytical Postgres projection + reader
outbound/facilitycache/ Kafka-fed facility-layout location cache (ADR 0013)
outbound/facilitylayout/ sync HTTP location lookup (LOCATION_LOOKUP_MODE=http, rollback for kafka)
outbound/telemetry/ OTel setup, trace-aware slog, metrics
outbound/bootretry/ boot-time dial retry (ADR 0028)
outbound/system/ wall-clock Clock
resilience/ circuit breaker policy + call deadlines (ADR 0020)
pgtx/ transaction-on-context helper (idempotency middleware)
architecture/ arch-go fitness tests encoding the rule above
migrations/ golang-migrate SQL files (OLTP)
migrations/analytics/ golang-migrate SQL files (analytical DB)
apis/ openapi.yaml + asyncapi.yaml (Spectral-linted)
features/ Gherkin acceptance specs (godog)
charts/inventory-storage/ Helm chart
web/ inventory_mfe Module Federation remote

Binaries, ports and data stores​

One image carries four binaries (Dockerfile copies all of them to /app; the default entrypoint is ./inventory). Each is its own composition root.

BinaryRoleListens on (default)Data storeKafka
cmd/inventoryOLTP REST API: every route in apis/openapi.yaml except /reports/*, plus /healthz (liveness) and /readyz (drain gate + Postgres + Kafka); always runs the outbox relay, the housekeeping sweeper and all four inbound consumersHTTP_ADDR :8080OLTP Postgres (DATABASE_URL, mandatory)produces warehouse.inventory.events + warehouse.inventory.analytics (outbox relay); consumes the transfer, product-master, inbound-receiving and fulfillment topics (always on) and, with LOCATION_LOOKUP_MODE=kafka, the facility topic; KAFKA_BROKERS mandatory
cmd/mcpMCP server (Streamable HTTP): 4–5 tools, 1 resource template, 1 prompt over the same use casesMCP_ADDR :8090same OLTP Postgres (DATABASE_URL, mandatory; always writes outbox rows, runs no relay)none: never dials Kafka, no /readyz
cmd/a2aA2A agent (JSON-RPC over HTTP, Agent Card at /.well-known/agent-card.json, ADR 0048): skills check_availability (read) and revoke_reservation (write) over the same use casesA2A_ADDR :8093same OLTP Postgres (DATABASE_URL, mandatory; always writes outbox rows, runs no relay)none: never dials Kafka, no /readyz
cmd/inventory-projectorAnalytics writer: projects warehouse.inventory.analytics into the rollupADMIN_ADDR :8091 (/healthz, /readyz)analytical Postgres (ANALYTICS_DATABASE_URL, read-write; applies migrations/analytics)consumes warehouse.inventory.analytics (group inventory-analytics); KAFKA_BROKERS mandatory; exits non-zero if the consumer dies
cmd/inventory-reportsAnalytics reader: GET /reports/flow-accuracy, GET /reports/flow-accuracy/freshness, /healthzHTTP_ADDR :8092analytical Postgres, read-only pool—

Source: cmd/inventory/main.go, cmd/mcp/main.go, cmd/inventory-projector/main.go, cmd/inventory-reports/main.go, charts/inventory-storage/templates/*-deployment.yaml.

The OLTP and analytical databases are separate on purpose (ADR 0011): the projector is the only writer of the analytical schema and nothing in the OLTP path reads it. Ports, probes and Deployments are on the Runbook; every environment variable is on Configuration.

The dependency flow​

Source: internal/architecture/architecture_test.go, internal/application/ports/ports.go.

Solid arrows are compile-time imports; dashed arrows are interface satisfaction. Note that no arrow points from the application layer into an adapter — the application only ever names an interface in application/ports, and cmd/inventory/main.go is the only place that decides which implementation gets plugged in.

The rule is executable, not aspirational​

internal/architecture/architecture_test.go uses arch-go to assert the layering as a normal Go test, and CI runs it as a blocking arch-test job. The rules it encodes:

  1. internal/domain/... must not import any other internal/... package.
  2. internal/application/... may import only internal/domain/... and itself — never internal/adapters/....
  3. internal/adapters/inbound/... must not import internal/adapters/outbound/... (and vice versa).
  4. Nothing under internal/... may import cmd/... — cmd stays the leaf composition root.
  5. internal/application/ports may contain only interfaces.
  6. internal/analytics/... imports nothing internal except itself, and the OLTP domain must not import the analytics store (ADR 0011).

Further fitness tests in the same package (ADR 0029) guard the MCP adapter's dependency rule, forbid reintroducing auth middleware, keep Kafka consumer groups out of inline literals, require testcontainers for Kafka integration tests, pin the event catalogue to apis/asyncapi.yaml, enforce CloudEvents-only encoding, and require CommitInterval on replay consumers.

If someone reaches from a use case into pgx for a "quick fix," the build goes red. See ADR 0006.

Ports​

PortResponsibilityImplementations
StockRepoPersist/retrieve StockUnit; find by ID, SKU, bin; mint IDspostgres, memory
LocationRepoPersist/retrieve Binpostgres, memory
ReservationRepoPersist/retrieve Reservation; mint IDspostgres, memory
ProductClassificationRepoPersist/retrieve ProductClassification by SKUpostgres, memory
LocationClassificationLookupZone attributes (hazmat, temperature class) for a bin, for stow placement rulesfacilitycache (Kafka-fed cache, LOCATION_LOOKUP_MODE=kafka), facilitylayout (sync HTTP client, LOCATION_LOOKUP_MODE=http, the rollback)
EventPublisherPublish a shared.DomainEventpostgres.OutboxPublisher (one outbox_events row per event × topic inside the caller's transaction, ADR 0017; the only implementation the binaries wire, ADR 0042); the relay then publishes through kafka (integration + analytics); events (log/buffered/multi) exist as test doubles only
UnitOfWorkBracket a use case's Save(s) and Publish(es) in one atomic scopepostgres.UnitOfWork (joins a transaction already on the context, e.g. the idempotency middleware's)
ReservationMetricsCount reservations created/revoked (inventory.reservations)telemetry
ClockNow() — makes reservation timeouts deterministic in testssystem.Clock (the binaries), memory fixed clocks (tests)
PickConfirmationMetrics / InboundReceiptMetricsCount inventory.pick_confirmations / inventory.inbound_receipt_units by outcometelemetry
ProductClassificationLocalCopyApply product-master's classification to the local copy (ADR 0034)postgres, memory (test doubles only)
ProcessedEventRepoClaim an inbound event id once (dedupe for product-master, inbound-receipt and TaskCompleted consumers)postgres (processed_events), memory
OrderPickProgressRepoCount completed PICK tasks per order (ADR 0035)postgres (order_pick_progress), memory
TransferAllocationRepoOrigin-side transfer ledger (ADR 0030)postgres (transfer_allocations), memory
TransferReceiptRepo / InventoryExceptionRepoDestination receipts and quarantined scans (ADR 0033)postgres (transfer_receipts, inventory_exceptions), memory

The Clock port matters more than it looks: reservation expiry is a domain concept, so time must be injected rather than read from time.Now() inside an aggregate. Every domain event's occurredAt comes from that injected clock.

Composition root​

Each cmd/<binary> is the only place that knows both an interface and its implementation. cmd/inventory is split by concern (config.go env parsing, adapters.go repository/publisher/relay assembly, postgres.go migrations and pool, lookup.go location lookup, transfer.go / productmaster.go / inboundreceipt.go / confirmpick.go consumers, housekeeping.go, server.go, shutdown.go). Two variables are read outside cmd/: CORS_ALLOWED_ORIGINS by the HTTP adapter and ENVIRONMENT by the telemetry adapter.

The startup order is fixed: config validated (loadConfig, before any dial) → telemetry → migrations + pool (under boot retry) → outbox publisher + relay → location lookup (blocks on the facility cache replay in kafka mode) → the four consumers → HTTP listener. Every variable, default and requirement per binary is on Configuration.

There is no in-memory fallback in any binary (ADR 0042): a missing DATABASE_URL or KAFKA_BROKERS is a boot error, and the sensor TestRuntimeBinaryHasNoInMemoryAdapters fails the build if a cmd/ binary imports internal/adapters/outbound/memory. The httptest and godog acceptance suites stay cheap by using those adapters as test doubles; anything that needs real behaviour runs on testcontainers (TestRunOnRealPostgresAndKafka).

Quality gates​

Everything below runs in .github/workflows/ci.yml on every push and pull request:

JobWhat it enforces
lintgolangci-lint against the committed .golangci.yml
guide-lintThe harness guide/repo linters and hook self-tests (scripts/harness/*.py)
complexitygolangci-lint with gocyclo,gocognit,cyclop,funlen,nestif only; informational gocyclo report in the job summary
testUnit tests with -race; coverage gate on domain + application
bddgodog acceptance suite over the Gherkin specs in features/
contractSchemathesis property-based contract tests driven from apis/openapi.yaml, run against a postgres:16 and a confluentinc/confluent-local service container (the real runtime)
evals-testsThe MCP eval gate (E1 schema, E2 wire conformance, E3 behavioral) as its own named check — the same suites also run inside test
integrationThe whole -tags=integration tree: every Postgres and Kafka test boots its own container via testcontainers (no service container, no DATABASE_URL; the Ryuk reaper is disabled on the ephemeral runner)
mutation-fastgremlins on internal/domain/stock — blocking
mutationgremlins on all of internal/domain (scheduled/dispatch only)
driftDead code, go mod tidy -diff, knip, coverage quality (scheduled/dispatch only, advisory)
api-lintSpectral against apis/openapi.yaml and apis/asyncapi.yaml
vulngovulncheck ./...
docs-api-driftRegenerates the REST reference from apis/openapi.yaml and fails on any diff
helm-lintct lint against charts/inventory-storage (pull requests)
arch-testThe hexagonal fitness tests above
webLint, typecheck, test and build of the web/ remote
trivy-scanContainer image scan, blocking on fixable CRITICAL/HIGH (pull requests)
docker-publishGated on lint, complexity, test, bdd, contract, integration, mutation-fast, vuln, api-lint, arch-test, evals-tests; pushes to GHCR on main only
releasemain-only, gated on docker-publish: computes the next vMAJOR.MINOR.PATCH tag and cuts the GitHub release

This documentation site is built and deployed by a separate workflow, .github/workflows/docs.yml, which never touches ci.yml. The matching make targets, test counts and per-layer detail are on Testing.