Skip to main content

Runbook

How inbound-receiving is deployed and operated. Every fact here comes from charts/inbound-receiving, the four cmd/*/main.go composition roots and the adapters they wire. Configuration knobs are listed per binary on Configuration; metrics and logs on Observability; symptom-driven fixes on Troubleshooting.

Deployment​

One container image (Dockerfile) carries every binary under /app (/app/api is the default entrypoint; the other Deployments set command). The Helm chart is charts/inbound-receiving. In the fleet's kind cluster warehouse-infra installs it through Terraform/ArgoCD (warehouse-infra/terraform/locals.tf, values in warehouse-infra/helm-values/inbound-receiving.yaml), with the image side-loaded by kind load docker-image (pullPolicy: IfNotPresent).

Component labelTemplateCommandContainer portServiceEnabled by
apideployment.yaml/app/api8080 (http)<release> ClusterIP :80 → httpalways
mcpmcp-deployment.yaml/app/mcp8090<release>-mcp ClusterIP :8090mcp.enabled (default false)
analytics-projectorprojector-deployment.yaml/app/inbound-projector8091 (admin)none (admin port only)analytics.enabled (default false)
analytics-reportsreports-deployment.yaml/app/inbound-reports8092 (http)<release>-reports ClusterIP :80 → 8092analytics.enabled
frontendfrontend-deployment.yamlnginx-unprivileged8080ClusterIP :80frontend.enabled (default false)

The chart refuses to render (template fail) when database.url and database.existingSecret are both empty, when kafka.brokers or either consumer group is missing, when kafka.enabled is false, when config.eventPublisher or a mode is anything but kafka (also through extraEnv), and when analytics.enabled has no DSN source (ADR 0011).

In the kind cluster warehouse-infra enables everything: eventPublisher: kafka, productMode: kafka with group inbound-receiving-product, dockDoorMode: kafka with group inbound-receiving-dock-doors, kafka.enabled, mcp, analytics (database inbound_receiving_analytics) and the frontend remote.

Edge​

  • REST: Kong exposes the api Service at /api/inbound-receiving (Gateway API httproute.yaml, stripPath: true) on :8000. The ingress.yaml alternative is disabled by default.
  • The httproute/ingress target only the api Service. The MCP and reports Services stay ClusterIP (in-cluster callers only).
  • The frontend remote is served by warehouse-infra's Nginx web gateway at /mfes/inbound-receiving/, never through Kong.
  • There is no authentication on REST, MCP or reports (fleet rule); access control is the in-cluster boundary.

Probes​

ComponentstartupProbelivenessProbereadinessProbe
apiGET /healthz, every 2 s, 30 failures (~60 s window)GET /healthz, 5 s initial, every 10 sGET /readyz, 3 s initial, every 5 s
mcpGET /healthzGET /healthzGET /healthz (no /readyz on this binary)
analytics-projectorGET /healthz on adminGET /healthz on adminGET /readyz on admin
analytics-reportsGET /healthzGET /healthzGET /healthz (no /readyz on this binary)

What readiness means: /readyz (api and projector) starts ready the moment the listener is up and only flips to 503 {"status":"not_ready"} as the first step of graceful shutdown. It does not wait for Kafka, for the consumers to catch up, or for the outbox to drain. Postgres is covered differently: the HTTP listener is only started after migrations and the first ping succeeded, so a pod whose database is unreachable never answers /healthz at all and exits after the boot retry budget (5 attempts, 15 s of backoff).

Graceful shutdown​

cmd/api on SIGTERM: (1) /readyz → 503, (2) wait SHUTDOWN_DRAIN_DELAY (5 s), (3) drain HTTP (10 s cap), (4) stop and await each consumer (10 s cap each), (5) stop and await the outbox relay last (10 s cap), then close the pool. The chart's terminationGracePeriodSeconds: 40 covers the ~35 s worst case. The projector flips /readyz, drains its admin server, lets the in-flight message commit or dead-letter (10 s cap) and closes its pool. The MCP and reports binaries simply drain HTTP (10 s cap).

Databases and migrations​

DatabaseOwner binariesMigrationsTables
OLTP (inbound_receiving in kind)cmd/api (read/write), cmd/mcp (reads)internal/adapters/outbound/postgres/migrations/0001_inbound_receiving.up.sql (+ 0002_housekeeping_indexes.up.sql, sweeper indexes), embeddedasns, asn_lines, appointments, appointment_asns, receipts, receipt_lines, known_skus, dock_doors, outbox_events, processed_events, idempotency_keys
Analytical (inbound_receiving_analytics in kind)cmd/inbound-projector (only writer), cmd/inbound-reports (read-only)analytics/migrations/0001_receiving_performance.up.sql, embeddedanalytics_processed_events, asn_facts, appointment_facts, receipt_facts, receipt_line_events, receipt_discrepancies
  • When migrations run: at process start, before the pool opens, inside bootretry. cmd/api and cmd/mcp both run the OLTP migrations (either may boot first on a fresh database; golang-migrate's advisory lock makes concurrent starts safe). cmd/inbound-projector runs the analytical migrations. cmd/inbound-reports never migrates. There is no separate migration Job.
  • MIGRATIONS_DATABASE_URL: a direct (session-mode) DSN used only for the migration step of cmd/api and cmd/mcp, read from the database Secret key database.migrationsExistingSecretKey (optional: true, falls back to DATABASE_URL). Needed whenever DATABASE_URL points at PgBouncer in transaction mode, which cannot hold the advisory lock. The projector has no such split: ANALYTICS_DATABASE_URL must itself be direct.
  • A migration failure is fatal: after the retry budget the process logs service exited with error with run migrations (after 5 attempts): ... and exits 1; the pod goes into CrashLoopBackOff. golang-migrate leaves a failed migration marked dirty in schema_migrations; fix the cause, then reset the dirty flag by hand before restarting.

Analytics tables​

The analytical database is a projection of warehouse.inbound-receiving.analytics, never a source of truth, and can be rebuilt by replay (see below).

TableOne row perWritten from
analytics_processed_eventsapplied CloudEvents id (with event_type, occurred_at); max(occurred_at) is the freshnessevery applied event, same transaction as its effect
asn_factsASN: expected_arrival, registered_at, cancelled_at, earliest receipt_opened_atASNRegistered, ASNCancelled, ReceiptOpened
appointment_factsappointment: booked_at, checked_in_at, cancelled_at, completed_atthe four retired DockAppointment* events (none produced since ADR 0019; the projector still folds the ones already on the stream, ADR 0022)
receipt_factsreceipt: asn_number, opened_at, closed_atReceiptOpened, ReceiptClosed
receipt_line_eventsReceiptLineReceived (keyed by event id): line, SKU, quantity, Good/DamagedReceiptLineReceived
receipt_discrepancies(receipt, line, kind Short/Over/Damaged) stamped with the close timeReceiptClosed

Every milestone column keeps the earliest event time seen (LEAST), so arrival order does not matter.

Kafka​

One broker platform-wide (in-cluster Bitnami; localhost:9092 from the host). All messages are CloudEvents 1.0 in structured mode (application/cloudevents+json), built and decoded only through internal/adapters/kafka/cloudevents.

TopicDirectionBinaryConsumer groupNotes
warehouse.inbound-receiving.eventsproducedcmd/api (outbox relay)—the 8 integration events (ASNRegistered, ASNCancelled, ReceiptOpened, ReceiptLineReceived, ReceiptCartonReceived, CartonDiscrepancyRaised, ReceiptClosed, ReceiptStowCompleted); key = ASN number (ASN and receipt events). The four legacy DockAppointment* events are no longer raised (ADR 0019) and the republish-appointments command is removed (ADR 0022)
warehouse.inbound-receiving.analyticsproduced and consumedcmd/api produces; cmd/inbound-projector consumesANALYTICS_CONSUMER_GROUP (inbound-receiving-analytics)same 8 events, same id and type as the integration row (the projector folds six of them plus the historical DockAppointment* ones; the two carton types are ignored), dataschema ...:analytics:...
warehouse.inbound-receiving.analytics.dlqproducedcmd/inbound-projector—raw poison message + x-dlq-source-topic, x-dlq-source-partition, x-dlq-source-offset, x-dlq-error, x-dlq-failed-at headers; auto-created on first write
warehouse.product-master.eventsconsumedcmd/api (always on)PRODUCT_CONSUMER_GROUP (inbound-receiving-product in kind), PACKAGING_CONSUMER_GROUPProductRegistered fills known_skus; ProductPackLevelDeclared / ProductPackLevelRetired fill the packaging view
warehouse.facility.eventsconsumedcmd/api (always on)DOCK_DOOR_CONSUMER_GROUP (inbound-receiving-dock-doors in kind)LocationSlotRegistered / LocationSlotDecommissioned maintain dock_doors
warehouse.dock-scheduling.eventsconsumedcmd/api (always on)DOCK_APPOINTMENT_CONSUMER_GROUPDockAppointmentBooked / Cancelled / Rescheduled / DoorReassigned maintain the appointments copy (ADR 0019, ADR 0020)
warehouse.yard-management.eventsconsumedcmd/api (always on)VISIT_ARRIVAL_CONSUMER_GROUPVisitCheckedIn fills visit_arrivals (ADR 0021)
warehouse.inventory.eventsconsumedcmd/api (always on)CARTON_STOW_CONSUMER_GROUPContainerStowed fills carton_stows (ADR 0021)

The local-copy consumers have no DLQ: a message that is not a CloudEvent, has a malformed payload or an invalid value is logged at WARN and committed past; a transient failure retries the same message forever (200 ms doubling to 5 s) and blocks the partition. Their idempotency guard is processed_events with the consumer names product-registry and dock-door-registry.

Outbox relay​

cmd/api runs one relay goroutine (internal/adapters/outbound/outbox/relay.go):

  • every OUTBOX_RELAY_INTERVAL (default 1 s) it claims up to 100 unpublished rows of outbox_events (ORDER BY id ... FOR UPDATE SKIP LOCKED); a full batch is followed immediately by another pass;
  • rows are sent one at a time in id order; each success sets published_at; the first failure stops the pass, increments attempts, stores last_error and is retried on the next pass (head-of-line, so a later event never overtakes an earlier one that is still being retried);
  • attempt cap (ADR 0007): a row that has failed OUTBOX_MAX_ATTEMPTS times (default 20, chart config.outboxMaxAttempts, 0 = unlimited) is no longer claimed. The pass that records the last attempt logs outbox relay: row reached the attempt cap and is excluded from future claims; ... at ERROR with outbox_id, topic, event_type, key, attempts, max_attempts and error. From then on later rows, including rows with the same key, overtake it; the row stays in outbox_events (unpublished, with attempts and last_error) until re-armed (below);
  • EVENT_PUBLISHER=log is a boot error since ADR 0011: no binary marks rows published without writing them to Kafka;
  • every domain event is two rows (integration first, analytics second) sharing one CloudEvents id; (event_id, topic) is unique.

Re-arm a row excluded by the attempt cap​

Find the excluded rows, fix the cause shown in last_error (broker limit, topic, payload), then reset attempts so the next pass claims the row again:

SELECT id, topic, event_type, key, attempts, last_error
FROM outbox_events
WHERE published_at IS NULL AND attempts >= 20; -- 20 = OUTBOX_MAX_ATTEMPTS

UPDATE outbox_events SET attempts = 0 WHERE id = <id>;

The re-armed row is delivered late, with its original CloudEvents id; consumers dedupe on it.

Housekeeping​

Two in-process sweepers bound the append-only tables (ADR 0010, gap fix D24). Each sweeps once at start, then every HOUSEKEEPING_INTERVAL (default 1h), in 1000-row batches:

BinaryTableDeleted whenKnob (default)
cmd/apiidempotency_keyscreated_at older than the TTLIDEMPOTENCY_KEY_TTL (24h)
cmd/apioutbox_eventspublished and published_at older than the retention; unpublished rows (including rows excluded at the attempt cap) are never sweptOUTBOX_RETENTION (168h)
cmd/apiprocessed_eventsprocessed_at older than the retentionPROCESSED_EVENTS_RETENTION (720h)
cmd/inbound-projectoranalytics_processed_eventsoccurred_at older than the retention, except the newest mark (the projection's freshness)PROCESSED_EVENTS_RETENTION (720h)

The chart sets them under config.* (housekeepingInterval, idempotencyKeyTTL, outboxRetention, processedEventsRetention). 0 disables one part; config.housekeepingInterval: "0" disables both sweepers. Keep processedEventsRetention above the consumed topics' retention, or an older redelivery is applied again (harmless: every apply is idempotent). A failed pass logs housekeeping sweep failed (or analytics housekeeping sweep failed) and retries on the next tick; it never affects serving. A pass that deleted rows logs housekeeping sweep with the per-table counts. Several replicas may sweep at once; the bounded DELETEs only ever remove eligible rows. Migration 0002 adds the indexes the sweeps use.

Scaling​

ComponentScalingWhy
apiautoscaling.api HPA (disabled by default; min 1, max 4, 70 % CPU). When enabled the Deployment omits replicas.N>1 is safe: the relay uses FOR UPDATE SKIP LOCKED, aggregate writes are version-guarded (concurrent-modification on conflict), consumers use stable groups and dedupe on the CloudEvents id. Not load-tested.
mcpfixed mcp.replicaCount (1), no HPAthe Streamable HTTP handler keeps per-process session state and the Service has no session affinity
analytics-projectoranalytics.projector.replicaCount (1)one fixed group shares the partitions; writes dedupe on the event id
analytics-reportsanalytics.reports.replicaCount (1)stateless reads

Connection pools (pgxpool, fixed in code): api and mcp MaxConns = 10 with statement_timeout = 5s each; projector MaxConns = 5, 10s; reports MaxConns = 5, 15s, read-only transactions. Size Postgres max_connections for 10 × (api replicas + mcp replicas) + 5 × (projector + reports replicas).

Reports API (cmd/inbound-reports)​

These routes are also described in apis/openapi.yaml (the generated REST reference), but they are served by a different binary: cmd/inbound-reports on :8092 (Service <release>-reports:80), from the analytical database only. The api binary does not serve them, and Kong does not route to them.

GET /reports/receiving-performance​

Query paramFormatDefault
fromRFC 3339 timestampto minus 30 days
toRFC 3339 timestampnow

The range is half-open [from, to) in UTC, must be non-empty and at most 366 days; otherwise 400 problem invalid-report-range. Response 200 (shape from performanceReportDTO in internal/adapters/inbound/http/reports_handler.go; the numbers are illustrative):

{
"from": "2026-09-12T00:00:00Z",
"to": "2026-10-12T00:00:00Z",
"dock_to_stock_target_seconds": 11160,
"days": [
{
"day": "2026-10-11",
"receipts_closed": 3,
"lines_received": 12,
"units_good": 480,
"units_damaged": 4,
"discrepancies": {"short": 1, "over": 0, "damaged": 1},
"receipt_cycle": {"count": 3, "p50_seconds": 5400, "p95_seconds": 9000},
"appointments": {"booked": 4, "checked_in": 3, "cancelled": 1, "completed": 3},
"dock_dwell": {"count": 3, "p50_seconds": 4200, "p95_seconds": 7100},
"dock_to_stock": {"count": 2, "p50_seconds": 9300, "p90_seconds": 12100, "under_target": 1, "share_under_target": 0.5},
"advice": {"count": 3, "within_sla": 3, "share_within_sla": 1},
"asn_timeliness": [
{"supplier_ref": "ACME", "registered": 6, "late": 2, "share_on_time": 0.6666666666666666},
{"supplier_ref": "BOLT", "registered": 3, "late": 0, "share_on_time": 1}
]
}
],
"current": {"open_receipts": 2, "expected_today": 5, "expected_today_started": 3}
}

One days entry per UTC calendar day intersecting the range. p50_seconds / p95_seconds are null when count is 0. current is computed for today's UTC day.

appointments and dock_dwell are frozen since ADR 0019: the appointment moved to dock-scheduling, so nothing new feeds them. dock_to_stock (ADR 0021) is the time from the carrier's gate arrival (yard-management's VisitCheckedIn) to the stow of the last Good carton (inventory-storage's ContainerStowed), counted in the UTC day of that last stow. p50_seconds / p90_seconds are null when count is 0, under_target counts the facts at or under dock_to_stock_target_seconds (11160 s = 3.1 h, WERC best-in-class) and share_under_target is under_target / count (null when count is 0). Walk-in receipts (no appointment arrival) and receipts without cartons have no dock-to-stock and are not counted. The dock_to_stock_facts table is rebuilt by replaying the analytics topic under a new ANALYTICS_CONSUMER_GROUP.

advice (ADR 0023) counts the receiving advices (ReceivingAdviceIssued) issued in the day: count, within_sla (issued inside RECEIVING_ADVICE_SLA, default 24 h, after the last unit received) and share_within_sla (within_sla / count, null when count is 0). The advice_facts table is rebuilt by the same replay. A receipt closed before the advice existed has none.

asn_timeliness (ADR 0025) is the per-supplier KPI "% ASNs received before arrival": registered and late are both counted in the UTC day of the ASN's registered_at (from asn_facts and asn_late_facts, rebuilt by the same replay), share_on_time is 1 - late / registered (null when registered is 0), and the list holds at most the day's top ten suppliers by registered (ties by supplier_ref ascending). An empty day reports [].

Receiving tolerance (ADR 0026)​

POST /receiving-policies declares the tolerance bands of one (ownerRef, supplierRef); GET /receiving-policies/{supplierRef}?ownerRef= reads it (404 receiving-policy-not-found when the exact key has none; an absent ownerRef is the house default, which a client-owned receipt does not fall back to). With a policy, a close or a scan judges each variance:

  • inside the tolerance band: accepted, no finding;
  • between the band and its hard stop: 409 tolerance-override-required until the request carries an overrideReason (supplier-agreed, damaged-in-transit-recounted, mislabelled-recounted, recount-confirmed); the close then records OverTolerance or UnderTolerance with that code;
  • at or beyond the hard stop: 409 tolerance-blocked; the receipt stays open and no override passes.

A receipt closed before a policy existed keeps its old answers. The applied band is on the ReceiptClosed event (tolerance), not on the receipt. The report's per-day tolerance block shows share_without_override, auto_accepted and the top five override reasons. No new environment variable, consumer group or topic.

Receiving advice overdue​

An Open receipt whose last unit was received (or, with none, whose opening) is older than RECEIVING_ADVICE_SLA raises ReceivingAdviceOverdue once, from the housekeeping tick, with a WARN receiving advice overdue and the inbound_receiving.advice.overdue counter. Close the receipt (the advice then goes out with within_sla false) or cancel its ASN; the alarm is not repeated. Detection runs on HOUSEKEEPING_INTERVAL; 0 disables it with the sweeper.

GET /reports/freshness​

200 {"as_of": "<RFC 3339>", "lag_seconds": <number>}: the CloudEvents time of the newest applied event and now - as_of (never negative). Both are null until the projector has applied its first event.

A failed analytical query returns 500 problem report-store-error (the cause is logged, never echoed).

Routine procedures​

Switch a local copy to kafka​

The first start under a new consumer group reads the source topic from the beginning. Readiness does not wait for that replay, so POST /asns / POST /receipts may answer 422 unknown-sku / unknown-appointment until the consumer has caught up (there is no permissive mode any more, ADR 0011).

Re-publish outbox rows​

The relay only reads published_at IS NULL. To re-send rows (for example after a downstream topic was recreated), clear published_at on exactly the rows needed, in id order:

UPDATE outbox_events SET published_at = NULL
WHERE topic = 'warehouse.inbound-receiving.events' AND id >= <first id>;

Consumers dedupe on the CloudEvents id, which is persisted and therefore identical on the re-send.

Rebuild the analytical model (replay)​

The model is a pure projection of warehouse.inbound-receiving.analytics. Either truncate the six analytics tables and reset the group's offsets to earliest, or deploy the projector with a new ANALYTICS_CONSUMER_GROUP (a new group starts at the earliest offset) against an emptied database. Replays are bounded by the topic's retention.

Inspect and replay the analytics DLQ​

Read warehouse.inbound-receiving.analytics.dlq and look at the x-dlq-error header. A DLQ entry is deterministic (bad payload, subject/id mismatch, or a row the analytical store rejects with SQLSTATE class 22/23); fix the producer or the projection, then re-produce the original value to warehouse.inbound-receiving.analytics. Re-applying an id that was already applied is a no-op.

Rotate database credentials​

The DSNs come from Secrets (database.existingSecret keys DATABASE_URL and MIGRATIONS_DATABASE_URL; analytics Secret keys ANALYTICS_DATABASE_URL and ANALYTICS_READER_DATABASE_URL). The binaries read them only at start: update the Secret, then kubectl rollout restart the affected Deployments. In kind the passwords are generated by Terraform (random_password.service_db).

Reset a stuck consumer​

A local-copy consumer that keeps failing transiently on one message logs ... handling failed; retrying the same message at ERROR on every attempt. Fix the dependency (usually Postgres); the consumer resumes on its own. Do not skip the offset unless the message is confirmed irrelevant; then use kafka-consumer-groups.sh --reset-offsets --to-offset <n+1> for that group and partition while cmd/api is scaled to zero.