Understanding Interface Idempotency and Implementation Strategies
This article explains what API idempotency is, why it is needed, which interfaces should be idempotent, and presents various implementation methods such as frontend interception, database unique indexes, optimistic and pessimistic locks, JVM locks, distributed locks, and token‑based approaches.
What is Interface Idempotency?
In programming, an idempotent operation yields the same effect no matter how many times it is executed.
API idempotency means the API can be called repeatedly and the final result remains consistent. Query APIs are naturally idempotent because multiple identical queries have no side effects.
Why Design API Idempotency?
This question is equivalent to why duplicate calls occur.
Frontend duplicate form submission
When users submit a form and the response is delayed due to network issues, they may click the submit button repeatedly, causing duplicate requests.
Malicious attacks
For example, a hacker may repeatedly submit votes, skewing results.
Timeout retries
Many RPC frameworks (e.g., Dubbo) add retry mechanisms, which can cause the same request to be sent multiple times.
Message duplicate consumption
When using MQ middleware, consumer timeouts or missing ACKs can cause message redelivery and duplicate consumption.
Which APIs Need Idempotency?
Implementing idempotency consumes resources, so it should not be added to every API. Operations like queries and deletions are naturally idempotent and do not require extra checks.
Thus, the decision depends on business logic; a reference table is provided.
How to Implement Idempotency
Frontend interception
Disable or hide the submit button after the first click to prevent duplicate submissions. However, this can be bypassed, so backend validation is also required.
Database unique index
Suitable for insert operations. Create a deduplication table with a unique index on a field that represents the request.
Process steps:
Create a deduplication table with a unique index.
Client sends request; server inserts request info into the table.
If insertion succeeds, the request is new and business logic proceeds.
If insertion fails, the request has been processed before and is rejected.
Database optimistic lock
Suitable for update operations. Add a version field to the table and include it in the WHERE clause.
Process steps:
Client sends request with version field.
Server updates with SQL that increments version and checks previous version.
update t set stock = stock - 1, version = version + 1 where id = #{id} and version = #{version}Database pessimistic lock
Process steps:
Client accesses service with business ID.
Server checks existence of the ID with an X lock.
If exists, treat as duplicate; otherwise, proceed.
JVM lock
Use JVM built‑in locks such as Lock or synchronized to guard the critical section, check if the order has been processed, then execute within a transaction.
JVM locks work only in single‑machine environments.
Distributed lock
Overcomes the single‑machine limitation of JVM locks.
Process steps:
Client obtains a unique business key.
Server attempts to store the key in Redis with SETNX and a timeout.
If successful, it's the first request and business logic runs.
If failed, the request is a duplicate and is rejected.
Token
Process steps:
Client requests a token; server generates a globally unique ID, stores it in Redis, and returns it.
Client includes the token in the subsequent request.
Server validates the token, processes the request, and deletes the token.
If validation fails, the token is missing, indicating a duplicate operation.
Note:
Use a Lua script to check and delete the token atomically.
Global unique IDs can be generated with Baidu uid‑generator or Meituan Leaf.
Summary
Idempotency ensures correct program execution, eliminates garbage data, and reduces unnecessary resource consumption. Using a distributed lock is recommended as a generic solution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
