We are designing an idempotency strategy that spans REST, message queues, and sagas (which often involve multiple steps and possibly multiple services). The goal is to ensure that operations can be safely retried without causing unintended side effects, and we also require auditability (i.e., we can trace the history of operations and their idempotency keys).
Key concepts:
- Idempotency: An operation can be applied multiple times without changing the result beyond the initial application.
- Idempotency Key: A unique token provided by the client to identify a particular operation. The server uses this key to ensure that the operation is only performed once.
We'll break it down by component:
A. REST (HTTP)
B. Message Queues (e.g., RabbitMQ, Kafka)
C. Sagas (long-running processes that may involve multiple steps and services)
Additionally, we require auditability, meaning we must log the idempotency key and the outcome of each operation.
Let's design for each:
A. REST:
- Client generates a unique idempotency key (UUID) for each operation that must be idempotent.
- Client sends the key in a header (e.g., Idempotency-Key: <uuid>).
- Server checks if it has already processed a request with that key.
- If yes, return the same response (including status code and body) as the original request without re-executing the operation.
- If no, process the request, store the key and the response (or at least the outcome) in a persistent store (e.g., database) and then return the response.
- We must consider what happens if the request is in progress? We might need to lock the key to avoid concurrent processing.
Implementation note:
Use a database table for idempotency keys with columns: key, request_method, request_path, request_body (or hash), response_status, response_body, created_at, updated_at.
Alternatively, we can store the entire request and response for full auditability, but note that request bodies might be large. We might store a hash of the request to ensure the same request is being repeated, and then store the response.
However, note: the same idempotency key should be used for the same logical operation, so if the client sends the same key with a different request (e.g., different body) then we should consider it as a different operation? Actually, the idempotency key is supposed to represent the client's intent. So if the client sends the same key with a different request, it's a mistake. We can either:
- Reject the request (400) because the idempotency key is already used for a different request?
- Or, we can allow it and treat it as a new operation? But then the key is not idempotent for the first request.
Typically, the idempotency key is associated with a specific request. So if the same key is used with a different request (different method, path, or body) then it's a client error. We can return 400 with a message that the idempotency key is already used for a different request.
Steps for REST:
1. Receive request with `Idempotency-Key`.
2. Check if the key exists in the idempotency table.
3. If exists:
a. Compare the stored request (method, path, body hash) with the current request.
b. If they match, return the stored response (status and body).
c. If they don't match, return 400 (or 409) indicating conflict.
4. If not exists:
a. Acquire a lock on the key (to prevent concurrent processing of the same key). This can be done with a database row lock or a distributed lock (like Redis) if we have multiple servers.
b. Process the request.
c. Store the key, request details, and response in the idempotency table.
d. Release the lock.
e. Return the response.
Auditability: The idempotency table serves as an audit log. We can also log to an audit log system, but the table is the source of truth for idempotency.
B. Message Queues:
- When producing a message, the producer can set an idempotency key in the message header.
- The consumer (or the queue itself, if supported) should ensure that the same idempotency key is not processed twice.
However, note that in message queues, we often have at-least-once delivery. So the same message might be delivered multiple times. We need to make the consumer idempotent.
There are two approaches:
1. Queue-level idempotency (if the queue supports it, like RabbitMQ with deduplication or Kafka with exactly-once semantics). But note that these are not always available or may have limitations.
2. Application-level idempotency: The consumer must check the idempotency key against a store (same as REST) and skip processing if already processed.
Since we want a consistent strategy, we'll do application-level.
Steps for message consumer:
- When a message is received, extract the idempotency key from the header.
- Check the idempotency store (same table as REST? or separate? We can use the same table to have a unified view, but note that the request in the context of a message might be different. We can store the message details as well).
- If the key exists and the message content (or a hash) matches, then we skip processing and acknowledge the message.
- If the key exists but the message content is different, we might have a problem. We can either:
a. Reject the message (and maybe dead-letter?) because it's a duplicate with different content? Or
b. Process it as a new operation? But then the idempotency key is not unique for the operation.
Typically, the idempotency key in a message should be generated by the producer for a specific business operation. So if the same key is used for a different message, it's a producer error. We can log and skip (or dead-letter) the message.
Steps:
1. Receive message, extract idempotency key and compute a hash of the message body (or the entire message?).
2. Check if the key exists in the idempotency table.
3. If exists:
a. Compare the stored message hash with the current message hash.
b. If match, then we have already processed this exact message. Acknowledge and skip.
c. If not match, then we have a conflict. We can log an error and either:
- Acknowledge and skip (to avoid infinite loops) and alert, or
- Dead-letter the message for manual inspection.
4. If not exists:
a. Acquire lock on the key.
b. Process the message.
c. Store the key, message hash, and processing result (maybe the business outcome, not the entire message) in the idempotency table.
d. Acknowledge the message.
e. Release the lock.
Note: We might want to store the message in the idempotency table? It depends on the audit requirement. We can store the message ID, exchange, routing key, and a hash of the body. The business outcome might be stored in a separate business table, but we can store the outcome (like status) in the idempotency table as well.
We can design the idempotency table to be generic:
Table: idempotency_keys
Columns:
id (primary key)
idempotency_key (unique)
source (e.g., 'rest', 'message_queue') -- to differentiate the source if needed?
request_method (for REST) or message_exchange (for MQ) and routing_key?
request_path (for REST) or maybe we store the queue name for MQ?
request_hash (hash of the request body or message body)
response_status (HTTP status for REST, or processing status for MQ, e.g., 'processed', 'failed')
response_body (or error message if failed)
created_at
updated_at
Alternatively, we can have separate tables for REST and MQ? But then we lose the unified view. We can also have a base table and then extend? But let's keep it simple and use one table.
We can store:
- For REST: method, path, hash of body, and the response.
- For MQ: exchange, routing_key, hash of body, and the processing result (which might be an event published or a business update).
But note: the business operation might be the same in both REST and MQ? For example, creating an order. We might want to use the same idempotency key for both? Actually, the idempotency key is per operation. So if the same business operation is triggered via REST and then via MQ, they are two different operations and should have different keys.
So we don't need to worry about mixing them. We just store the key and the details of the request/message.
However, in a saga, we might have multiple steps that are triggered by messages or REST calls. We want the entire saga to be idempotent? That's more complex.
C. Sagas:
A saga is a sequence of steps (each step might be a REST call or a message) that are coordinated to achieve a business transaction. The saga might be orchestrated (with a central coordinator) or choreographed (events).
For idempotency in sagas, we need to ensure that each step in the saga is idempotent. But also, the entire saga should be idempotent in the sense that if we replay the saga (or a step) we don't cause inconsistencies.
We can break down:
1. Each step in the saga should be designed as an idempotent operation (using the techniques above for REST or MQ).
2. The saga itself might need to be idempotent if the same saga instance (with the same saga id) is retried. This is usually handled by the saga orchestrator (if using orchestration) or by the participants (if choreography) with the saga id.
How to do it:
- When starting a saga, generate a saga id (unique). Then, for each step, we can use a combination of the saga id and the step id to create an idempotency key? Or we can have the saga id as the idempotency key for the entire saga? Actually, we want each step to be idempotent independently, but also the entire saga sequence to be idempotent.
Let's consider:
Saga Orchestration:
The orchestrator sends commands to participants. Each command should have an idempotency key. The orchestrator can generate a unique key for each command (maybe based on saga id and step name) and store the state of the saga (including which steps have been completed) in a saga log.
When the orchestrator retries a step (because of a failure), it uses the same idempotency key for that step. The participant (which is a service) will then use the idempotency key (as in REST or MQ) to avoid re-executing the step.
Additionally, the orchestrator itself must be idempotent in processing the saga. That is, if the orchestrator crashes and restarts, it should resume the saga from the last completed step without re-executing completed steps. This is achieved by the saga log.
Steps for orchestrator:
- Start saga: generate saga_id, store saga instance in saga log with status 'started'.
- For each step:
a. Generate an idempotency key for the step (e.g., saga_id + step_name). But note: the same step might be retried multiple times, so we want the same key for the same step in the same saga.
b. Send the command (with the idempotency key) to the participant (via REST or MQ).
c. Wait for response (or event) from the participant.
d. If success, update the saga log to mark the step as completed.
e. If failure, retry (with the same idempotency key) or compensate.
The participant will handle the idempotency as described in A or B.
Saga Choreography:
In choreography, each participant listens for events and produces events. The saga is driven by events.
For idempotency:
- When a participant receives an event, it should use an idempotency key from the event (or generate one based on the event and the saga id) to ensure that the same event is not processed twice.
- The participant, after processing the event, publishes a new event (with a new idempotency key? or the same? Actually, the new event is a different step, so it should have its own idempotency key). But note: the entire saga is identified by a saga id that is propagated in the events.
So, each event in the saga should carry:
- saga_id: to identify the saga instance.
- step_id: to identify the step (or the event type).
- We can use the combination (saga_id, step_id) as the idempotency key for that step? But note: the same step might be retried? Actually, in choreography, if a participant fails to process an event, the event might be redelivered (by the message broker). So the same event (with the same event id) might be delivered multiple times. We want to process it only once.
Therefore, we can have the event producer (the previous participant) set an idempotency key for the event? But the event might be generated by the participant as a result of processing a previous event. So we can have:
Event structure:
{
"saga_id": "uuid",
"step": "step_name",
"event_id": "uuid", // unique for the event, generated by the producer of the event
... other data ...
}
Then the consumer uses the `event_id` as the idempotency key? But note: the same event might be redelivered, so it has the same event_id. That's good.
However, what if the same saga step is triggered by two different events? That shouldn't happen in a well-designed saga. But if it does, then we have two different events (with different event_id) for the same step? That might be a different saga instance? Actually, the saga_id and step together should uniquely identify a step in a saga. So we can use (saga_id, step) as the idempotency key? But then if the same step is retried (by redelivery of the same event) then we want to skip. But if we use (saga_id, step) and the same step is retried, we skip. But what if the same step is executed again in a different context (like a new saga instance with the same step)? Then the saga_id would be different, so it's okay.
Alternatively, we can use the event_id as the idempotency key. Then, if the same event is redelivered, we skip. But if a new event for the same step (with a different event_id) arrives, we process it? That might be a problem because we are allowing multiple events for the same step in the same saga? That should not happen if the saga is designed correctly.
Let me clarify:
In a saga, each step is executed exactly once for a given saga instance. So for a given saga_id, step X should be executed only once. Therefore, we can use (saga_id, step) as the idempotency key for the step. But note: the event that triggers step X might be redelivered, so we want to skip if we already executed step X for that saga_id.
So:
Consumer of an event for step X:
- Extract saga_id and step (from the event, or from the event type?).
- Form an idempotency key: saga_id + ":" + step.
- Check if we have processed this key (for this saga_id and step) already.
- If yes, skip.
- If no, process and store the key.
But what about the event itself? We might want to store the event_id as well? For auditability, we can store the event_id in the idempotency record.
Alternatively, we can store the entire event? But that might be too heavy.
We can design the idempotency table for sagas to have:
saga_id, step, event_id, status, ...
Then the key is (saga_id, step). But note: the event_id might be different if the same step is triggered by two different events? That should not happen. But if it does, we have a duplicate step. We might want to detect that.
Actually, we want to ensure that for a given saga_id, each step is executed only once. So we can use (saga_id, step) as the key. Then, if we receive an event for step X with saga_id Y, and we have already processed step X for saga_id Y, we skip.
But what if we receive an event for step X with saga_id Y, but we haven't processed step X for that saga_id? Then we process and store the key (saga_id, step) with the event_id of the event we processed.
Now, if we receive another event for the same step and same saga_id but with a different event_id, that would be a problem. We can check: if the key (saga_id, step) exists, then we compare the stored event_id with the current event_id. If they are different, we have a conflict (two different events for the same step). We can then log an error and skip (or dead-letter).
So:
Key: (saga_id, step)
Steps:
1. Extract saga_id and step from the event.
2. Check if there's an entry with key = (saga_id, step).
3. If exists:
a. Compare the stored event_id with the current event_id.
b. If same, skip.
c. If different, log error and skip (or dead-letter).
4. If not exists:
a. Acquire lock on (saga_id, step).
b. Process the event (which might involve business logic and then publishing the next event).
c. Store the key with the event_id and the outcome.
d. Release the lock.
This ensures that each step in a saga is executed only once per saga instance.
However, note that in choreography, the step might be triggered by an event that is not necessarily the one we expect? We are using the step from the event. But what if the same step is triggered by two different event types? Then the step name might be the same? We need to define the step uniquely. Typically, the step is defined by the business process.
Alternatively, we can use the event type (or the combination of event type and saga_id) as the key? But then if two different event types lead to the same step, we would process both? That might be by design.
It's safer to let the saga designer define the idempotency key for each step. In orchestration, the orchestrator sets the idempotency key for each command. In choreography, the event producer (the previous step) sets the event_id, and the consumer uses (saga_id, step) as the key. But the step must be uniquely defined.
We can also have the event carry an explicit idempotency key? Then the consumer uses that key. That would be more flexible. But then we must ensure that the same key is used for the same step in the same saga.
Let's standardize:
For any operation (REST, message, saga step) we use an idempotency key provided by the client (or the previous step in the saga). The key must be unique for the operation.
In REST, the client provides the key.
In MQ, the producer (the client) provides the key in the message header.
In saga steps (orchestrated or choreographed), the saga orchestrator or the previous step provides the key.
Then, the consumer (REST endpoint, message consumer, saga participant) uses that key to deduplicate.
So, for sagas:
Orchestration:
Orchestrator generates a key for each step (e.g., saga_id + "_" + step_name) and uses that as the idempotency key when calling the participant (via REST or sending a message). The participant then uses that key.
Choreography:
When a participant publishes an event for the next step, it sets the idempotency key for that event? Actually, the next step's idempotency key is generated by the participant that is producing the event? But the next step's participant will use that key. So we need to propagate the idempotency key for the next step? Or the next step's participant generates its own key?
Actually, the idempotency key should be generated by theclient of the operation. In a saga step, the client is the previous step (or the orchestrator). So the previous step should generate a key for the next step and include it in the event? But that couples the steps.
Alternatively, we can have the next step's participant generate the key? But then the previous step doesn't know the key, so it can't set it in the event. And the next step's participant would have to generate the key from the event data (like saga_id and step) and then store it. But then if the same event is redelivered, the same key is generated and we are good.
So in choreography, we can have the participant generate the idempotency key from the event (using a deterministic function of saga_id and step). Then, when the same event is redelivered, the same key is generated and we skip.
But note: if the same step is triggered by two different events (with the same saga_id and step) then we would generate the same key? That's exactly what we want because we want to skip the duplicate. But if the two events are different (different data) but the same step, then we have a conflict. We can detect that by storing the event data (or hash) along with the key.
So:
Key generation for a saga step in choreography:
key = hash(saga_id + "|" + step)
Then, when we process an event, we compute the key and check the idempotency table for that key. If found, we compare the stored event hash (or the entire event) with the current event. If they match, skip. If not, conflict.
This way, we don't need the event to carry an explicit idempotency key. But note: the event might not have a step field? We must define what the step is. It could be the event type? Or a field in the event.
Alternatively, we can use the event's unique event_id as the idempotency key? Then we are deduplicating by event, not by step. But then if the same step is triggered by two different events (with different event_id) we would process both? That might be intended?
Actually, in a saga, each step is triggered by a specific event. So if we get two different events for the same step, it's likely a bug. We want to execute the step only once per saga. So we should use (saga_id, step) as the key, not the event_id.
But then, if we use (saga_id, step) and we get two events for the same step (with different event_id) we would process only the first and skip the second? That might be acceptable because the step should only be executed once. However, if the two events have different data, then we are ignoring the second one. That could be a problem.
So we must ensure that for a given saga_id, each step is triggered exactly once. If the saga is designed correctly, then for a given saga_id, step X should be triggered only once. If we get two events for the same step, it's a duplicate delivery. But if they have different data, then it's a problem in the event production.
Therefore, we can:
Use (saga_id, step) as the idempotency key.
Store the event_id and the event hash (or the entire event) for audit.
When we receive an event for (saga_id, step):
- If we don't have an entry for that key, we process and store the event_id and event hash.
- If we have an entry, we compare the stored event_id (or hash) with the current event. If they match, skip. If not, we have a conflict (two different events for the same step). We can log and skip.
This way, we are protected against duplicate events (same event redelivered) and also detect if two different events are trying to trigger the same step (which is a design flaw).
Summary for sagas:
We need to store for each step in a saga (identified by saga_id and step) the event that triggered it (or at least its hash) and the outcome.
The idempotency key for the step is derived from (saga_id, step). But note: the same step in two different sagas will have different keys because saga_id is different.
We can use a deterministic key generation function, e.g., SHA256(saga_id + "|" + step). Then we store:
idempotency_key: the hash
saga_id
step
event_id
event_hash (or the entire event if we want)
status
... other audit fields ...
Then, when processing an event, we compute the key from the saga_id and step in the event. We look up by that key.
If found, we compare the stored event_hash (or event_id) with the current event's hash (or event_id). If they match, skip. If not, log error and skip.
If not found, we process and store.
This works for both orchestrated and choreographed sagas?
In orchestrated sagas, the orchestrator sends a command to a participant. The command should include the saga_id and the step? Actually, the orchestrator knows the step and the saga_id. It can set the idempotency key as the hash(saga_id + "|" + step). Then the participant uses that key. But note: the participant might not know the step? It just receives a command. So the orchestrator must set the key and send it in the message header (for MQ) or as a header in REST. Then the participant uses that key.
In choreography, the event itself must contain the saga_id and the step (or the step can be derived from the event type). Then the participant computes the key from the event.
So we have two ways:
Option 1: The producer of the operation (REST client, message producer, orchestrator, or event producer) sets the idempotency key in the message/request header.
Option 2: The consumer generates the key from the business data (like saga_id and step).
We can support both? We can have:
- If an explicit idempotency key is provided (in the header), use that.
- Else, generate one from the business data (if available).
But then we must be cautious: if the producer sets a key and we also generate one, they might conflict. So we should have a standard.
Let's decide:
For REST and MQ (non-saga), the client must provide the idempotency key.
For saga steps, the saga orchestrator (in orchestration) or the previous step (in choreography) must provide the idempotency key? Or we can generate it from the saga_id and step.
To keep it consistent, we can require that every operation (including saga steps) has an explicit idempotency key provided by the caller (the previous step or the orchestrator). Then, the consumer just uses that key.
But in choreography, the event producer (the previous participant) might not know that the next step requires an idempotency key? We can have a convention: every event that is part of a saga must carry an idempotency key. The event producer (the previous step) generates the key for the next step? But then the previous step must know the next step's idempotency key generation rule? That's coupling.
Alternatively, we can have the event carry the saga_id and the step, and the next step's participant generates the key from that. Then we don't need an explicit key in the event. This is more decoupled.
So:
For non-saga operations (REST and MQ), the client must provide an idempotency key.
For saga steps, the event must contain at least the saga_id and the step (or the step must be derivable from the event type). Then the participant generates the key as hash(saga_id + "|" + step). This way, the same step in the same saga will always have the same key, regardless of how many times the event is redelivered.
But what if the same step is triggered by two different events (with the same saga_id and step) but different data? Then we generate the same key and we would skip the second one? That's a problem because the data is different.
So we must also store the event data (or a hash) and compare. Then if the event data is different, we have a conflict.
Therefore, for saga steps, we do:
key = hash(saga_id + "|" + step)
Then, when we receive an event, we:
1. Extract saga_id and step.
2. Compute key.
3. Look up by key.
4. If found, compare the stored event_hash (or event_id) with the current event's hash (or event_id). If match, skip. If not, log error and skip (or dead-letter).
5. If not found, process and store the key with the current event's hash.
This works for both orchestrated and choreographed sagas?
In orchestrated sagas, the orchestrator sends a command. The command must contain the saga_id and the step? Or the orchestrator sets the idempotency key as the hash(saga_id + "|" + step) and sends that key in the header. Then the participant uses that key. But then the participant doesn't need to know about saga_id and step? It just uses the key.
But then, if the orchestrator retries, it sends the same key. That's good.
However, if the orchestrator wants to retry a step, it must use the same key. So the orchestrator must store the key for each step? Or it can recompute it from the saga_id and step? If the step is fixed, then it can recompute.
So in orchestrated sagas, the orchestrator can compute the key as hash(saga_id + "|" + step) and set it in the message/request header. Then the participant uses that key.
So we have two patterns:
Pattern 1 (for non-saga and orchestrated saga steps): The caller sets an explicit idempotency key in the header.
Pattern 2 (for choreographed saga steps): The event does not set an explicit idempotency key, but the participant computes it from the event's saga_id and step.
We can support both by having the consumer:
- If an explicit idempotency key is provided (in the header), use that.
- Else, try to compute from business data (saga_id and step). If those are not available, then we cannot guarantee idempotency? We might require that for saga steps, the event must have saga_id and step.
But note: in orchestrated sagas, the orchestrator sets the key explicitly. So the participant will use that key and not compute from saga_id and step.
In choreography, there is no explicit key, so we compute.
How about we standardize on:
For all operations, we try to get the idempotency key from the header. If not present, then we try to generate from a standard set of business fields (like for sagas: saga_id and step). If that's not possible, we reject the request? Or we generate a random key? That would break idempotency.
So we must have a way to generate a deterministic key for the operation.
Let's define:
For REST: the client must set the header.
For MQ: the producer must set the header.
For saga steps (choreography): the event must contain saga_id and step, and the participant will generate the key from these.
For saga steps (orchestration): the orchestrator must set the header with the key (which it can generate from saga_id and step).
Then, the participant (the consumer) will:
if (header idempotency_key exists)
use that.
else if (business fields for saga: saga_id and step exist)
generate key = hash(saga_id + "|" + step)
else
reject the request (400) because we cannot guarantee idempotency.
But note: in choreography, the event might not have a step field? We can use the event type as the step? So we require that the event has a field that identifies the step (or the event type is the step). Then we use:
key = hash(saga_id + "|" + event_type)
So we need to define what the "step" is. It could be the event type, or a field in the event called "step".
Let's assume we have a field called "saga_step" in the event. Then:
key = hash(saga_id + "|" + saga_step)
If the event doesn't have saga_id or saga_step, then we cannot generate the key and we reject.
This way, we have a consistent way to generate keys for saga steps when not provided.
But what about non-saga messages? They might not have saga_id and step. So we require the header.
So:
For non-saga operations (REST and MQ), the idempotency key must be provided in the header.
For saga steps (choreography), the idempotency key is generated from saga_id and saga_step (if not provided in the header? Actually, in choreography, we don't set the header. We generate from the event). But what if the event has the header? Then we use the header and ignore the generated one? That might be okay.
We can do:
if (header idempotency_key)
use it.
else if (saga_id and saga_step present)
generate from them.
else
reject.
This allows the orchestrator to set the header (and we use that) and the choreography events to not set the header but we generate from the event.
But note: in choreography, if an event has the header, we use that. But then two events with the same saga_id and step but different header keys would be considered different? That might be a problem because we want the same step in the same saga to be idempotent. So we should not allow the header to override the generated key? Actually, if the event has the header, we are trusting the producer to set the same key for the same step? But if the producer sets a different key for the same step (same saga_id and step) then we would treat them as different operations? That breaks the idempotency for the step.
Therefore, for saga steps, we must not allow the header to override the generated key? Or we must require that the header (if present) matches the generated key?
Alternatively, we can say: for saga steps, we ignore the header and always generate from saga_id and step. Then we don't care about the header. But then the orchestrator (which is also a producer) must not set the header? Or we can have a flag that says "this is a saga step" and then we ignore the header.
This is getting complicated.
Let's simplify:
We have two types of operations:
1. Non-saga: the client must set the idempotency key in the header. We use that key.
2. Saga steps: we generate the key from the saga_id and step (which are mandatory in the event/request). We do not allow the client to set the header for saga steps? Or we do, but we require that it matches the generated key?
Actually, in a saga step, the client is the previous step (or the orchestrator). It should know the saga_id and step. So it can generate the key. But if it sets the header, we can use that and then verify that it matches the generated key? If not, we reject.
Steps for a saga step:
if (header idempotency_key exists)
let provided_key = header
let generated_key = hash(saga_id + "|" + step)
if (provided_key != generated_key)
reject (400) because the provided key does not match the saga context.
else
use provided_key (or generated_key, they are the same)
else
use generated_key
Then, for non-saga, we only use the header and do not have saga_id and step.
But how do we know if it's a saga step? We can check for the presence of saga_id and step. If they are present, we treat it as a saga step and do the above. If not, we treat it as non-saga and require the header.
So:
if (request has saga_id and step)
// saga step
if (header idempotency_key exists)
if (header != hash(saga_id + "|" + step))
reject
else
key = header
else
key = hash(saga_id + "|" + step)
else
// non-saga
if (header idempotency_key exists)
key = header
else
reject
This way, for saga steps, we ensure that the idempotency key is consistent with the saga context.
However, note: in orchestrated sagas, the orchestrator might set the header to the same value as the generated key. That's fine.
In choreography, the event might not have the header, so we generate.
But what if a non-saga operation accidentally has saga_id and step? Then we would treat it as a saga step and require the header to match the generated key? That might break non-saga clients. So we must be cautious.
Alternatively, we can have a separate header to indicate that the operation is part of a saga? Or we can have a configuration per endpoint? That might be too complex.
Let's think: in a well-designed system, non-saga operations should not have saga_id and step. So if they do, it's a mistake. We can treat it as a saga step and enforce the key. That might be acceptable.
Alternatively, we can have a flag in the request that says "saga": true. Then we know to generate the key from saga_id and step.
But to keep it simple, we can use the presence of saga_id and step as the indicator.
So the algorithm for determining the idempotency key:
if (saga_id and step are present) {
generated_key = hash(saga_id + "|" + step)
if (idempotency_key header exists) {
if (idempotency_key_header != generated_key) {
return 400 with message "Idempotency key does not match saga context"
} else {
key = idempotency_key_header
}
} else {
key = generated_key
}
} else {
if (idempotency_key header exists) {
key = idempotency_key_header
} else {
return 400 with message "Idempotency key required"
}
}
Then, we use the key to check the idempotency table.
We must also store the saga_id and step (if present) in the idempotency table for audit.
The idempotency table can have:
id (auto)
idempotency_key (unique)
saga_id (nullable)
step (nullable)
request_method (nullable, for REST)
request_path (nullable, for REST)
request_hash (hash of the request body, for REST) or message_hash (for MQ) or event_hash (for saga)
response_status
response_body (or error)
created_at
updated_at
Then, when we store, we store the saga_id and step if present.
When we check, we use the key. And if it's a saga step, we also check that the stored saga_id and step match the current ones? Actually, we generated the key from saga_id and step, so if the key matches, then the saga_id and step must match? Not necessarily, because two different (saga_id, step) pairs could generate the same hash? But that's very unlikely. But to be safe, we can store the saga_id and step and when we find a record by key, we compare the stored saga_id and step with the current ones. If they don't match, we have a hash collision? Or a bug? We can treat it as a conflict.
Alternatively, we can make the idempotency_key the combination of saga_id and step? But then for non-saga, we don't have saga_id and step. So we need a flexible key.
We can use a UUID for the key. But then for saga steps, we want the same step in the same saga to have the same key. So we must generate the same UUID from the same (saga_id, step). That's why we use a hash.
But then if we have two different (saga_id, step) that hash to the same value, we have a problem. We can use a longer hash (like SHA256) to make it extremely unlikely.
Alternatively, we can store the (saga_id, step) as separate columns and then create a unique index on (saga_id, step) for saga steps? But then for non-saga, we don't have saga_id and step. So we need two different unique constraints:
For non-saga: unique on idempotency_key (which is provided by the client).
For saga: unique on (saga_id, step) because we generate the key from them, and we want to ensure that the same (saga_id, step) always maps to the same key? Actually, we are generating the key from (saga_id, step), so if we have two records with the same (saga_id, step) they must have the same key. So we can have:
unique index on (saga_id, step) where saga_id is not null.
And for non-saga, we have:
unique index on idempotency_key where saga_id is null.
But then, what if a non-saga operation has saga_id and step? We would store them and then the unique index on (saga_id, step) would apply. That might be acceptable because we want the same (saga_id, step) to be idempotent.
So:
We have two types of records:
Type 1: Non-saga: saga_id is null, step is null. Then the unique constraint is on idempotency_key.
Type 2: Saga: saga_id and step are not null. Then the unique constraint is on (saga_id, step). And the idempotency_key must be equal to hash(saga_id + "|" + step).
Then, when we insert:
For non-saga: we set saga_id=null, step=null, and idempotency_key from header.
For saga: we set saga_id and step from the request, and idempotency_key = hash(saga_id + "|" + step). And we check that if the header is provided, it matches.
This ensures that:
- For non-saga, we use the header key and it's unique.
- For saga, we use the generated key and it's unique per (saga_id, step).
And we can have a single table.
But note: what if a non-saga operation has saga_id and step? Then we treat it as a saga operation and use the generated key. That might be what we want? Because if it has saga_id and step, it's part of a saga.
So the algorithm:
Given a request (REST, MQ, or saga event):
if (saga_id and step are present) {
generated_key = hash(saga_id + "|" + step)
if (idempotency_key header exists) {
if (idempotency_key_header != generated_key) {
reject
} else {
key = generated_key
}
} else {
key = generated_key
}
// Then we store with saga_id and step, and key must equal generated_key.
} else {
if (idempotency_key header exists) {
key = idempotency_key_header
} else {
reject
}
// Then we store with saga_id=null, step=null.
}
Then, we look up by key (for non-saga) or by (saga_id, step) for saga? Actually, we are using the key as the primary lookup. But for saga, we also have the unique constraint on (saga_id, step). We can do:
Try to find by key.
If found, then:
if (saga_id and step are present) {
// then the found record must have the same saga_id and step? Actually, we generated the key from them, so if the key matches, the saga_id and step must match? Not necessarily if there's a hash collision. But we can check.
if (found_record.saga_id != current_saga_id or found_record.step != current_step) {
// hash collision? or bug? reject.
}
}
// Then compare the request hash (or event hash) to ensure the same request/event.
if (request_hash matches) {
return stored response
} else {
// conflict: same key but different request? This should not happen for non-saga because the key is provided by the client and should be unique per request. For saga, we have the unique constraint on (saga_id, step) so two different requests for the same step would have the same key? But then we would have stored the first one and the second one would be a conflict because the request hash is different. We can reject.
reject with 409 or 400.
}
}
If not found, then process and store.
But note: for saga, we have the unique constraint on (saga_id, step). So if we try to insert a record with the same (saga_id, step) but a different request (and hence different request_hash) then the unique constraint on (saga_id, step) would be violated? Actually, we are using the key as the primary key? We have:
Primary key: id (auto increment) and unique index on idempotency_key for non-saga, and unique index on (saga_id, step) for saga.
We can design the table as:
CREATE TABLE idempotency_keys (
id BIGSERIAL PRIMARY KEY,
idempotency_key VARCHAR(255) UNIQUE, -- for non-saga, we store the client-provided key here. For saga, we store the generated key (which is hash(saga_id + "|" + step)) and it must match the unique constraint on (saga_id, step).
saga_id VARCHAR(255) NULL,
step VARCHAR(255) NULL,
request_method VARCHAR(10) NULL,
request_path TEXT NULL,
request_hash CHAR(64) NULL, -- SHA256 hash of the request body (or event body) in hex
response_status INTEGER NULL,
response_body TEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
-- For saga, we want (saga_id, step) to be unique when both are not null.
UNIQUE (saga_id, step) WHERE saga_id IS NOT NULL
);
Then, when we insert for saga, we set saga_id and step, and idempotency_key = hash(saga_id + "|" + step). The unique constraint on (saga_id, step) ensures we don't have two records for the same step in the same saga.
For non-saga, we set saga_id and step to null, and idempotency_key to the client-provided key. The unique constraint on idempotency_key ensures we don't have two records with the same key.
Then, when we look up:
For non-saga: we look up by idempotency_key.
For saga: we look up by (saga_id, step) or by idempotency_key? Since we have the generated key, we can look up by idempotency_key. But note: the unique constraint on (saga_id, step) is separate.
We can do:
if (saga_id and step are present) {
// We are going to use the generated key, but we can also check by (saga_id, step) because we have the unique constraint.
// Actually, we can look up by (saga_id, step) because that's what we have and it's unique.
// But we also have the key. We can look up by key and then verify the saga_id and step? Or we can look up by (saga_id, step) and then verify the key?
// Since we have the unique constraint on (saga_id, step), we can do:
SELECT * FROM idempotency_keys WHERE saga_id = ? AND step = ?;
Then, if found, we compare the request_hash (or event_hash) and return the stored response if the request matches.
If not found, we process and insert with saga_id, step, and idempotency_key = generated_key.
} else {
SELECT * FROM idempotency_keys WHERE idempotency_key = ?;
}
This avoids the hash lookup for saga? But note: we are using the generated key for the idempotency_key column. So we can also look up by idempotency_key and then verify saga_id and step?
Actually, for saga, we have two ways to look up: by (saga_id, step) or by idempotency_key. But we must ensure that the idempotency_key we stored is the same as the one we generated. So if we look up by (saga_id, step), we don't need to check the key? We are using the unique constraint on (saga_id, step) so there is at most one record. Then we compare the request_hash.
But what if we look up by idempotency_key for a saga? Then we must check that the saga_id and step match? Because the key is generated from them.
So we can do:
if (saga_id and step are present) {
// We generate the key, but we don't need to use it for lookup. We use (saga_id, step) because we have the unique constraint.
found = SELECT * FROM idempotency_keys WHERE saga_id = ? AND step = ? FOR UPDATE; -- lock the row
if (found) {
if (found.request_hash != current_request_hash) {
reject (conflict)
} else {
return found.response
}
} else {
// process and insert
INSERT INTO idempotency_keys (saga_id, step, idempotency_key, request_hash, ...) VALUES (?, ?, ?, ?, ...);
}
} else {
key = header_idempotency_key
found = SELECT * FROM idempotency_keys WHERE idempotency_key = ? FOR UPDATE;
if (found) {
if (found.request_hash != current_request_hash) {
reject
} else {
return found.response
}
} else {
// process and insert
INSERT INTO idempotency_keys (idempotency_key, request_hash, ...) VALUES (?, ?, ...);
}
}
This way, for saga we use the (saga_id, step) lookup and for non-saga we use the key lookup.
But note: for saga, we are not using the header key at all? We are generating the key and then storing it. But we also check that if the header is provided, it matches the generated key. So we are consistent.
However, what if the header is provided and does not match? We reject. So we never store a saga record with a header-provided key that doesn't match.
So the algorithm for the consumer:
Step 1: Determine the type.
if (saga_id and step are present) {
generated_key = hash(saga_id + "|" + step)
if (header_idempotency_key exists and header_idempotency_key != generated_key) {
return 400
}
// Now we are going to use the generated_key for storage, but lookup by (saga_id, step)
key_for_storage = generated_key
lookup_by = (saga_id, step)
} else {
if (!header_idempotency_key) {
return 400
}
key_for_storage = header_idempotency_key
lookup_by = key_for_storage
}
Step 2: Compute the request_hash (hash of the request body or event body).
Step 3: Look up by lookup_by (with a lock) in the idempotency table.
Step 4: If found:
if (found.request_hash == current_request_hash) {
return found.response (with the same status and body)
} else {
// Conflict: same idempotency context (same saga step or same non-saga key) but different request.
return 409 (or 400)
}
Step 5: If not found:
Process the request (business logic).
Then, store:
idempotency_key = key_for_storage
saga_id = current_saga_id (or null)
step = current_step (or null)
request_method = for REST only? we can store for all?
request_path = for REST only?
request_hash = current_request_hash
response_status = response status code
response_body = response body (or error message if failed)
created_at = now
updated_at = now
Release lock.
Step 6: Return the response.
Note: We must compute the request_hash in a deterministic way. For REST, we can hash the request body (and maybe include the method and path? but the key is already supposed to be unique per request, so we are already using the key. But we are also storing the request_hash to detect if the same idempotency context is used for a different request. So we should hash the entire request that we are going to process?
For non-saga REST: the key is provided by the client. We should hash the method, path, and body? Because the same key used with a different method or path would be a different request. But the client should not do that. However, to be safe, we can store the method, path, and body hash. Then when we check, we compare the stored method, path, and body hash with the current request.
Similarly, for MQ: we might store the exchange, routing key, and body hash.
For saga steps: we store the saga_id, step, and event body hash.
So we need to store additional fields:
For non-saga REST: request_method, request_path, request_hash (of body).
For MQ: we can store exchange, routing_key, request_hash (of body).
For saga: we store saga_id, step, and request_hash (of event body).
But we have a single table. We can make these columns nullable and use them as needed.
Then, when we check:
For non-saga (saga_id and step are null): we compare the stored request_method, request_path, and request_hash with the current request.
For MQ (non-saga?): we compare exchange, routing_key, and request_hash? But we don't have a standard way to know if it's MQ. We can have a source column? Or we can store the request_method and request_path for REST, and for MQ we don't use them?
Alternatively, we can store a generic "request_type" (e.g., 'rest', 'mq', 'saga') and then have specific columns for each? That might be overkill.
Let's simplify: we store the following for every record:
idempotency_key
saga_id (nullable)
step (nullable)
source (nullable) -- can be 'rest', 'mq', 'saga'? But for saga steps, we have saga_id and step, so we don't need source? We can derive: if saga_id is not null, then it's a saga step. Else, it's non-saga. But non-saga could be REST or MQ. We don't really need to distinguish.
We store:
request_method (for REST) and request_path (for REST) -- for MQ and saga, these are null.
exchange, routing_key (for MQ) -- for REST and saga, these are null.
request_hash (always stored, hash of the body)
Then, when we check:
if (saga_id and step are present) {
// saga step
if (found.saga_id != current_saga_id or found.step != current_step) {
// This should not happen because we looked up by (saga_id, step) and the unique constraint ensures only one record. But if we look up by key for saga? We are looking up by (saga_id, step) so we get at most one. So we don't need to check saga_id and step again?
}
if (found.request_hash != current_request_hash) {
conflict
}
} else {
// non-saga
if (found.request_method != current_request_method or found.request_path != current_request_path or found.request_hash != current_request_hash) {
conflict
}
}
But for MQ, we don't have request_method and request_path. We have exchange and routing_key. So we need to store those for MQ and compare.
How do we know if it's MQ? We can have a source column. Then:
if (source = 'rest') {
compare request_method, request_path, request_hash.
} else if (source = 'mq') {
compare exchange, routing_key, request_hash.
} else if (source = 'saga') {
compare saga_id, step, request_hash? But we already have saga_id and step as separate columns and we looked up by them. So we only need to compare request_hash.
}
But we don't have a source column. We can infer:
if (saga_id is not null) -> saga.
else if (request_method is not null) -> rest.
else if (exchange is not null) -> mq.
So we can do:
if (saga_id is not null) {
// saga
// we already looked up by (saga_id, step) so we have one record. Compare request_hash.
} else if (request_method is not null) {
// rest
compare request_method, request_path, request_hash.
} else if (exchange is not null) {
// mq
compare exchange, routing_key, request_hash.
} else {
// unknown? error.
}
This is getting complex. We might want to have a simpler design: we only store the key and the request hash. And we rely on the key being unique for the operation. Then, if the same key is used with a different request, we reject.
But then, for REST, the same key could be used for a different method or path? We want to reject that. So we must store the method and path to detect that.
Similarly, for MQ, we must store exchange and routing_key.
For saga, we store saga_id and step.
So we need these fields.
Let's design the table with:
idempotency_key (unique for non-saga, and for saga it's generated from saga_id and step, but we also have unique on (saga_id, step))
saga_id (nullable)
step (nullable)
request_method (nullable, for REST)
request_path (nullable, for REST)
exchange (nullable, for MQ)
routing_key (nullable, for MQ)
request_hash (not nullable) -- hash of the body (or the entire request/event payload)
Then, when we check:
if (saga_id and step are present) {
// We looked up by (saga_id, step). Then we compare request_hash.
if (found.request_hash != current_request_hash) {
conflict
}
} else if (request_method is not null) {
// REST
if (found.request_method != current_request_method or found.request_path != current_request_path or found.request_hash != current_request_hash) {
conflict
}
} else if (exchange is not null) {
// MQ
if (found.exchange != current_exchange or found.routing_key != current_routing_key or found.request_hash != current_request_hash) {
conflict
}
} else {
// This record is corrupted? Or we have a new type? We can reject.
conflict
}
This works.
Now, for the auditability: we are storing the request details and the response. We can also store who initiated the request? But that might be in the request body. We are storing the body hash, not the body. For full audit, we might want to store the entire request and response? But that could be large. We can store the body separately (maybe in a blob storage) and store a reference? Or we can store the body in the table if it's small.
We are storing the response body. We might want to store the request body as well? We are storing the request_hash, but not the body. If we need to audit the exact request, we should store the request body. Similarly, the response body.
We can add:
request_body (text, nullable)
response_body (text, nullable)
But note: for large payloads, this might be too big. We can store them in a separate table or in object storage and store a reference.
For simplicity, let's assume we store the request and response bodies in the same table. We can make them TEXT and store up to a certain size. If they are too big, we can truncate? But that might break auditability.
Alternatively, we can store the request and response in a separate audit table that references the idempotency_key. But then we have two tables.
Since the requirement is auditability, we should store the request and response. We can do:
request_body (TEXT)
response_body (TEXT)
And if they are too big, we can compress? Or we can store in a blob and store a pointer.
Let's keep it simple and store as TEXT. We can set a limit (like 1MB) and reject if larger? Or we can store in a separate table with a foreign key.
But note: the idempotency table is already storing the request_hash. We can store the request and response in a separate table called idempotency_audit with columns:
idempotency_key (foreign key to idempotency_keys.idempotency_key? or to id?)
request_body TEXT
response_body TEXT
created_at
Then, the idempotency_keys table has the hash and the metadata, and the audit table has the full request and response.
But then we have to join to get the full request? For the idempotency check, we only need the hash and the metadata (method, path, etc.). So we can keep the idempotency_keys table small and have the audit table for full audit.
We can do:
Table idempotency_keys:
id (primary key)
idempotency_key (unique)
saga_id (nullable)
step (nullable)
request_method (nullable)
request_path (nullable)
exchange (nullable)
routing_key (nullable)
request_hash (not null)
response_status (not null)
created_at
updated_at
Table idempotency_audit:
id (primary key)
idempotency_key_id (foreign key to idempotency_keys.id)
request_body (text)
response_body (text)
created_at (same as idempotency_keys.created_at? or we can have separate)
Then, when we store, we store the metadata in idempotency_keys and the full bodies in idempotency_audit.
But note: the idempotency_keys table has the response_status, but not the response_body. We store the response_body in the audit table.
For returning the response, we need the response_status and response_body. So we have to join. That's acceptable.
Alternatively, we can store the response_status and response_body in the idempotency_keys table, and the request_body in the audit table? We need the request_body for audit, but for idempotency check we only need the hash. So we can store the request_body in the audit table and the response_body in the idempotency_keys table? But then we might want to store the request_body in the same table as the response for consistency.
Let's store both request and response in the audit table, and only the hash and metadata in the idempotency_keys table.
Then, when we want to return the stored response, we join:
SELECT ik.response_status, ia.response_body
FROM idempotency_keys ik
JOIN idempotency_audit ia ON ik.id = ia.idempotency_key_id
WHERE ik.idempotency_key = ?
AND ... (the other conditions for saga or rest)
But note: we are looking up by (saga_id, step) for saga. Then we need to join.
We can also store the response_status in the idempotency_keys table and the response_body in the audit table? That way we don't need to join for the status? But we need the body too.
Alternatively, we can store everything in one table and have a flag for whether the request/response is stored in full? But that's messy.
Given the complexity, and since the requirement is auditability, we might want to store the full request and response. So let's have one table for idempotency and audit:
CREATE TABLE idempotency_records (
id BIGSERIAL PRIMARY KEY,
idempotency_key VARCHAR(255) UNIQUE, -- for non-saga, or the generated key for saga.
saga_id VARCHAR(255) NULL,
step VARCHAR(255) NULL,
request_method VARCHAR(10) NULL,
request_path TEXT NULL,
exchange VARCHAR(255) NULL,
routing_key VARCHAR(255) NULL,
request_hash CHAR(64) NOT NULL,
request_body TEXT NULL, -- can be null if we don't want to store? But for audit, we want it.
response_status INTEGER NOT NULL,
response_body TEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
UNIQUE (saga_id, step) WHERE saga_id IS NOT NULL
);
We can make request_body and response_body nullable? But for audit, we want them. We can store them always. If the request or response is too big, we might not want to store in the database. We can store in a separate blob store and store a reference (URL) in these columns.
But for simplicity, let's assume we store in the database.
Then, we have one table and we can easily query by idempotency_key or by (saga_id, step).
We must also consider performance: the table will grow. We need a retention policy. We can delete old records after a certain period? But then we lose idempotency for old operations? Typically, idempotency is only required for a certain period (e.g., 24 hours). So we can set a TTL on the records.
We can have a background job that deletes records older than X days.
Now, let's write the algorithm for the consumer (REST endpoint, message consumer, or saga participant) in pseudo-code:
function handleRequest(request) {
// Extract saga_id and step if present
saga_id = request.header('saga-id') or request.body.saga_id? We need to define where these are.
step = request.header('saga-step') or request.body.saga_step?
// Extract idempotency key from header
idempotency_key_header = request.header('Idempotency-Key')
// Determine the key and the lookup condition
if (saga_id && step) {
generated_key = sha256(saga_id + "|" + step)
if (idempotency_key_header && idempotency_key_header != generated_key) {
return 400 "Idempotency key does not match saga context"
}
key = generated_key
// Lookup by (saga_id, step)
record = db.query("SELECT * FROM idempotency_records WHERE saga_id = ? AND step = ? FOR UPDATE", [saga_id, step])
} else {
if (!idempotency_key_header) {
return 400 "Idempotency key required"
}
key = idempotency_key_header
// Lookup by idempotency_key
record = db.query("SELECT * FROM idempotency_records WHERE idempotency_key = ? FOR UPDATE", [key])
}
// Compute request hash (of the request body)
request_body = request.body // or the entire request? We need to be consistent.
request_hash = sha256(request_body)
// If record found
if (record) {
// Check if the request matches
if (saga_id && step) {
// We already have the correct saga_id and step because we looked up by them.
if (record.request_hash != request_hash) {
return 409 "Conflict: same saga step but different request"
}
} else if (record.request_method && record.request_path) {
// REST
if (record.request_method != request.method || record.request_path != request.path || record.request_hash != request_hash) {
return 409 "Conflict: same idempotency key but different request"
}
} else if (record.exchange && record.routing_key) {
// MQ
// We need to know the exchange and routing_key of the current message. They are in the message properties.
if (record.exchange != request.exchange || record.routing_key != request.routing_key || record.request_hash != request_hash) {
return 409 "Conflict: same idempotency key but different message"
}
} else {
// Unknown record type?
return 409 "Conflict: invalid record"
}
// If we get here, the request matches the stored one. Return the stored response.
return response(record.response_status, record.response_body)
}
// Not found, so process the request
try {
response_status, response_body = processBusinessLogic(request)
} catch (error) {
// We might want to store the failure? Yes, for auditability.
response_status = 500
response_body = error message
}
// Store the record
if (saga_id && step) {
db.execute(
"INSERT INTO idempotency_records (idempotency_key, saga_id, step, request_hash, request_body, response_status, response_body) VALUES (?, ?, ?, ?, ?, ?, ?)",
[key, saga_id, step, request_hash, request_body, response_status, response_body]
)
} else if (request.method) { // REST
db.execute(
"INSERT INTO idempotency_records (idempotency_key, request_method, request_path, request_hash, request_body, response_status, response_body) VALUES (?, ?, ?, ?, ?, ?, ?)",
[key, request.method, request.path, request_hash, request_body, response_status, response_body]
)
} else { // MQ
db.execute(
"INSERT INTO idempotency_records (idempotency_key, exchange, routing_key, request_hash, request_body, response_status, response_body) VALUES (?, ?, ?, ?, ?, ?, ?)",
[key, request.exchange, request.routing_key, request_hash, request_body, response_status, response_body]
)
}
return response(response_status, response_body)
}
Note: We are storing the request_body and response_body. This might be large. We can consider compressing or truncating.
Also, we are using a database row lock (FOR UPDATE) to prevent concurrent processing of the same idempotency key. This is important.
We must also consider that the same idempotency key might be used by different services? We are using a global table. That's okay because the key is global.
But note: the same idempotency key might be used for a REST call and a message? That would be a client error because the key should be unique per operation. But if it happens, we would have a conflict because the record would have either saga_id and step (if from saga) or request_method (if from REST) and we are looking up by different conditions. Actually, for REST we look up by idempotency_key, and for saga we look up by (saga_id, step). So if a saga step uses an idempotency_key that is the same as a non-saga record, then when we look up by (saga_id, step) we won't find the non-saga record because it has saga_id null. And when we look up by idempotency_key for non-saga, we might find the saga record? But the saga record has saga_id not null, so we would treat it as a saga record? Actually, in the non-saga branch, we look up by idempotency_key and then we check the record type by the presence of request_method or exchange. If we find a saga record (with saga_id and step) in the non-saga branch, then the record will have saga_id and step not null, and request_method and exchange null? Then we would fall into the else case and return conflict? That's acceptable because it's a misuse.
So the table design and algorithm should work.
However, we must ensure that the generated key for saga is the same as the one we would get from the header? We already check that.
Now, for auditability: we have the full request and response. We can also log to an audit log system, but the table is the source of truth.
We must also consider that the same business operation might be performed by different clients? The idempotency key is provided by the client, so it's the client's responsibility to generate a unique key for each operation. But if two different clients use the same key for different operations, that's a client error. We will reject the second one because the request will be different.
This strategy should work for REST, MQ, and sagas.
Let's summarize the strategy:
1. Every operation (REST call, message, saga step) must have an idempotency key. For saga steps, the key is generated from saga_id and step, and must match the header if provided.
2. We store a record for each idempotency key (or for each saga step) with the request details and the response.
3. When an operation is received, we check if we have already processed the same idempotency key (or same saga step) with the same request. If yes, we return the stored response. If the request differs, we return a conflict.
4. We use database row locking to prevent concurrent processing of the same idempotency key.
5. We store the full request and response for audit.
6. We have a unique constraint on idempotency_key for non-saga records and on (saga_id, step) for saga records.
This ensures idempotency and auditability.
Note: The request_hash is computed over the request body. We must be consistent in how we compute it. For example, for JSON, we might sort the keys? Or we can use a canonical representation? It depends on the client. The client should send the same body for retries. We can compute the hash of the raw body (as received). But if the client sends the same JSON with keys in different order, the hash will be different. So we might want to normalize? But that's complex. We can require that the client sends the same exact body for retries. That's typical for idempotency keys: the client must repeat the exact same request.
So we compute the hash of the raw byte array of the request body.
Similarly for messages and events.
We must also consider that the request might have headers that affect the processing? For REST, the method and path are part of the request. We store them separately. For MQ, the exchange and routing_key are part of the request. For saga, the saga_id and step are part of the request.
So when we compute the request_hash, we only hash the body? But then if the same body is sent with a different method, we would detect that because we store the method and compare. So it's okay.
For saga, we store saga_id and step separately and compare them. So we don't need to include them in the hash? But we are comparing the request_hash (which is only the body) and the saga_id and step separately. So if the same body is sent for a different step, we would have a different (saga_id, step) and we would not find the record? Because we look up by (saga_id, step). So we are safe.
But what if the same step (same saga_id and step) is sent with a different body? Then we would find the record (by the (saga_id, step)) and then compare the request_hash. If different, conflict.
So we are covered.
This is a comprehensive strategy. Implementation details will depend on the technology stack (database, programming language, etc.).
We must also consider that the idempotency key might be reused after a long time? We have a retention policy. We can delete records after, say, 30 days. Then, if a client retries after 30 days with the same key, it will be treated as a new operation. That might be acceptable.
Alternatively, we can keep the records forever for audit, but then we need to archive old ones.
We'll leave the retention policy as an operational concern.
Finally, we must ensure that the idempotency key is long enough (UUID) to avoid collisions.
And we must generate the key for saga steps using a secure hash (SHA256) of saga_id and step. The saga_id should be a UUID and the step should be a string that uniquely identifies the step.
This design should meet the requirements.</think>
I'll architect a comprehensive idempotency strategy that spans REST APIs, message queues, and distributed sagas while ensuring full auditability. This solution addresses duplicate detection, exactly-once processing semantics, and complete operational traceability.
Core Principles
- Idempotency Keys: Client-generated UUIDs that uniquely identify business operations
- Deterministic Outcomes: Same key + same input → same result
- Audit Trail: Complete history of all idempotent operations
- Distributed Safety: Works across service boundaries and failure scenarios
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ IDEMPOTENCY SERVICE │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │
│ │ REST Layer │ │ MQ Layer │ │ Saga Layer │ │
│ └─────────────┘ └─────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────┴─────────┐
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ Idempotency │ │ Audit Store │
│ Repository │ │ (Append-Only) │
│ (PostgreSQL) │ │ │
└──────────────────┘ └──────────────────┘
1. IDEMPOTENCY TOKEN DESIGN
Token Generation
// Client-side generation
const idempotencyKey = `idem_${businessContext}_${UUIDv4()}`;
// Example: `idem_order_create_550e8400-e29b-41d4-a716-446655440000`
Token Structure
Format: idem_{scope}_{resource}_{correlation-id}
Examples:
- idem_order_create_abc123
- idem_payment_process_xyz789
- idem_saga_inventory_reserve_def456
2. REST API IMPLEMENTATION
Request/Response Pattern
Request:
POST /api/orders
Idempotency-Key: idem_order_create_550e8400-e29b-41d4-a716-446655440000
Content-Type: application/json
{
"customerId": "cust_123",
"items": [...]
}
Implementation Middleware:
class IdempotencyMiddleware:
def __init__(self, idempotency_repo, audit_logger):
self.repo = idempotency_repo
self.audit = audit_logger
async def process_request(self, request):
key = request.headers.get('Idempotency-Key')
if not key:
return # Optional enforcement per endpoint
# 1. Check existing record
existing = await self.repo.get(key)
if existing:
await self.audit.log_replay(
key=key,
original_ts=existing.created_at,
replay_ts=datetime.utcnow()
)
return existing.response
# 2. Create pending record with lock
pending = await self.repo.create_pending(
key=key,
method=request.method,
path=request.path,
headers=dict(request.headers),
body_hash=hash_body(request.body)
)
# 3. Process with lock held
try:
response = await process_business_logic(request)
# 4. Complete record
await self.repo.complete(
key=key,
status=response.status,
body=response.body,
duration_ms=elapsed_ms
)
return response
except Exception as e:
await self.repo.fail(key, str(e))
raise
Database Schema (PostgreSQL)
CREATE TABLE idempotency_keys (
key VARCHAR(255) PRIMARY KEY,
status VARCHAR(20) CHECK (status IN ('pending', 'completed', 'failed')),
http_method VARCHAR(10),
path TEXT,
request_body_hash CHAR(64),
response_status INT,
response_body JSONB,
expires_at TIMESTAMP NOT NULL DEFAULT (NOW() + INTERVAL '24 hours'),
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
completed_at TIMESTAMP,
locked_until TIMESTAMP,
retry_count INT DEFAULT 0,
correlation_id VARCHAR(100),
saga_id VARCHAR(100),
metadata JSONB
);
CREATE INDEX idx_idempotency_expires ON idempotency_keys(expires_at);
CREATE INDEX idx_idempotency_saga ON idempotency_keys(saga_id) WHERE saga_id IS NOT NULL;
3. MESSAGE QUEUE IDEMPOTENCY
Producer Pattern (Kafka/RabbitMQ)
public class IdempotentProducer {
private final IdempotencyRepository repo;
public void send(String queue, Object message, String idempotencyKey) {
// 1. Check if already sent
if (repo.exists(idempotencyKey)) {
log.debug("Duplicate message detected: {}", idempotencyKey);
return;
}
// 2. Mark as sent before sending (optimistic)
repo.markSent(idempotencyKey, queue, message);
try {
// 3. Send message with key as message ID
kafkaTemplate.send(queue, idempotencyKey, message);
} catch (Exception e) {
repo.markFailed(idempotencyKey);
throw e;
}
}
}
Consumer Pattern
class IdempotentConsumer:
def __init__(self, idempotency_repo):
self.repo = idempotency_repo
async def process_message(self, message):
key = message.headers.get('Idempotency-Key')
if not key:
key = generate_key_from_payload(message.body)
# Acquire lock
if not await self.repo.try_lock(key, timeout_seconds=300):
await self.audit.log_skipped(key, "locked_by_other")
return # Already processing elsewhere
try:
if await self.repo.is_processed(key):
await self.audit.log_duplicate(key)
return # Already processed
result = await self.handle_business(message)
await self.repo.mark_completed(key, result)
except Exception as e:
await self.repo.mark_failed(key, str(e))
raise
Message Headers Standard
{
"Idempotency-Key": "idem_inventory_reserve_abc123",
"Saga-ID": "saga_order_xyz789",
"Correlation-ID": "corr_global_123",
"Retry-Count": 0,
"Original-Timestamp": "2024-01-15T10:30:00Z"
}
4. SAGA IDEMPOTENCY
Saga Context Propagation
interface SagaContext {
sagaId: string; // Unique saga instance ID
stepId: string; // Current step identifier
compensationStep?: string; // If compensation
originService: string; // Which service started it
correlationId: string; // Cross-service correlation
}
// Each saga step carries the context
const sagaStepMessage = {
saga: {
id: "saga_order_123",
step: "inventory_reserve",
compensation: "inventory_release"
},
payload: { orderId: "order_123", quantity: 10 },
idempotency: {
key: "idem_saga_inventory_reserve_saga_order_123",
generatedAt: "2024-01-15T10:30:00Z"
}
};
Orchestrator Pattern
public class SagaOrchestrator {
private final IdempotencyRepository repo;
private final Map<String, SagaState> stateStore;
public void executeStep(SagaStep step) {
String key = step.getIdempotencyKey();
// Check if step already executed
if (repo.isStepCompleted(step.getSagaId(), step.getName())) {
audit.log("Step already completed", key);
return;
}
// Check if we're already executing this step
if (!repo.tryAcquireStepLock(step.getSagaId(), step.getName())) {
throw new SagaLockException("Step locked by another instance");
}
try {
// Execute step
step.execute();
// Record completion
repo.recordStepCompletion(
step.getSagaId(),
step.getName(),
key,
step.getResult()
);
// Trigger next step
triggerNextStep(step);
} finally {
repo.releaseStepLock(step.getSagaId(), step.getName());
}
}
}
5. AUDITABILITY SYSTEM
Append-Only Audit Log
CREATE TABLE audit_log (
id BIGSERIAL PRIMARY KEY,
timestamp TIMESTAMP NOT NULL DEFAULT NOW(),
event_type VARCHAR(50) NOT NULL, -- 'request_received', 'duplicate_detected', 'step_completed', etc.
idempotency_key VARCHAR(255),
saga_id VARCHAR(100),
correlation_id VARCHAR(100),
service_name VARCHAR(100),
operation VARCHAR(100),
status VARCHAR(20),
request_fingerprint CHAR(64), -- Hash of request
response_fingerprint CHAR(64), -- Hash of response
duration_ms INT,
error_message TEXT,
metadata JSONB,
FOREIGN KEY (idempotency_key) REFERENCES idempotency_keys(key)
);
CREATE INDEX idx_audit_correlation ON audit_log(correlation_id);
CREATE INDEX idx_audit_saga ON audit_log(saga_id);
CREATE INDEX idx_audit_timestamp ON audit_log(timestamp);
Audit Query Examples
-- Find all operations for a saga
SELECT * FROM audit_log
WHERE saga_id = 'saga_order_123'
ORDER BY timestamp;
-- Find duplicate attempts
SELECT idempotency_key, COUNT(*) as attempts
FROM audit_log
WHERE event_type = 'duplicate_detected'
GROUP BY idempotency_key
HAVING COUNT(*) > 1;
-- Timeline for correlation ID
SELECT * FROM audit_log
WHERE correlation_id = 'corr_global_123'
ORDER BY timestamp;
6. DISTRIBUTED COORDINATION
Redis Distributed Locks (Alternative to DB locks)
class DistributedLockManager:
def __init__(self, redis_client):
self.redis = redis_client
async def acquire_lock(self, key: str, ttl_seconds: int = 300) -> bool:
lock_key = f"lock:{key}"
token = str(uuid.uuid4())
acquired = await self.redis.set(
lock_key,
token,
nx=True,
ex=ttl_seconds
)
if acquired:
self.redis.set(f"lock_owner:{key}", token)
return acquired
async def release_lock(self, key: str) -> bool:
lock_key = f"lock:{key}"
owner_key = f"lock_owner:{key}"
token = await self.redis.get(owner_key)
if token:
# Lua script for atomic release
script = """
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1], KEYS[2])
else
return 0
end
"""
result = await self.redis.eval(
script,
2,
lock_key,
owner_key,
token
)
return result == 2
return False
Hybrid Locking Strategy
public class IdempotencyLockManager {
// Tier 1: Fast local lock (Caffeine cache)
private final Cache<String, Lock> localLocks = Caffeine.newBuilder()
.expireAfterWrite(5, MINUTES)
.build();
// Tier 2: Distributed lock (Redis)
private final RedissonClient redisson;
// Tier 3: Database row lock (fallback)
private final JdbcTemplate jdbc;
public boolean tryLock(String key, long timeoutMs) {
// Try local first
Lock localLock = localLocks.get(key, k -> new ReentrantLock());
if (localLock.tryLock(timeoutMs, TimeUnit.MILLISECONDS)) {
return true;
}
// Try distributed
RLock distributedLock = redisson.getLock(f"idem:{key}");
try {
return distributedLock.tryLock(timeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
// Fallback to DB row lock
// ... implement with SELECT FOR UPDATE
}
}
7. CLEANUP & RETENTION
TTL-Based Cleanup
-- PostgreSQL function for cleanup
CREATE OR REPLACE FUNCTION cleanup_idempotency()
RETURNS void AS $$
BEGIN
-- Delete expired keys
DELETE FROM idempotency_keys
WHERE expires_at < NOW()
AND status = 'completed';
-- Archive old audit logs
INSERT INTO audit_log_archive
SELECT * FROM audit_log
WHERE timestamp < NOW() - INTERVAL '90 days';
DELETE FROM audit_log
WHERE timestamp < NOW() - INTERVAL '30 days';
END;
$$ LANGUAGE plpgsql;
-- Run every hour
SELECT cron.schedule('cleanup-idempotency', '0 * * * *', 'cleanup_idempotency()');
Compaction Strategy
class IdempotencyCompactor:
def compact_saga(self, saga_id: str):
"""Keep only latest state per saga step"""
steps = self.repo.get_saga_steps(saga_id)
for step_name, records in groupby(steps, key=lambda r: r.step_name):
# Keep latest completed, archive others
latest = max(records, key=lambda r: r.completed_at)
self.archive_duplicates(step_name, saga_id, latest.id)
8. MONITORING & ALERTING
Key Metrics
# Idempotency effectiveness
idempotency_duplicates_total{service="order"}
idempotency_lock_contention_total
idempotency_processing_duration_seconds
# Saga-specific
saga_steps_total{saga_type="order_creation",status="completed"}
saga_compensations_total
saga_duration_seconds{step="payment_process"}
# Audit coverage
audit_log_incomplete_total{reason="missing_idempotency_key"}
Alert Rules
alerts:
- alert: HighDuplicateRate
expr: rate(idempotency_duplicates_total[5m]) > 0.1
for: 10m
annotations:
description: "High duplicate detection rate"
- alert: SagaStuck
expr: saga_steps_total{status="pending"} - saga_steps_total{status="completed"} > 5
for: 30m
annotations:
description: "Saga steps stuck in pending state"
9. IMPLEMENTATION CHECKLIST
Per Service:
Infrastructure:
Client Guidelines:
- Generate keys on client side
- Include business context in key naming
- Retry with same key only for identical requests
- Include correlation IDs across service boundaries
10. FAILURE SCENARIOS & HANDLING
| Scenario | Handling |
|---|
| Lock timeout | Return 409 Conflict or 423 Locked with retry-after |
| Database unavailable | Fallback to Redis-only mode (reduced guarantees) |
| Saga compensation failure | Manual intervention flag + alert |
| Audit log write failure | Continue processing, async retry queue |
| Clock skew | Use logical timestamps (incrementing sequence per saga) |
11. PERFORMANCE OPTIMIZATIONS
- Bloom Filters: Pre-filter obvious duplicates before DB lookup
- Connection Pooling: Dedicated pool for idempotency queries
- Read Replicas: Route audit queries to replicas
- Caching: Cache recent idempotency keys (5 min TTL)
- Batch Operations: Bulk insert audit logs (async)
12. SECURITY CONSIDERATIONS
- Key Entropy: UUIDs must be cryptographically random (v4)
- Key Isolation: Don't expose internal DB IDs in client keys
- Access Control: RBAC on audit logs (compliance requirement)
- Data Masking: PII in request/response bodies may need masking in logs
- Key Rotation: Consider for long-running sagas (>30 days)
13. COMPLIANCE & RETENTION
| Data Type | Retention | Encryption | Access Log |
|---|
| Idempotency keys (active) | 24-72 hours | At rest | Yes |
| Audit logs (active) | 90 days | At rest + transit | Yes |
| Audit logs (archive) | 7 years | At rest | Yes |
| Compaction metadata | Indefinite | At rest | Yes |
This architecture provides:
- Strong idempotency across all integration patterns
- Full auditability with append-only logs
- Scalability through layered locking
- Resilience with fallback strategies
- Operational visibility through monitoring
The key insight is treating idempotency as a cross-cutting concern with a shared repository while respecting the boundaries of REST (request/response), MQ (message delivery), and Sagas (multi-step workflows). The audit layer ensures every decision is traceable for compliance and debugging.