How-To Guide

How to Implement Idempotent Stream Processing

Make stream consumers idempotent so at-least-once delivery, retries and rebalances never double-apply an event or lose one silently.

On this page

  1. Introduction
  2. Why At-Least-Once Is the Norm
  3. Idempotency Keys and Deduplication
  4. Idempotent Effects Versus Dedup Only
  5. Offsets and Processing Order
  6. Handling Rebalances
  7. Monitoring Idempotency
  8. Common Pitfalls and Conclusion

Introduction

Streaming systems deliver at least once: an event may be redelivered after a consumer crash, a rebalance or a retry, and the consumer must cope. A consumer that applies each delivery blindly double-counts, double-charges or double-sends. Idempotency is the property that applying the same event twice has the same effect as applying it once, and building it deliberately is what makes at-least-once delivery safe. The alternative, exactly-once end to end, is expensive and often unavailable across systems, so idempotent consumers are the practical guarantee.

Why At-Least-Once Is the Norm

Delivering a message exactly once across a network requires coordination that most systems do not provide end to end. What they provide is at-least-once: a message is retried until acknowledged, so it is never silently lost, but it may be delivered more than once. The consumer must therefore tolerate duplicates.

Exactly-once within a system, such as a stream processor with transactional state, is possible, but the boundary is usually the system. The moment you write to an external database or call an external API, you are back to at-least-once across that boundary, and idempotency is what makes the boundary safe.

# delivery guarantees
at-most-once:  may lose, never duplicates   (rarely acceptable)
at-least-once: never loses, may duplicate   (the practical default)
exactly-once:  neither, but only within a system boundary
# across an external DB/API you are at-least-once again -> need idempotency

Idempotency Keys and Deduplication

Give every event a unique id and record which ids have been processed. When an event arrives, check the id: if it is already recorded, skip the work; otherwise process it and record the id atomically with the effects. The atomicity matters: recording the id and writing the effect must be one transaction, or a crash between them causes a double apply or a skipped event.

The dedup record needs a retention policy: keep ids long enough to cover the maximum redelivery window, which depends on the source’s retry and retention settings. Keeping them forever grows unbounded; keeping them too briefly lets a slow redelivery slip through. Size the window from the source’s maximum retry horizon.

-- The effect and the dedup record in ONE transaction.
BEGIN;
INSERT INTO processed_events (event_id, processed_at)
  VALUES ($1, now())
  ON CONFLICT (event_id) DO NOTHING;
-- if the insert did nothing, the event was already processed:
--   check row count and skip the effect
INSERT INTO orders (id, amount_cents) VALUES ($2, $3)
  ON CONFLICT (id) DO NOTHING;   -- effect is ALSO idempotent
COMMIT;

Idempotent Effects Versus Dedup Only

Two layers work together. The dedup record catches the duplicate; an idempotent effect makes the write itself safe to repeat. Making the effect idempotent, with an upsert keyed on a natural key or an insert that ignores a conflict, means a duplicate does not corrupt even if the dedup check is missed.

Idempotent effects are especially valuable because they do not depend on the dedup state being correct or complete. An upsert that sets a value to the same result is naturally idempotent; an increment is not, unless it is keyed so a duplicate is ignored. Prefer writes that produce the same state regardless of repetition.

-- Idempotent effect: upsert keyed on a natural key, not an increment.
INSERT INTO account_balances (account_id, balance_cents, last_event_id)
VALUES ($1, $2, $3)
ON CONFLICT (account_id) DO UPDATE
  SET balance_cents = EXCLUDED.balance_cents,   -- set, not add
      last_event_id = EXCLUDED.last_event_id
  WHERE EXCLUDED.last_event_id > account_balances.last_event_id; -- monotonic guard
-- a duplicate delivery sets the same balance, not a doubled one

Offsets and Processing Order

The consumer’s offset records how far it has processed. Commit the offset only after the effect is durably applied, so a crash re-delivers rather than skips. But committing after the effect creates the possibility of re-delivering an event whose effect was applied, which is exactly why the effect must be idempotent.

Per-partition ordering is preserved by the source; across partitions it is not. If an event’s correctness depends on another event’s order, they must be in the same partition, keyed consistently, or the consumer must handle out-of-order arrival. Idempotency does not fix ordering; it fixes duplication.

# offset commit discipline
1. process the event (durable effect)
2. commit the offset (after, never before)
=> a crash re-delivers the last event(s): at-least-once
=> the effect must be idempotent so re-delivery is safe
# ordering: per partition only; key related events to the same partition

Handling Rebalances

When partitions are reassigned between consumers, in-flight work can be interrupted and events redelivered. The consumer must finish or abort cleanly on rebalance: finish the current event and commit its offset before yielding the partition, or abort without committing so it is redelivered. Both are safe with an idempotent effect.

Track in-flight events so a rebalance does not leave a partial apply. If the effect is a transaction, an abort rolls it back; if it is a sequence of writes, make the sequence idempotent so a re-delivery completes it rather than duplicating it. The rebalance is exactly when duplicates are most likely, so it is the case to test.

# rebalance checklist
[ ] on partition revocation: finish current event + commit, or abort uncommitted
[ ] in-flight effects are transactional (rollback on abort) or idempotent
[ ] test a forced rebalance under load and assert no double-apply
[ ] duplicates are expected around rebalances, not exceptional

Monitoring Idempotency

Emit a counter of duplicate deliveries detected and a counter of events applied. A rising duplicate rate near a rebalance is expected; a steady duplicate rate may indicate the source is retrying excessively. The absence of any duplicates might mean your dedup is too aggressive and skipping legitimate events, so watch for skipped-event counters too.

Also alert on gaps: if offsets advance without events being applied, or applied events do not match the source count, something is being dropped. Idempotency should make duplication harmless, but silently losing events is a different and worse failure that the same instrumentation should catch.

# idempotency telemetry
duplicates_detected_total     rising near rebalance = normal
events_applied_total          should track source rate
skipped_as_duplicate_total    high/steady = dedup too aggressive?
source/consumer count gap      events lost (a worse failure than dupes)
# alert on loss, tolerate duplicates

Common Pitfalls and Conclusion

Do not commit the offset before the effect, or a crash loses events. Do not record the dedup id outside the effect’s transaction, or a crash between them double-applies. Do not use increments for effects that must be idempotent. Do not keep dedup ids forever or for too short a window. And do not confuse idempotency with ordering; they solve different problems.

At-least-once delivery means duplicates are normal, so the consumer must be idempotent: a dedup record and an effect written together, an effect that produces the same state on repetition, offsets committed only after the effect, and rebalances handled so in-flight work finishes or aborts cleanly. Done well, redelivery is harmless and the stream is safe to retry.

Sources: Confluent: Exactly-once semantics, Kafka: Consumer rebalancing, Designing Data-Intensive Applications (Kleppmann).

FAQ

Where does the dedup record need to live?
In the same transaction as the effect. If the dedup id is recorded separately and a crash happens between the two, you either double-apply (id written, effect not) or skip (effect applied, id not). One transaction, or an idempotent effect that makes the record redundant.
Does idempotency give me exactly-once processing?
Effectively, for the effect. Redelivery still happens, but each applies the same state, so the outcome equals exactly-once. Ordering is separate: idempotency handles duplicates, not out-of-order events.

Related Examples