<p class="summary">
Idempotent event processing with a dedicated store: recording the MessageId of each handled event in Redis, skipping duplicates, and the tradeoffs (no shared transaction, TTL sizing, durability) of this most generic technique.
</p>

<div class="img-container">
  <img src="https://blog.techdominator.com/imgs/IdempotentEventProcessingPart2Cover.webp" width="693" height="462" alt="Idempotent Event Processing With Azure Event Hubs Part 2 Cover" fetchpriority="high" />
</div>

In the [previous post](https://blog.techdominator.com/article/idempotent-event-processing-with-azure-event-hubs-part-1.html), we discussed why Azure Event Hubs consumers should be idempotent: duplicates can appear [while sending](https://blog.techdominator.com/article/idempotent-event-processing-with-azure-event-hubs-part-1.html#duplicates-while-sending) and [while receiving](https://blog.techdominator.com/article/idempotent-event-processing-with-azure-event-hubs-part-1.html#duplicates-while-receiving), and checkpointing alone can't remove them. We also reviewed the [theory and the state of the art](https://blog.techdominator.com/article/idempotent-event-processing-with-azure-event-hubs-part-1.html#idempotent-processing-theory-and-state-of-the-art).

This post is the first of four, each covering one technique I've found useful for implementing idempotent event processing. The techniques are ordered from most generic to most domain-specific. We start with the most generic one: a dedicated store that records the events already handled, and the tradeoffs that come with it.

For each technique, you'll see whether it uses *explicit deduplication* or relies on *message semantics*, as discussed in [Enterprise Integration Patterns](https://blog.techdominator.com/article/idempotent-event-processing-with-azure-event-hubs-part-1.html#enterprise-integration-patterns). 

For simplicity, the examples focus on one consumer's processing logic. Making non-transactional side effects, such as calling an external system, safe is beyond the scope of this series.

<i class="fa fa-github" aria-hidden="true"></i> **Full working sample** [is available on Github as usual.](https://github.com/MissaouiChedy/BlogSamples/tree/main/AzureEventHubsIdempotentProcessing)


## Remember What You Processed

**Type:** explicit deduplication.

The first technique is the most generic one: the consumer keeps a record of the events it already handled, and skips an event when its identifier is in that record. It doesn't depend on any business data, which makes it usable when the side effect has **no natural state** to inspect.

The code in this section comes from the `IdempotencyTechnique1` project of the `AzureEventHubsIdempotentProcessing` sample.

In the sample, the consumer handles `OrderPlaced` events and sends an order confirmation email for each one. This is a good fit for the technique because an email can't be queried afterwards ("was this email already sent?") and can't share a transaction with anything else.

```csharp
public record OrderPlaced(
    string OrderId,
    string CustomerEmail,
    decimal Total,
    DateTime PlacedAt);
```

The `IdempotencyTechnique1` console app runs a sender and a consumer concurrently, on a 3-partition event hub with 1 day of retention. The consumer relies on three elements:

- **A checkpoint store:** a blob container, updated every 2 events per partition to make replays easy to trigger.
- **A processed events store:** an Azure Managed Redis instance holding the identifiers of processed events.
- **A fake email sender:** prints a line to the console, standing in for an email provider.

The deduplication key is the [`MessageId`](https://learn.microsoft.com/en-us/dotnet/api/azure.messaging.eventhubs.eventdata.messageid?view=azure-dotnet) of the event. It is set by the producer, **once per logical event and before sending.**

```csharp
EventData eventData = new(BinaryData.FromObjectAsJson(order))
{
    /*
     * Assigned once per logical event,
     * so that SDK send retries carry
     * the same value
     */
    MessageId = Guid.NewGuid().ToString()
};

await eventHubProducerClient.SendAsync(
    [eventData],
    new SendEventOptions { PartitionKey = order.OrderId });
```

This ordering matters. As discussed in [Duplicates While Sending](https://blog.techdominator.com/article/idempotent-event-processing-with-azure-event-hubs-part-1.html#duplicates-while-sending), a retried send creates a second event with its own offset and sequence number. Only a value assigned by the producer before the first attempt can tell the consumer that both events represent the same business fact.

To reproduce this, the sample can resend an already sent order with the same body and the same `MessageId`. This is what a producer retry after a lost acknowledgment looks like from the consumer side.

The responsibility of the `ProcessedEventsStore` is to answer one question ("did I see this `MessageId`?") and to record new ones. Each identifier becomes a Redis key with a TTL.

```csharp
public async Task<bool> IsProcessedAsync(string messageId)
{
    /*
     * EXPIRE only succeeds on an existing
     * key: checks and restarts the TTL
     * in one atomic command
     */
    return await _cache.KeyExpireAsync(
        GetProcessedEventKey(messageId),
        _processedEventTtl);
}

public async Task<bool> MarkAsProcessedAsync(string messageId)
{
    return await _cache.StringSetAsync(
        GetProcessedEventKey(messageId),
        DateTime.UtcNow.ToString("o"),
        /*
         * The key expires on its own
         */
        _processedEventTtl,
        /*
         * SET NX: the first record
         * is kept
         */
        When.NotExists);
}

private string GetProcessedEventKey(string messageId)
{
    return $"{EventhubNamespace}|{Eventhub}|{ConsumerGroup}"
        + $"|processed|{messageId}";
}
```

Three details are worth noting:

- **The key is scoped by consumer group.** Each consumer group is an independent reader of the event hub, so a `MessageId` processed by one group must not make another group skip the event.
- **A skipped duplicate restarts the TTL.** A resent event is retained by the event hub from its own enqueue time, not from the original's. Without the refresh, a duplicate enqueued 20 hours after the original, and replayed 6 hours later, would find the key expired. `KeyExpireAsync` only succeeds on an existing key, so the check and the refresh are a single atomic command.
- **`SET NX` keeps the first record, it doesn't prevent concurrent duplicates.** When two consumers record the same `MessageId`, only one of them gets `true` back, but by then both have already sent the email (see the [tradeoffs](#tradeoffs-of-a-dedicated-store)). The sample doesn't use the return value.

At runtime, the handler runs the same sequence for every received event. Consider the following simplified version of the sample's `ProcessEventHandler`:

```csharp
string? messageId = eventArgs.Data.MessageId;

if (await _processedEventsStore.IsProcessedAsync(messageId))
{
    Console.WriteLine("RECEIVER: ==> Already processed, skipped");
}
else
{
    OrderPlaced order = eventArgs.Data.EventBody
        .ToObjectFromJson<OrderPlaced>()!;

    await _emailSender.SendOrderConfirmationAsync(order);

    /*
     * Failure window: a crash here
     * sends a duplicate email on
     * replay
     */
    await _processedEventsStore.MarkAsProcessedAsync(messageId);
}

await CheckpointIfThresholdReachedAsync(eventArgs, partitionId);
```

The order of operations is the core of the technique: check, perform the side effect, record the identifier, and only then let the checkpoint logic run. A skipped event is still counted towards the checkpoint, otherwise a partition made of duplicates would never advance.

For brevity, the sample logs failed events instead of retrying them, and assumes every event carries a `MessageId`. A production consumer would need to decide what to do with events that don't.

The main advantage is that **no natural state is required.** Any handler can be wrapped this way, including ones whose side effect is opaque, such as sending an email or calling an external API.

## Tradeoffs of a Dedicated Store

The downsides are more numerous, and they explain why the next techniques exist:

- **The two stores can't be updated in the same transaction.** The email provider and Redis don't share a transaction, so the write order is a choice. Recording the identifier **after** the side effect (as the sample does) risks a duplicate email if the process crashes in between. Recording it **before** risks losing the email: the replay is skipped while the email was never sent. As discussed in [Does Checkpointing At Every Event Solve This?](https://blog.techdominator.com/article/idempotent-event-processing-with-azure-event-hubs-part-1.html#does-checkpointing-at-every-event-solve-this), I would prefer duplicates over losses here.
- **Concurrent duplicates still have a window.** The `IsProcessedAsync` check and the side effect aren't atomic. Handlers of a given partition run sequentially, but when partition ownership changes, two consumers can both pass the check before either one records the identifier. `SET NX` keeps the record consistent, it doesn't stop the second email.
- **The TTL must exceed the worst-case duplicate window.** If an identifier expires and a duplicate arrives afterwards, the duplicate goes through. The window has two parts: replays, which can't reach further back than the event hub retention (1 day), and producer retries, which can resend an event long after the original. Restarting the TTL on each skipped duplicate covers the replays of a resent event, but not a retry that first arrives after the key expired. In the sample the producer resends within a run, so a 25 hours TTL covers both. A longer retention or a longer producer retry window requires a longer TTL, and a larger store.
- **Durability is on you.** The sample uses a single Azure Managed Redis node without high availability and with the `VolatileTTL` eviction policy, which evicts keys with the shortest TTL under memory pressure. A failover, a restart or an eviction silently forgets identifiers, and the corresponding duplicates are processed again. Treat the store as part of the correctness of your system, not as a disposable cache.
- **It adds a dependency and a round trip per event.** Each event costs at least one read, and one write for new events, on a store that must be available for the consumer to make progress.


## Closing Thoughts

A dedicated store is the most generic technique, since it can wrap any handler, including ones with an opaque side effect such as sending an email. The price is an extra dependency, a TTL to size, and a failure window between the side effect and the record that no write order fully closes.

When the side effect leaves a trace in your own data, you can remove the store. The next post, [Part 3 - Rely on Natural State](https://blog.techdominator.com/article/idempotent-event-processing-with-azure-event-hubs-part-3-rely-on-natural-state.html), uses the business data as the record of what was processed.
