Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Distributed Systems: Duplicate Prevention & Idempotency Implementation Patterns

Distributed Systems: Duplicate Prevention & Idempotency Implementation Patterns

This article details four duplicate request prevention strategies — unique ID tables, distributed locks, token mechanisms, and state machines — and four idempotency approaches — database unique constraints, optimistic locking, global idempotency tokens, and state machine flow control — with step-by-step flows and trade-off analysis for distributed architectures.

1. Distributed Request Deduplication Strategies

In distributed environments, client retries, network jitter, gateway timeout retries, or message queue redelivery can cause the same request to reach the service multiple times. Request deduplication aims to identify and discard duplicate requests so that a business logic executes effectively only once for identical requests, preventing data redundancy and errors while serving as a prerequisite for interface idempotency.

1.1 Unique Request ID with Deduplication Table

This strong-consistency approach uses a database or persistent store. The core idea: generate a globally unique identifier for each business operation and validate before processing.

Generate ID: Client or upstream service generates a globally unique request_id before a write request.

Carry ID in request: Client sends request_id with business parameters.

Atomic insert validation: Before core logic, service attempts INSERT INTO deduplication_table (request_id) VALUES (?).

Result handling: (a) Insert succeeds → new request, proceed with business logic. (b) Insert fails with unique key conflict → request_id already processed; capture exception, treat as duplicate, discard or return prior result without executing business logic.

Deduplication table flow
Deduplication table flow

Advantages: high reliability via database ACID. Disadvantages: every request requires a DB write, making the database a bottleneck under high concurrency. Requires cleanup mechanism to prevent unbounded growth. Usually implemented by defining a unique key on the business table rather than a separate deduplication table.

1.2 Distributed Locks

Distributed locks control concurrency, ensuring a critical code block runs on only one node at a time, indirectly achieving deduplication.

Construct lock key: Service builds a unique lock identifier from request parameters, e.g., lock:payment:order_id_123.

Attempt lock acquisition: Use Redis SETNX or ZooKeeper ephemeral nodes.

Result handling: (a) Lock acquired → no other request processing this business; execute logic, release lock after completion. (b) Lock acquisition fails → another thread/process is handling it; treat current request as duplicate, return immediately or discard.

Core advantage: concurrency control, suitable for "in-progress" deduplication to prevent concurrent modification of the same resource. Implementable via Redis or ZooKeeper. Drawbacks: adds complexity — must handle lock timeout, renewal, safe release to avoid deadlocks. Lock granularity is critical; too coarse reduces throughput.

1.3 Token Mechanism

Prevents duplicate form submissions from user mis-clicks or flawed frontend logic. Two phases: obtain token, use token.

Request token: Client requests a token when user accesses the form page.

Issue and store token: Server generates a unique token (e.g., UUID), stores in Redis with short TTL, returns to client. Client places token in a hidden form field.

Submit with token: Form submission must include the token.

Atomic verify and destroy: Server uses atomic operation (Redis + Lua script) to verify and delete token. (a) Token exists and deleted → process business logic. (b) Token missing (consumed by another request or expired) → reject as duplicate.

Token mechanism flow
Token mechanism flow

Effectively blocks frontend duplicate requests, simple to implement. Requires frontend cooperation, adding an extra round-trip.

1.4 State Machine Constraints

For business objects with clear lifecycles (orders, tickets), use a state machine model. Operations must follow predefined state transitions; any transition not allowed from the current state is treated as illegal or duplicate.

Define states: e.g., order states: PENDING_PAYMENT, PAID, SHIPPED, COMPLETED, CANCELLED.

Receive operation request: e.g., "pay order".

Validate current state: Read order's current state from DB or cache.

Judge transition legality: (a) If state is PENDING_PAYMENT, "pay" is legal; execute payment logic, update state to PAID. Use optimistic locking (version) to prevent concurrent state conflicts. (b) If state is already PAID, another "pay" request is duplicate; reject directly.

Tightly coupled with business logic, clear and reliable. Prevents duplicates and ensures process correctness. Limitation: only applies to workflows that can be modeled as finite state machines.

2. Distributed Interface Idempotency Implementation Strategies

