Prompt
How do I make sure events are delivered in order for a critical workflow?
Latest observation
To make sure events are delivered in order for a critical workflow, you usually need to control both publishing and consumption, because “ordered delivery” is often only guaranteed under specific conditions.
Practical ways to preserve order
-
Use a single partition / shard for the workflow
- If your broker supports partitions (Kafka, Kinesis, Pulsar, etc.), send all events for the same workflow/entity to the same partition.
- Use a stable key like
workflowIdorcustomerId. - This gives ordering within that partition.
-
Process each partition with only one active consumer at a time
- Multiple consumers can break effective processing order if they operate on the same stream independently.
- Let the system scale by partition, not by parallelizing a single ordered stream.
-
Make the producer preserve sequence
- Emit events from a single writer or ensure the producer assigns a monotonic sequence number.
- Avoid concurrent writers for the same entity unless you have a strict ordering strategy.
-
Add sequence numbers to events
- Include
sequenceNumberorversionin every event. - Consumers can detect duplicates, gaps, or out-of-order arrivals.
- This is especially important because delivery may be ordered but retries/redelivery can still happen.
- Include
-
Make consumers idempotent
- Even with ordering guarantees, retries and duplicates happen.
- Ensure applying the same event twice does not corrupt state.
-
Use optimistic concurrency / version checks
- If events update a stateful record, store the current version.
- Only apply event
nif the current version isn-1. - If an out-of-order event arrives, buffer it or reject/retry it.
-
Avoid fan-out paths that reorder events
- If events pass through multiple services, queues, or async steps, any stage can reorder them.
- Preserve ordering end-to-end or reconstruct order downstream using sequence numbers.
Important caveat
Most brokers only guarantee ordering:
- within a single partition
- for a single producer session
- sometimes only under certain settings
They usually do not guarantee global ordering across all events.
Recommended pattern for critical workflows
For a critical workflow, the safest approach is:
- key events by
workflowId - route all related events to one partition/queue shard
- attach a monotonic sequence number
- process in order
- enforce idempotency and version checks
If you need stronger guarantees
If the workflow is truly critical, consider:
- a single-threaded workflow engine or orchestrator
- a state machine with versioned transitions
- storing the source of truth in a database with transactional writes
- using a log-based system where ordering is explicit and replayable
If you tell me what system you’re using (Kafka, SQS, RabbitMQ, Azure Service Bus, etc.), I can give a concrete setup to preserve ordering there.