0004. Kafka and a shared envelope for integration events
Status
Superseded by ADR-0024 for
the envelope: the flat event_id / event_type / occurred_at / source /
data wrapper described below is retired, and every message is now a
CloudEvents 1.0 structured-mode event. Kafka as the transport and the
additive-adapter decision still stand. Originally accepted. Introduced as a strictly additive change (Task 7, commit "Task 7:
cross-service Kafka integration (additive)"). The CloudEvents type
convention was formalised later, alongside apis/asyncapi.yaml.
Context
wes-work-planning — the WES-tier conductor — needs stock reality to plan and
release work. It needs to know when usable inventory for a SKU goes down
(something was reserved) and when it comes back up (a reservation was revoked).
Three options were on the table:
- Give it database access. Fastest to build, and immediately fatal to the
bounded-context boundary:
warehouse-systems-ddd.mdrequires that "WES does not get write access to WMS's Order/Inventory aggregates — only to the published events/API." Read access is barely better — it couples Work Planning to this service's schema and turns every migration into a cross-repository breaking change. - Have it poll
GET /inventory/{sku}/usable. Correct but wasteful and laggy: the conductor would have to poll every SKU it cares about, and would learn about a revoke only on the next tick. - Publish integration events. This service states facts; anyone interested subscribes. The publisher does not need to know who is listening, which is what makes it an Open Host Service rather than a point-to-point integration.
The service already had a ports.EventPublisher port with log, buffered and
Postgres implementations, and every use case already published past-tense
domain events through it. The gap was purely transport.
Constraints that shaped the shape of the answer:
- The existing test suite must be unaffected. Requiring a broker for
go test ./...would be a serious regression. - The envelope must be identical across all five services. Five slightly different envelopes would push translation into every consumer.
- One shared broker. It runs from
~/warehouse-systems/docker-compose.kafka.yml; this repo must connect to it, not stand up a competing one. - Not everything is integration. Ten domain events exist; only two are of cross-context interest. Publishing all ten would expose internal model detail as a public contract.
Decision
We will publish integration events to Kafka from a new outbound adapter
behind the existing EventPublisher port, selected by environment variable,
using a platform-wide envelope.
- Client library:
github.com/segmentio/kafka-go— pure Go, no cgo. - Topic:
warehouse.inventory.events, one per bounded context, matching the platform'swarehouse.<context>.eventsnaming. - New package
internal/adapters/outbound/kafka/implementing the existingports.EventPublisher. No aggregate, invariant or use case changed. - Selected by env:
EVENT_PUBLISHER=kafka|log, defaulting tolog, so the existing suite and local runs need no broker. Brokers come fromKAFKA_BROKERS(defaultlocalhost:9092). - Publish exactly two events —
StockReservedandReservationRevoked— both withdata: {sku, quantity, demand_ref}. Everything else hits the adapter'sdefault: return nilbranch and stays in-process. ReservationRevokedis enriched in the adapter. The domain event carries only a reservation id; the adapter looks the reservation up throughports.ReservationRepoto fill insku/quantity/demand_ref. Enrichment for a consumer's convenience is an adapter concern — putting those fields on the domain event to save a lookup would let an integration requirement leak into the domain model.- The
typeconvention is platform-wide:com.warehouse.<subdomain>.<bounded-context>.<entity>.<EventName>— all lowercase except the final PascalCase name. Here the subdomain segment iswmsand the entity segment is the aggregate:stock,reservation,bin. - The contract is a checked-in, linted artefact:
apis/asyncapi.yaml(AsyncAPI 2.6.0), Spectral-linted by theapi-lintCI job, documenting the complete catalog and marking each catalog-only message explicitly.
Consequences
Easier
- The boundary holds. Work Planning gets stock reality without schema access and without write access.
- Additive, reversible.
EVENT_PUBLISHER=logrestores the previous behaviour exactly. The Kafka work touched no domain code. - Testable without a broker.
Writeris a one-method interface, sopublisher_test.goasserts the exact envelope against an in-memory fake and runs in the default suite. - New consumers cost this repo nothing. A sixth service subscribes from the published spec; no change here.
- A small public surface. Two events, not ten — the internal model can evolve freely.
Harder
- At-least-once delivery is now every consumer's problem. Consumers must
deduplicate;
wes-work-planningdoes so with aprocessed_eventstable keyed by event id. - No ordering guarantee (as originally accepted; superseded by
ADR-0021: messages are now keyed
by reservation id and routed by
Hash, giving per-reservation ordering). TheLeastBytesbalancer with no partition key meant no per-SKU ordering. Acceptable for an increment/decrement projection, but it is why the REST read remains authoritative. - Publish failures fail the request.
Publisherrors propagate out of the use case, so a broker outage surfaces as a500. That is the honest behaviour for now, but it couples request success to broker availability — a transactional outbox would decouple them and is not built. - Two envelopes coexist. The adapter emits the legacy flat envelope
(
event_id/event_type/occurred_at/source/data), while the AsyncAPI document describes the CloudEvents target the platform is moving to. Thedatapayloads match field-for-field; the context attributes do not. Documented explicitly inapis/asyncapi.yamland on the Events page rather than hidden — migrating the adapter is outstanding work. - The
ReservationRevokedenrichment needs a repo read at publish time, which is an extra query and a failure mode (ErrReservationNotFound) that would not exist if the payload came straight off the event.
Verification
Unit-tested against an in-memory Writer fake, and smoke-tested for real: with
the shared broker running and EVENT_PUBLISHER=kafka, a live
POST /reservations against the running binary was confirmed to land on
warehouse.inventory.events via a console consumer before the task was
considered done.