Idempotency (mathematical concept): an operation produces the same effect/result whether executed once or multiple times. In distributed systems, retries due to unreliable networks are normal; guaranteeing write idempotency is critical to avoid data corruption, financial loss, etc.

2.1 Database Unique Constraints

Create a unique index on field(s) that uniquely identify a business transaction/entity, leveraging the database to block duplicate inserts.

Identify unique business key: Determine a field that uniquely identifies a transaction/entity during table design.

Create unique index: UNIQUE INDEX on that field.

Execute insert: Service runs INSERT to create a record.

Handle result: (a) First request: INSERT succeeds, data created. (b) Retry requests: transaction_id exists, INSERT fails with unique key conflict; application catches error, treats as duplicate creation, guaranteeing idempotency of "create".

Unique constraint flow
Unique constraint flow

Simple, efficient, guarantees eventual consistency. Primarily for INSERT scenarios; UPDATE needs other strategies. Under high-concurrency writes, unique index conflict checks can pressure the database.

2.2 Optimistic Locking / Versioning

Classic solution for idempotent UPDATE operations. Assumes no concurrent modification until commit-time check. Implemented via a version or timestamp column.

Read data and version: SELECT data, version FROM my_table WHERE id = ?.

Compute business logic: In-memory calculation based on read data.

Update with version check:

UPDATE my_table SET data = 'new_data', version = version + 1 WHERE id = ? AND version = 'old_version'

.

Check update result: (a) Rows affected = 1 → no other request modified data; update succeeds. (b) Rows affected = 0 → version changed by another request; current operation based on stale data. Treat as idempotency/conflict; abort or re-read and retry.

Optimistic locking flow
Optimistic locking flow

Avoids long-held pessimistic locks; performs well in high-concurrency read-heavy, write-light scenarios. Solves UPDATE idempotency. Drawback: adds business logic complexity; application must handle retry logic on update failure.

2.3 Global Idempotency Token

Decouples idempotency validation from business logic; works for INSERT, UPDATE, DELETE. Token represents a complete business operation, not just an HTTP submission.

Generate token: Caller generates a globally unique idempotency_key before a business operation requiring idempotency.

Carry token in request: Pass via header or body.

Atomic check and lock: Server uses idempotency_key as key, attempts atomic creation of a placeholder in shared cache (Redis SET key value NX EX).

Process flow: (a) First request: SET succeeds → first time for this key. Execute business logic. On completion, store result in cache associated with the key, set longer TTL. (b) Retry request: SET fails → key exists. Server reads and returns previous execution result from cache, guaranteeing idempotency.

Global idempotency token flow
Global idempotency token flow

Flexible, non-invasive to core business tables, optimizes retry experience by returning cached results. Depends on highly available distributed cache (Redis). Token generation, propagation, and storage management add system complexity.

2.4 State Machine Flow Control

Strictly control business entity state transitions; operation executes only in specific states, achieving idempotency. Consistent with deduplication state machine but emphasizes that the operation's effect on final state is unique. Whether an operation executes depends on whether the current state permits it.

Load entity and state: On request, load business entity and its current state.

Validate state transition: Per predefined state machine, check if current state allows the requested operation. E.g., only PENDING_SHIPMENT allows "ship".

Execute and update state: (a) Transition legal → execute business operation, atomically (usually with optimistic lock) update entity to next state. (b) Transition illegal → reject directly, return error. Any number of illegal requests leaves state unchanged, guaranteeing idempotency.

Highly coupled with domain model, rigorous logic; once modeled, idempotency is naturally assured. Limitation: only for business flows with clear, finite states. Not applicable to stateless generic interfaces.

Distributed system robustness requires treating deduplication and idempotency as core architectural concerns. Request deduplication safeguards data correctness via unique IDs, distributed locks, tokens, and state machines to filter unexpected duplicate requests. Interface idempotency ensures that under unreliable networks, database constraints, optimistic locking, global tokens, and state machines prevent retries from causing unintended side effects.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

distributed systemsstate machineidempotencydistributed locksoptimistic lockingduplicate preventiontoken mechanismdeduplication tableidempotency tokenunique constraints

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion