Planning for implementation
I need to include guidelines for poller versus CDC, and for Kotlin, I think showing some pseudocode will be useful. The user asked for coaching on implementation, so I’ll create a detailed plan and structure my response with clear headings: architecture, schemas, producer, consumer, retries, end-of-stream (EOS), observability, and disaster recovery tests. I should also include some concrete SQL examples. Interestingly, although security wasn't requested, it might be worth mentioning briefly too. Let's move forward!
1) Target behavior (what you’re building)
- Atomic “business change + intent to publish” in your service DB (outbox row is written in the same DB transaction as your domain updates).
- Asynchronous publish from outbox → Kafka (at-least-once publish).
- Idempotent consumers so duplicates don’t cause duplicate side effects (effective-once end-to-end).
This is the standard way to get “exactly-once-ish” behavior when you have a DB + Kafka boundary.
2) Outbox schema design (DB)
2.1 Minimal, production-ready Outbox table
Use a single table per service DB. Store enough metadata to:
- route/partition correctly,
- re-publish safely,
- observe lag and failures,
- trace across services.
Postgres example:
create table outbox_event (
id uuid primary key, -- event_id (global unique)
aggregate_type text not null,
aggregate_id text not null,
event_type text not null, -- e.g., OrderCreated
event_version int not null default 1, -- schema version
partition_key text not null, -- used as Kafka key
payload jsonb not null, -- or bytea for protobuf/avro
headers jsonb not null default '{}'::jsonb, -- trace ids, etc.
created_at timestamptz not null default now(),
status text not null default 'NEW', -- NEW, IN_FLIGHT, PUBLISHED, FAILED
publish_attempts int not null default 0,
next_attempt_at timestamptz not null default now(),
last_error text null,
published_at timestamptz null
);
create index outbox_event_poll_idx
on outbox_event (status, next_attempt_at, created_at);
create index outbox_event_aggregate_idx
on outbox_event (aggregate_type, aggregate_id, created_at);
Key points
id is the dedup key across the whole system.
partition_key should usually be aggregate_id to preserve ordering per aggregate.
event_version helps consumers handle schema evolution.
status + next_attempt_at supports backoff without external schedulers.
2.2 Transactional write pattern
In your application service method, do:
- Begin DB tx
- Update domain tables
- Insert outbox_event row
- Commit
If the business transaction commits, the event exists and will be published eventually.
3) Publishing from Outbox to Kafka
3.1 Publisher options (pick one)
Option A: Polling publisher (simplest)
- A background worker queries
NEW/FAILED rows with next_attempt_at <= now().
- It publishes to Kafka.
- It marks rows
PUBLISHED after send success.
Option B: CDC (Debezium) transactional outbox
- Debezium tails the DB WAL and publishes outbox rows.
- Less custom code, great operationally, but adds CDC infra and constraints on schema.
If you’re coaching a team new to this, start with polling, then migrate to Debezium if scale/latency warrants.
3.2 Safe polling (avoid double-publish from multiple workers)
Use row-level locking to claim work:
with cte as (
select id
from outbox_event
where status in ('NEW','FAILED')
and next_attempt_at <= now()
order by created_at
limit 100
for update skip locked
)
update outbox_event e
set status = 'IN_FLIGHT'
from cte
where e.id = cte.id
returning e.*;
Then publish those returned rows.
3.3 Kafka producer config
Turn on idempotent producer:
enable.idempotence=true
acks=all
retries high
max.in.flight.requests.per.connection=5 (Kafka default with idempotence is safe; avoid increasing in ways that break ordering guarantees)
Important: producer idempotence prevents duplicates due to producer retries to Kafka, but it does not solve DB↔Kafka atomicity. Keep outbox anyway.
3.4 Marking as published
After successful publish, update:
update outbox_event
set status='PUBLISHED', published_at=now()
where id = :id;
If publish fails:
- increment
publish_attempts
- set
status='FAILED'
- set
next_attempt_at using backoff
- store
last_error
4) Dedup keys and idempotent consumers (“Inbox pattern”)
4.1 What to dedup on
Use event_id (outbox_event.id) as the canonical deduplication identifier.
- Put it into Kafka message as either:
- Kafka header:
event_id
- and/or payload field:
eventId
Also include:
aggregate_id, event_type, event_version, occurred_at, trace_id
4.2 Consumer-side Inbox table
Each consumer service that has side effects should persist which events it already processed.
create table inbox_event (
consumer_name text not null, -- identify the consuming component
event_id uuid not null,
received_at timestamptz not null default now(),
processed_at timestamptz null,
topic text null,
partition int null,
offset bigint null,
primary key (consumer_name, event_id)
);
4.3 Consumer processing algorithm (the important part)
For each Kafka record:
- Begin DB tx
- Insert into
inbox_event(consumer_name, event_id, …)
- If insert fails due to PK conflict → duplicate → safely skip side effects
- Apply side effects (update your DB, call downstream if you have idempotency there too, etc.)
- Mark inbox row
processed_at=now()
- Commit DB tx
- Commit Kafka offset after DB commit
This gives effective-once behavior for DB side effects.
Notes
- If you must call an external API, you need that call to be idempotent too (idempotency key =
event_id) or you need an outbox for that integration as well.
4.4 TTL / cleanup
Inbox grows forever if you never delete. Pick:
- time-based retention (e.g., 7–30 days), but only if you will never replay older Kafka offsets in normal ops
- or keep forever (costly)
- or retain based on topic retention + maximum replay horizon
A common compromise: keep inbox rows for > max Kafka retention or > max “reprocess window”.
5) Retry/backoff strategy (publisher + consumers)
5.1 Outbox publisher backoff
Use exponential backoff with jitter:
- attempt 1: immediately
- attempt 2: 1s
- attempt 3: 5s
- attempt 4: 30s
- attempt 5+: cap at e.g. 5–15 minutes
- add jitter ±20%
Persist next_attempt_at and publish_attempts in outbox row.
After N attempts:
- mark
FAILED_PERMANENT
- alert
- optionally write to a “dead-letter outbox” table for manual repair
5.2 Consumer retries
Avoid blocking the main consumer loop with long retries.
Typical patterns:
- Retry topics (recommended):
topic.retry.1m, topic.retry.10m, topic.dlt
- On transient failure, publish to next retry topic with a delay mechanism (Kafka tiered approach or a scheduler/consumer that waits until due).
- Or pause partition + seek (simple but can stall throughput).
- Or store failed events in DB and have a separate reprocessor.
Also separate:
- Transient (timeouts, 5xx): retry with backoff
- Permanent (validation error): DLT immediately
6) Exactly-once semantics: realistic tradeoffs
6.1 What Kafka EOS does and doesn’t do
Kafka “Exactly Once Semantics” (transactions) can guarantee exactly-once within Kafka for read-process-write pipelines (e.g., Kafka Streams, or consuming and producing to Kafka with transactions).
It does not magically make “Kafka + relational DB update” exactly-once.
6.2 Recommended stance for microservices with DB
- Use Outbox for producer side atomicity with DB.
- Use Inbox/idempotent consumer for side effects.
- Accept Kafka delivery as at-least-once, and make processing idempotent.
This is the most robust operationally.
6.3 When to consider Kafka transactions anyway
- If your consumer only writes to Kafka (no DB side effects), transactions can give you true EOS.
- If you do DB writes, transactions still don’t cover the DB, but can reduce duplicate downstream messages.
7) Observability (you’ll want this on day 1)
7.1 Outbox metrics (publisher)
Track:
- outbox.pending.count: rows with status NEW/FAILED
- outbox.oldest.age.seconds:
now - min(created_at where not published)
- outbox.publish.rate: events/sec
- outbox.publish.failures: counter by exception type
- outbox.attempts.distribution: histogram
- outbox.in_flight.stuck.count: IN_FLIGHT older than threshold (crash recovery bug)
Alert examples:
- oldest age > SLO (e.g., 5 minutes)
- failure rate > threshold
- pending count growing for N minutes
7.2 Consumer metrics
- Kafka consumer lag per partition (standard)
- processing latency histogram
- dedup.hit.count (inbox PK conflicts)
- retry counts (by transient/permanent)
- DLT counts
7.3 Tracing + correlation
Propagate these in headers:
traceparent (W3C), tracestate
event_id
aggregate_id
causation_id (the event that triggered this event)
correlation_id (end-to-end business flow)
Log structured fields for all the above.
8) Disaster recovery & failure-mode tests (what to actually run)
Build a test matrix that proves you tolerate duplicates, reordering (where allowed), and outages.
8.1 Producer/outbox failure tests
-
DB commit succeeds, Kafka down
- Expect: outbox row remains NEW/FAILED, eventually published after Kafka returns
- Verify: no missing events, and no permanent stuck IN_FLIGHT
-
Kafka publish succeeds, DB update to PUBLISHED fails
- Expect: outbox row stays FAILED/IN_FLIGHT → it may republish → duplicates possible
- Verify: consumers dedup successfully
-
Publisher crashes mid-batch
- Expect: some rows IN_FLIGHT; they must be reclaimed
- Implement: a lease timeout (“IN_FLIGHT older than X → back to FAILED”)
- Verify: no starvation and eventual publish
8.2 Consumer failure tests
-
Consumer processes DB side effect, crashes before committing Kafka offset
- Expect: message redelivered
- Verify: inbox dedup prevents double side effect
-
Consumer commits offset before DB commit (anti-test)
- Demonstrate data loss possibility; ensure your implementation avoids this ordering
-
Retry storms
- Inject transient failures (e.g., 30% timeouts)
- Verify: retry topics/backoff prevent hot-looping and keep main topic moving
-
Reprocessing / replay
- Reset consumer group offsets to earliest (in staging)
- Verify: idempotency holds; inbox storage and retention policy support this
8.3 Data correctness / ordering tests
-
Ordering per aggregate
- Produce multiple events for same aggregate
- Verify they are keyed by
partition_key=aggregate_id, and consumer logic handles ordering assumptions correctly
-
Schema evolution
- Publish event_version=2 while some consumers still on v1
- Verify: compatibility strategy works (ignore unknown fields, default values, etc.)
8.4 Infra DR tests
-
Kafka broker outage / partition leader changes
- Verify publisher retries behave; consumer group rebalances don’t break correctness
-
DB failover / read replica promotion
- Verify publisher uses correct DB endpoint and no duplicate claiming behavior across instances
9) Practical implementation checklist (so you can execute)
Producer service
Consumer service
If you tell me:
- your DB (Postgres/MySQL/etc.),
- whether you can use Debezium,
- your consumer tech (Spring Kafka, Kafka Streams, Node, Go, etc.),
- whether consumers do external API calls,
…I can tailor the exact schema types, retry topic topology, and the transaction/offset-commit code skeleton for your stack.