Considering ordering techniques
I'm thinking about ordering strategies like per key and partitioning, which can have some pitfalls to consider. SQS FIFO groups and Kafka partitions come to mind for ensuring global ordering, though that's rare. I'm also comparing DLQs against parking lot queues and redrive strategies. Some examples I might reference are log ingestion and order processing using an outbox pattern. It would be useful to provide message schemas and consider their evolution too.
1) Topics vs queues (and when to use which)
Queue (point-to-point)
- Semantics: each message is processed by one consumer (competing consumers).
- Use when: work distribution, task processing, RPC-ish async jobs (image resize, email send).
- Examples: RabbitMQ queue, SQS standard/FIFO queue.
Topic / pub-sub
- Semantics: each message is delivered to all subscribed consumer groups (each group gets a copy).
- Use when: event-driven architectures, audit trails, multiple downstream consumers (fraud + analytics + fulfillment).
- Examples: Kafka topic, SNS topic (fanout), Pulsar topic.
Common mapping
- Kafka “topic + consumer groups” ≈ pub/sub (each group is like an independent subscription).
- SNS topic + SQS queues ≈ pub/sub fanout, with queue semantics per subscriber.
2) Delivery semantics: at-most / at-least / exactly-once
At-most-once
- What: message may be lost, but never duplicated.
- How it happens: consumer commits/acks before processing; producer doesn’t retry.
- Use when: low-value telemetry, sampling.
At-least-once (most common)
- What: message won’t be lost (assuming infra durability), but may be delivered more than once.
- Cause of duplicates: consumer crashes after processing but before ack/commit; producer retries after timeout.
- Requirement: make handlers idempotent (see §3).
Exactly-once (hard end-to-end)
- “Exactly once” is usually achievable only within a bounded system (same broker + same storage with transactions), and even then it’s often “exactly-once processing” not “exactly-once effects everywhere”.
- Practical approach: effectively-once = at-least-once delivery + idempotent effects + dedup.
Platform notes
- Kafka: can do exactly-once between Kafka and a transactional sink/consumer using idempotent producer + transactions (EOS) but you still must design downstream side-effects carefully.
- SQS FIFO: can do deduplication within a time window using MessageDeduplicationId, but consumers still need idempotency.
- RabbitMQ: typically at-least-once; exactly-once requires application-level dedup/idempotency.
3) Idempotency (the non-negotiable for at-least-once)
Goal
Processing the same message multiple times produces the same final state as processing it once.
Common strategies
-
Idempotency key + dedup store
- Message includes a unique key (e.g.,
eventId or commandId).
- Consumer writes
eventId to a table with a unique constraint.
- If insert fails (already processed), skip side effects.
SQL sketch
CREATE TABLE processed_events (
event_id TEXT PRIMARY KEY,
processed_at TIMESTAMP NOT NULL DEFAULT now()
);
-
Idempotent writes
- Use deterministic identifiers and upserts.
- Example:
INSERT ... ON CONFLICT DO NOTHING/UPDATE.
-
Business-key idempotency
- “CreateOrder” keyed by
orderId (client-generated UUID).
- Second delivery sees
orderId exists → no-op.
-
Idempotency at external boundaries
- Payment provider: pass an Idempotency-Key header.
- Email: store “sent receipt for orderId” state.
Example consumer pseudocode (dedup + transactional write)
def handle(msg):
with db.transaction():
# 1) dedup gate
if not db.insert_if_absent("processed_events", event_id=msg.eventId):
return # duplicate delivery
# 2) apply state change
db.upsert("orders", id=msg.orderId, status="PAID")
# 3) ack only after commit
broker.ack(msg)
4) Ordering guarantees (and how to preserve them)
Reality check
- Global ordering across all messages rarely scales.
- Most brokers provide ordering within a partition / FIFO group / single queue.
Patterns
-
Partition by key (Kafka/Pulsar)
- Choose a key like
orderId so all events for one order go to the same partition.
- Guarantees order per key, enables parallelism across keys.
-
FIFO queues with message group id (SQS FIFO)
- Set
MessageGroupId = orderId for per-order ordering.
-
Sequence numbers + reordering buffer (application-level)
- When strict order is required but delivery is out-of-order, include
sequence and buffer until gaps fill.
- Risk: head-of-line blocking; needs timeouts/compaction logic.
Avoid
- Assuming “publish order == consume order” across multiple partitions/consumers.
- Designing workflows that require cross-entity global ordering.
5) Retries, backoff, and poison messages
Types of failures
- Transient: network hiccup, DB deadlock, downstream 503 → retry.
- Permanent: schema invalid, missing required entity, logic bug → don’t infinite-retry.
Retry techniques
-
Immediate retry (small count)
- For very short glitches; keep small to avoid hot loops.
-
Exponential backoff + jitter
- Typical: 1s, 2s, 4s, 8s… capped (e.g., 2–5 minutes).
- Add jitter to avoid thundering herds.
-
Delayed retries via retry topic/queue
- Route failed messages to
topic.retry.1m, topic.retry.10m, etc.
- Or use broker-native delay (if supported).
-
Max attempts + DLQ
- After N attempts, send to DLQ with failure metadata.
What to include in retry/DLQ metadata
attempt, firstSeenAt, lastError, stackTraceHash, consumerVersion, originalTopic, originalOffset/messageId.
6) Dead-letter queues (DLQs) and “parking lot” flows
DLQ purpose
Quarantine messages that can’t be processed automatically so they don’t block the stream.
Recommended DLQ design
- Separate DLQ per source topic or per bounded context:
- Preserve original payload + headers + failure reason.
- Provide a re-drive mechanism:
- Fix bug/data → replay from DLQ back to original topic (optionally after transformation).
Operational rule
- DLQ depth > 0 should page someone if it keeps growing or crosses threshold.
- Don’t silently accumulate DLQ forever; treat it as an incident queue.
7) Exactly-once patterns in practice (effective designs)
A) Transactional Outbox (reliable publish)
Problem: DB updated but event not published (or published but DB not updated).
Pattern:
- In the same DB transaction that changes state, insert an outbox row.
- A relay process reads outbox rows and publishes to broker.
- Mark outbox row as sent (or delete) when broker acked.
Example (Order service)
- Transaction:
orders.status = PAID
outbox(eventId, type=OrderPaid, payload=...)
This achieves atomic state + event without distributed transactions.
B) Transactional Inbox (reliable consume)
Problem: message processed but ack fails → redelivery → duplicates.
Pattern:
- Store
eventId in an inbox/processed table inside the same transaction as side effects.
- Ack only after commit (see §3 pseudocode).
C) Kafka EOS (bounded exactly-once)
- Use Kafka transactions to:
- Consume from topic(s)
- Produce to output topic(s)
- Commit offsets
- Still treat external calls (email/payment) as needing idempotency keys.
8) Schema evolution (so producers and consumers can change independently)
Rules of thumb
- Prefer backward compatibility (new consumers can read old messages) and/or forward compatibility depending on rollout strategy.
- Avoid “flag day” deployments requiring producer+consumer simultaneous upgrade.
Best practices
- Use a schema system
- Avro/Protobuf + schema registry (Kafka ecosystems) or versioned JSON schema.
- Version schemas explicitly
- Embed
schemaVersion or rely on registry id.
- Make additive changes
- Add optional fields with defaults.
- Don’t rename/remove fields; deprecate then remove later.
- Handle unknown fields
- Consumers ignore fields they don’t understand.
- Upcasting/downcasting
- Consumer translates old versions to internal canonical model.
Example evolution
v1
{ "eventId":"...", "type":"OrderCreated", "orderId":"...", "totalCents":1234 }
v2 (add currency, optional)
{ "eventId":"...", "type":"OrderCreated", "orderId":"...", "totalCents":1234, "currency":"USD" }
- v1 consumers ignore
currency.
- v2 consumers default
currency=USD if missing.
9) Monitoring & alerting (what to measure)
Broker-level
- Backlog / consumer lag
- Kafka: consumer group lag per partition.
- SQS: ApproximateNumberOfMessagesVisible/NotVisible.
- Throughput
- Publish/consume error rates
- Age of oldest message (great SLO signal)
Consumer-level (business + reliability)
- Processing latency
- time from
event.createdAt to completion.
- Retry counts and retry rate
- DLQ rate and DLQ depth
- Poison message fingerprints
- group by
stackTraceHash or validation error code.
- Idempotency/dedup hits
- high duplicate rate indicates ack/timeout tuning issues.
Tracing and correlation
- Include
correlationId, causationId, eventId, orderId.
- Propagate trace headers (W3C traceparent) across publish/consume boundaries.
Alerts (typical)
- Lag/backlog growing for > X minutes.
- DLQ growing or DLQ rate above baseline.
- Error rate > threshold.
- P95 processing time or end-to-end latency breaches SLO.
10) Worked example: order workflow with topics, retries, DLQ, idempotency
Topics
orders.events (OrderCreated, OrderPaid, OrderCancelled)
payments.commands (AuthorizePayment)
payments.events (PaymentAuthorized, PaymentFailed)
orders.events.dlq
Flow
-
Order Service
- Creates order in DB
- Writes outbox event
OrderCreated
- Outbox relay publishes to
orders.events
-
Payment Service
- Consumes
OrderCreated
- Dedup by
eventId (inbox table)
- Calls payment provider with
Idempotency-Key = eventId
- Publishes
PaymentAuthorized or PaymentFailed
-
Order Service
- Consumes
PaymentAuthorized
- Updates order status to PAID + outbox
OrderPaid
- If consumer fails transiently → retry with backoff
- If message is invalid (permanent) → send to
orders.events.dlq
Ordering choice
- Partition by
orderId so per-order event order is preserved.
11) Practical configuration tips (quick checklist)
- Ack/commit after durable effects (DB commit) to avoid losing work.
- Set visibility timeout / max poll interval > worst-case processing time, or use heartbeats.
- Bound concurrency per partition/key to preserve ordering.
- Retry only transient errors; classify errors.
- Always include unique
eventId and make handlers idempotent.
- Have DLQ + replay tooling from day one.
- Load-test failure modes (broker outage, consumer crash mid-processing, DB slow).
If you share which broker(s) you’re targeting (Kafka, RabbitMQ, SQS/SNS, Pulsar) and a sample domain flow, I can map these patterns into a concrete reference architecture with exact settings (timeouts, retry topics, partition keys, schema compatibility mode) and example producer/consumer code.