0032. The analytics consumer's dedupe claim and projection write commit in one transaction
Status
Accepted (2026-10-13). Amends ADR 0012 (its split of "mark once, then retry only the apply"). No migration, no contract change.
Context
kafka.AnalyticsConsumer (cmd/pathmgmt-projector, ADR 0007) dedupes
every CloudEvent on its id in analytics_consumed_events
(ConsumedEventsRepo.MarkProcessed). It then applies the projection
(PostgresProjection.Apply*), which claims the id again in
analytics_processed_events and upserts catalogue_growth_rollup in its own
transaction. handleFetchedMessage ran these as two separate transactions:
markProcessedWithRetry, then applyProjectionWithRetry.
ADR 0012 saw that retrying the whole handler after a successful mark and a
failed apply would see isNew=false and skip the apply. Its fix was to mark
once and retry only the apply. That fix did not cover the process stopping
(SIGTERM, eviction, OOM, crash) after the mark committed and before the
apply committed. The offset is not committed in that case, so Kafka
redelivers the message. Since the clean-shutdown fix (PR #153), Run also
treats the cancellation as a clean stop. But the redelivery's MarkProcessed
returns isNew=false and the apply is skipped. The projection update is
lost, with no error and no dead letter.
The fleet already avoids this. labor-performance's RecordTaskPerformance
runs MarkProcessed and its writes in one UnitOfWork, and
order-management's RepromiseConsumer, which ADR 0012 mirrors, dedupes
inside its use case's single UnitOfWork. This repository's OLTP side has
the same tool: postgres.UnitOfWork carries a pgx.Tx in the context.
Decision
- One analytics transaction. A new
analyticsstore.UnitOfWork(internal/adapters/outbound/analyticsstore/unit_of_work.go) does on the analytical pool whatpostgres.UnitOfWorkdoes on the OLTP pool.Execute(ctx, fn)begins a transaction and carries it in the context under a key private toanalyticsstore, so an OLTP transaction can never be joined by mistake. It deliberately does not useinternal/pgtx: that key binds the OLTP database's transaction, and the analytical database is a separate database with its own pool. It commits only whenfnreturns nil, and a nestedExecutejoins the outer scope. Rollback runs on a context without cancellation, so a shutdown that interruptedfnstill releases the transaction. - The stores join it.
ConsumedEventsRepo.MarkProcessedissues its insert through the context's transaction when one is present.PostgresProjection.inTxuses the context's transaction instead of beginning its own, and the UnitOfWork owns commit and rollback. Outside a UnitOfWork both behave as before. - The consumer claims and applies as one unit.
AnalyticsConsumer.claimAndApplyrunsMarkProcessedand, for a new id, the projection apply insideAtomic.Execute.handleFetchedMessageretries that whole step (jittered backoff 100 ms to 2 s,maxAnalyticsHandlerAttempts= 3). Retrying is now safe because every failed attempt rolled its claim back. This replaces ADR 0012's "mark once, retry only the apply" split, and the dead-letter cause is now prefixedclaim and apply:.NewAnalyticsConsumerandNewAnalyticsConsumerInGrouptake the UnitOfWork, andcmd/pathmgmt-projectorpassesanalyticsstore.NewUnitOfWork(pool). A consumer built without one runs the step directly. That case covers the in-memory store and the test fakes, which have no transaction to share. - DLQ and shutdown rules are unchanged. A message that is not a valid
CloudEvent is dead-lettered at once. An exhausted retry budget is
dead-lettered and committed. Cancellation is never dead-lettered: the
offset stays uncommitted,
Runreturns nil, and the redelivery now applies the event because the interrupted transaction left no claim.
Consequences
- A stop at any point between the claim and the projection write leaves either both rows or neither. The redelivery applies the event exactly once.
- The two idempotency layers (
analytics_consumed_events,analytics_processed_events) now commit together. Both are kept: the projection's own claim still protects a directApply*caller. - One transaction per message instead of two. No new table, env var, topic or metric.
Verification
internal/adapters/inbound/kafka/analytics_atomic_claim_integration_test.go,TestAnalyticsConsumer_CrashBetweenClaimAndApply_RedeliveryAppliesExactlyOnce(testcontainers Kafka and Postgres). The first consumer's projection cancels the run context on its first apply, which simulates the process stopping after the claim. The test asserts that noanalytics_consumed_eventsrow is left. A second consumer in the same group then gets the redelivered message, and the test assertspaths_defined = 1plus exactly one row in each claim table. Before this change it failed on both assertions: the claim row was left behind and the rollup stayed at 0.internal/adapters/outbound/analyticsstore/unit_of_work_integration_test.gochecks three cases. Rollback removes the claim, the projection claim and the rollup row together. Commit keeps all three. A nestedExecutejoins the outer transaction.internal/adapters/inbound/kafka/analytics_consumer_atomic_test.gochecks that the claim and the apply run in the same UnitOfWork scope and that an apply or claim error fails the UnitOfWork.