Below is a practical blueprint for a Saga Orchestrator that supports compensation, retries/timeouts, DLQs, and observability (logs/metrics/traces). It’s designed for at-least-once delivery (Kafka/Rabbit/SQS) with idempotency and durable state (Postgres).
1) Core architecture
Components
- Saga Orchestrator service
- Owns saga state machine (durable).
- Emits commands to participant services.
- Consumes replies/events from participants.
- Drives retries/timeouts + compensation.
- Message broker (Kafka/Rabbit/SQS)
- Command topics/queues per participant action and compensation.
- Reply topics/queues per participant.
- DLQ topics/queues.
- Durable store (Postgres)
- Saga instance state + step executions.
- Outbox for reliable message publishing.
- Inbox / processed-message table for idempotent consumes.
Reliability pattern
- Use Transactional Outbox: orchestrator writes state + outgoing message in one DB transaction; a relay publishes to broker.
- Use Idempotent consumers: store
messageId (or (sagaId, step, kind)) in an inbox table; ignore duplicates.
2) Data model (minimum viable)
Tables
saga_instance
saga_id (pk)
saga_type
status (RUNNING, COMPENSATING, SUCCEEDED, FAILED, COMPENSATED, COMPENSATION_FAILED)
current_step (int)
payload_json (initial request + working data)
created_at, updated_at
version (optimistic concurrency)
saga_step
saga_id
step_index
status (PENDING, EXECUTING, SUCCEEDED, FAILED, COMPENSATING, COMPENSATED)
attempt (int)
deadline_at (for timeout)
next_retry_at
last_error_code, last_error_message
- PK:
(saga_id, step_index)
outbox
id (pk)
topic
key (e.g., saga_id)
headers_json (trace context, correlation ids)
payload_json
created_at
published_at nullable
inbox_dedupe
consumer_name
message_id
processed_at
- PK:
(consumer_name, message_id)
3) Message envelope (commands + replies)
Use a consistent envelope for all topics.
{
"messageId": "uuid",
"sagaId": "uuid",
"sagaType": "OrderSaga",
"step": 2,
"kind": "COMMAND", // or REPLY
"name": "ReserveInventory", // action/compensate name
"timestamp": "2025-12-13T12:00:00Z",
"correlationId": "uuid",
"traceparent": "00-....",
"payload": { }
}
Participant reply payload should include:
outcome: SUCCESS | FAILURE | RETRYABLE_FAILURE
data (optional output)
errorCode, errorMessage
4) Saga definition model
Define each saga as steps with forward + compensation actions.
type StepDef = {
name: string; // "ReserveInventory"
commandTopic: string; // "inventory.commands"
replyTopic: string; // "orchestrator.replies"
timeoutMs: number; // step deadline
maxAttempts: number; // retries
compensate?: {
name: string; // "ReleaseInventory"
commandTopic: string; // "inventory.commands"
timeoutMs: number;
maxAttempts: number;
};
};
Example saga: CreateOrder
- AuthorizePayment (compensate: VoidAuthorization)
- ReserveInventory (compensate: ReleaseInventory)
- CreateShipment (compensate: CancelShipment)
5) Orchestrator behavior (state machine)
Start saga
- Insert
saga_instance = RUNNING and step0 = EXECUTING.
- Write a command to
outbox.
- Outbox relay publishes command.
Handle replies (happy path)
On reply for (sagaId, step):
- Idempotency check (inbox).
- Load saga + step row with optimistic lock.
- If reply is
SUCCESS:
- Mark step SUCCEEDED.
- Advance to next step; emit next command.
- If last step succeeded → mark saga SUCCEEDED.
Failure handling
If reply is FAILURE (non-retryable):
- Mark saga = COMPENSATING.
- Begin compensation from last SUCCEEDED step backwards.
- Emit compensation command(s).
If reply is RETRYABLE_FAILURE:
- Schedule retry with backoff (don’t block a consumer thread).
6) Retries + timeouts (with backoff)
Retry policy
attempt < maxAttempts
next_retry_at = now + backoff(attempt) (e.g., exponential with jitter)
- Update step to
EXECUTING again and emit the command.
Typical backoff:
base=1s, multiplier 2x, max 1m, add jitter ±20%.
Timeout watcher
Run a scheduler (every few seconds) that:
- Finds steps with
status=EXECUTING AND deadline_at < now
- Converts to retryable failure and applies retry rules.
- If max attempts exceeded → initiate compensation (or fail saga if no compensation possible).
7) Compensation
When entering COMPENSATING:
- Determine all steps with
status=SUCCEEDED and compensate defined.
- Execute compensation in reverse order.
- Each compensation step has its own retry/timeout policy.
- Terminal states:
- All compensations done → saga = COMPENSATED
- A compensation repeatedly fails → saga = COMPENSATION_FAILED + send to Saga-DLQ
8) DLQs (two levels)
A) Message DLQ (poison messages)
Send to *.dlq when:
- Cannot deserialize / schema invalid
- Missing required fields (sagaId/step/messageId)
- Violates invariants (unknown saga, impossible step transitions)
Include metadata:
- original topic, partition/offset (if Kafka), error stack, received payload
B) Saga DLQ (stuck/terminally failing sagas)
When:
- Step exceeded retries and compensation also fails
- Or saga is in RUNNING/COMPENSATING beyond an SLA
Write a “saga snapshot” record/event:
- sagaId, state, step statuses, last errors, payload, timestamps
Support re-drive:
- An operator can patch data (if needed) and re-enqueue the next command/compensation.
9) Observability (logs, metrics, traces)
Structured logging
Every orchestrator log line includes:
sagaId, sagaType, step, messageId, correlationId, attempt, status
traceId (from OTel context)
Metrics (Prometheus-style)
Minimum set:
saga_started_total{sagaType}
saga_completed_total{sagaType,status}
saga_step_attempts_total{sagaType,step,name,outcome}
saga_step_duration_seconds_bucket{sagaType,step,name}
saga_retry_scheduled_total{sagaType,step}
saga_dlq_total{type=message|saga,reason}
outbox_lag_seconds (oldest unpublished outbox row age)
Distributed tracing (OpenTelemetry)
- Root span:
Saga <type> with sagaId
- Child span per step attempt:
Step ReserveInventory attempt=2
- Propagate context via message headers (
traceparent / tracestate)
- Add events for transitions:
step.succeeded, step.retry_scheduled, compensation.started
10) Orchestrator pseudocode (durable + outbox)
async function handleReply(msg: ReplyEnvelope) {
// 1) inbox dedupe
if (await inboxSeen("orchestrator", msg.messageId)) return;
await markInbox("orchestrator", msg.messageId);
await db.tx(async (tx) => {
const saga = await tx.getSagaForUpdate(msg.sagaId); // lock / optimistic version
const step = await tx.getStepForUpdate(msg.sagaId, msg.step);
// ignore late/duplicate replies safely
if (!step || step.status !== "EXECUTING") return;
if (msg.outcome === "SUCCESS") {
await tx.markStepSucceeded(step);
const next = await tx.computeNextStep(saga);
if (!next) {
await tx.markSagaSucceeded(saga);
return;
}
await tx.markStepExecuting(next, {
deadlineAt: nowPlus(next.timeoutMs),
attempt: step.attempt // next step has its own attempt counter in practice
});
await tx.outboxAdd(commandFor(next, saga));
await tx.markSagaRunningAtStep(saga, next.step_index);
}
if (msg.outcome === "RETRYABLE_FAILURE") {
if (step.attempt + 1 <= step.maxAttempts) {
const nextRetryAt = computeBackoff(step.attempt + 1);
await tx.scheduleRetry(step, nextRetryAt, msg.error);
} else {
await tx.markSagaCompensating(saga, msg.error);
await enqueueCompensations(tx, saga);
}
}
if (msg.outcome === "FAILURE") {
await tx.markSagaCompensating(saga, msg.error);
await enqueueCompensations(tx, saga);
}
});
}
Outbox relay loop:
SELECT * FROM outbox WHERE published_at IS NULL ORDER BY created_at LIMIT N
- publish to broker
- set
published_at = now() (retry on publish failure)
11) API surface (operators + callers)
POST /sagas/{type} start saga (returns sagaId)
GET /sagas/{sagaId} state + step details + last errors
POST /sagas/{sagaId}/retry manual re-drive (from DLQ or stuck)
POST /sagas/{sagaId}/abort triggers compensation (if allowed)
12) Practical defaults (that avoid common failure modes)
- Always require participants to be idempotent by
(sagaId, step, commandName) (store “already processed”).
- Use timeouts + retries only for retryable categories (network, 5xx, lock timeouts).
- Treat “unknown sagaId” replies as message-DLQ (or quarantine) unless you intentionally allow late replies after retention.
- Keep saga payload small; store large blobs externally and reference them.
If you tell me your stack (Kafka vs SQS, Postgres vs DynamoDB, language), I can provide a concrete implementation skeleton (project layout, schema migrations, working consumer/producer code, OpenTelemetry wiring, and DLQ re-drive tooling).