Creating design guidance
I'm working on design guidance that includes architecture components, flows, and patterns. I need to focus on achieving exactly-once semantics with effective-once delivery while ensuring idempotent consumers. I'll cover producer-side outbox/transactional messaging and consumer-side idempotent processing with a deduplication store. I want to mention Kafka, SQS, and Pulsar, and also discuss handling retries, DLQs, and poison messages. Observability will be critical, so I’ll include tracing, metrics, logging, and correlation IDs. It sounds like a lot to cover, and I'll ensure to provide clear examples and diagrams.Drafting architecture recommendations
I need to provide recommendations for replay, retention, and compaction while also addressing failure modes. It’s important to balance conciseness with thorough coverage. I’ll create a clear blueprint that includes components, message format, producer and consumer flows, and retry logic. Pseudocode will involve SQL tables, transaction boundaries, and consumer logic, incorporating observability measures like OpenTelemetry for trace context propagation. I want to ensure idempotency and deduplication while designing effective replay strategies, observing the exact-once semantics challenge. I need to organize everything into sections for clarity!Creating schema and pseudocode
I’m focused on including a concrete example of the outbox and inbox schema, along with processing pseudocode. It’s essential to ensure exactly-once semantics across multiple services, especially for consumers using the inbox pattern. This is crucial for maintaining message integrity and minimizing duplicates. I’ll draft this carefully so it's clear and effective, illustrating how the flows and patterns work in practice. I want to make sure it’s practical and easy to understand!
Below is a practical “exactly-once” (more precisely: effectively-once) event-driven architecture. It assumes the broker delivers at-least-once and you achieve “exactly-once effects” via idempotency + deduplication + transactional outbox/inbox + disciplined retries + observability.
1) Core principles (what “exactly-once” means here)
Goal: Each business event causes its intended side effects once, even if:
- the producer retries publishing,
- the broker redelivers,
- consumers crash mid-processing,
- handlers time out and retry.
How:
- Unique event identity (eventId) and idempotency keys.
- Atomic local transactions: write business state + (outbox/inbox) markers together.
- Deduplicate at consumers using a “processed events” store keyed by
(consumer, eventId) (or (handler, idempotencyKey)).
- Retries + DLQ are explicit and observable.
- End-to-end traceability with correlation/causation IDs and metrics.
2) Event contract (required metadata)
Every event must include (headers or payload):
eventId (UUID/ULID) — globally unique per event instance.
eventType (string) — e.g., OrderPlaced.v1.
aggregateId (string) — entity ID; also used for partitioning/ordering.
aggregateVersion (int) — optional; helps enforce ordering/optimistic checks.
occurredAt (timestamp)
producer (service name/version)
correlationId — ties together a business transaction across services.
causationId — points to the event/command that caused this event.
idempotencyKey — stable key for the business operation (often equals commandId).
traceparent (W3C) / OTel context — for distributed tracing.
schemaVersion — for evolution.
Recommendation: keep eventId unique per publish attempt and keep idempotencyKey stable per business operation. This lets you dedupe “same business operation published twice” even if event IDs differ.
3) Producer side: Transactional Outbox Pattern (no lost/duplicate publishes)
3.1 Data model (in producer’s database)
Business tables (example):
Outbox table (same DB):
CREATE TABLE outbox (
outbox_id bigserial PRIMARY KEY,
event_id uuid NOT NULL,
idempotency_key text NOT NULL,
aggregate_id text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
headers jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz,
publish_attempts int NOT NULL DEFAULT 0,
status text NOT NULL DEFAULT 'PENDING',
UNIQUE (idempotency_key, event_type) -- or a business-appropriate uniqueness constraint
);
3.2 Write flow (single local DB transaction)
When handling a command (e.g., “PlaceOrder”):
- Validate + write business state to
orders.
- Insert event row into
outbox.
- Commit.
This guarantees: business change and “intent to publish” are atomic.
3.3 Publish flow (Outbox dispatcher)
A separate component publishes pending outbox rows to the broker:
- Option A: Poller (periodic query on
outbox where status='PENDING').
- Option B (preferred at scale): CDC (e.g., Debezium reads outbox inserts and publishes to Kafka).
Dispatcher logic:
- Fetch a batch with row locking (
FOR UPDATE SKIP LOCKED).
- Publish to broker with
eventId and idempotencyKey in headers.
- Mark row as
published_at=now(), status='PUBLISHED'.
Important: Publishing may be duplicated if dispatcher crashes after publish but before marking published. That’s fine—consumers will dedupe.
3.4 Broker-level exactly-once (optional enhancement)
If using Kafka, you can also use idempotent producer + transactions to reduce duplicates at the broker level. Still keep consumer idempotency; it’s your true safety net.
4) Transport: topics/streams, partitioning, ordering
- Partition key =
aggregateId to preserve order per aggregate.
- Retention long enough to allow replay/backfill.
- Consider log compaction for certain event types (not a replacement for dedupe).
5) Consumer side: Idempotent handler + Dedup store (+ optional Inbox)
Consumers must assume at-least-once delivery.
5.1 Minimum: “processed events” dedup table
Per consumer service, store processed markers:
CREATE TABLE processed_events (
consumer_name text NOT NULL,
event_id uuid NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer_name, event_id)
);
Consumer processing algorithm (single DB transaction):
- Begin transaction.
- Attempt
INSERT INTO processed_events(...) VALUES (...).
- If it fails (PK conflict), already processed → ACK message and exit.
- Perform side effects (write DB state, call downstream, etc.).
- Commit.
- ACK message.
This is the key: dedup insert + side effects are atomic.
5.2 When side effects include publishing new events
Use Outbox on the consumer too (any service that publishes events should use outbox).
So in the consumer’s transaction:
- apply state changes
- insert next events into its outbox
- commit
Then its dispatcher publishes.
5.3 Inbox pattern (optional but useful)
Instead of only processed_events, you can store the full incoming message in an inbox table (good for audit/replay/debugging). The dedup key is still (consumer, eventId) or (consumer, idempotencyKey).
5.4 Idempotent external calls
If you must call an external HTTP API:
- Prefer APIs that accept an Idempotency-Key header.
- Store your call result keyed by
(provider, idempotencyKey) to avoid double-charging, double-creating, etc.
- If the provider is not idempotent, wrap it with your own idempotent façade (or use a saga/compensation design).
6) Retry strategy, poison messages, and DLQs
6.1 Classify failures
-
Transient (timeouts, temporary DB lock, 503)
→ retry with backoff.
-
Permanent (schema mismatch, validation failure, missing referenced entity that will never exist)
→ DLQ immediately or after limited retries.
-
Poison (always crashes handler due to bug/data)
→ DLQ with enough context to reproduce.
6.2 Recommended retry pipeline
- Immediate retries: small count (e.g., 3) with exponential backoff + jitter.
- Delayed retries: re-enqueue to a “retry topic/queue” with scheduled delay (or broker-native delay).
- DLQ: after max attempts or permanent errors.
Headers to maintain:
deliveryAttempt
firstSeenAt
lastErrorType, lastErrorMessage (bounded)
originalTopic, originalPartition, originalOffset (Kafka)
correlationId, eventId, idempotencyKey
6.3 DLQ handling
Provide a DLQ consumer/tooling to:
- inspect messages,
- fix data or deploy a bugfix,
- replay to original topic (with a new wrapper envelope) without breaking dedupe.
Important: replay should preserve the original eventId (or preserve idempotencyKey) so dedupe still works.
7) Observability (you can’t prove exactly-once without it)
7.1 Structured logging (per event)
Log at least:
eventId, eventType
aggregateId
correlationId, causationId
idempotencyKey
consumerName, handler name
- attempt count, latency, outcome (processed/deduped/retried/dlq)
7.2 Metrics (SLO-driven)
Per topic/consumer:
events_received_total
events_processed_total
events_deduped_total
processing_latency_ms (p50/p95/p99)
retry_total and dlq_total
outbox_pending_count, outbox_publish_latency_ms, outbox_publish_failures_total
- broker lag (Kafka consumer lag), queue depth (SQS)
Alert on:
- DLQ rate > threshold
- rising dedupe rate (often indicates producer/publisher issue)
- outbox pending grows (dispatcher stuck)
- consumer lag breaches SLO
7.3 Distributed tracing
Use OpenTelemetry:
- propagate trace context in message headers (
traceparent).
- create spans for:
- command handling → outbox insert
- outbox publish
- consumer receive → dedupe check → side effects → outbox insert
- retries and DLQ publishes
7.4 Auditability
If needed (regulated domains):
- store immutable event envelope (inbox or event store),
- record who/what triggered the operation (from causation/correlation),
- provide deterministic replay.
8) End-to-end flow (text sequence)
Producer Service A
- Handle command
C with idempotencyKey=K.
- DB tx: write state + insert outbox(eventId=E1, K).
- Dispatcher publishes E1 (maybe twice due to crash).
Broker
- Delivers E1 to Service B at least once.
Consumer Service B
- Receive E1.
- DB tx:
- insert
processed_events(B, E1); if conflict → ACK (dedup).
- apply state changes.
- insert outbox for any downstream events.
- Commit; ACK.
- Downstream publish happens via B’s outbox dispatcher (safe on crash).
Result: even with duplicates/redelivery, the side effects in B occur once.
9) Key implementation choices / gotchas
- Choose dedup key intentionally:
- If you want “exactly-once per emitted event,” key by
eventId.
- If you want “exactly-once per business operation,” key by
idempotencyKey (+ eventType).
- Dedup storage TTL: if you expire processed markers, replays may re-trigger effects. Keep long enough for your replay window (often weeks/months), or never expire for critical operations.
- Consumer concurrency: ensure handlers for same aggregate are serialized if required (partitioning + single-thread per partition, or DB optimistic concurrency with
aggregateVersion).
- Schema evolution: use a schema registry + compatibility rules; DLQ often spikes due to schema mismatches.
- Avoid cross-service distributed transactions: keep transactions local; coordinate with events (sagas/process managers) if needed.
If you share your constraints (Kafka vs SQS/PubSub, relational DB vs DynamoDB, throughput, ordering requirements), I can tailor the exact table schemas, retry topology (topics/queues), and the consumer transaction boundaries for your stack.