Ensuring API Idempotency: Concepts, Importance, and Practical Solutions
This article explains the concept of idempotency in distributed systems, why it is crucial for scenarios like payments and order submission, and presents practical solutions such as database unique keys, optimistic locking, the Post/Redirect/Get pattern, and anti‑repeat token mechanisms, complete with code examples.
Idempotency is a fundamental concept in mathematics and computer science where applying an operation multiple times yields the same result as applying it once. In the context of APIs, idempotency means that repeated requests to the same resource should have identical effects, preventing issues like duplicate orders or multiple charges.
Idempotency is essential in payment and order‑submission scenarios, where network failures or user actions can cause repeated submissions. Without proper handling, a user might unintentionally create multiple orders or be charged multiple times.
Solutions for Achieving Idempotency
Database Unique Primary Key
Using a unique primary key (or unique index) ensures that only one record with a given identifier can be inserted, making it suitable for insert‑type operations. The primary key should be a globally unique ID rather than an auto‑increment value to work in distributed environments.
CREATE TABLE `table_name` (
`id` int NOT NULL AUTO_INCREMENT,
`orderid` varchar(32) NOT NULL DEFAULT '' COMMENT '唯一id',
PRIMARY KEY (`id`),
UNIQUE KEY `uq_orderid` (`orderid`) COMMENT '唯一约束'
) ENGINE=InnoDB;Database Optimistic Lock
Optimistic locking adds a version field to a row and checks this version during updates. If the version has changed, the update fails, preventing lost updates from concurrent requests.
select version from tablename where xxx; update tablename set count = count + 1, version = version + 1
where version = #{version};Post/Redirect/Get (PRG) Pattern
The PRG pattern avoids duplicate form submissions by redirecting the client to a GET request after processing a POST. Refreshing the final page triggers only the GET, not the original POST.
Anti‑Repeat Token
A token generated by the server (often stored in Redis) is sent to the client and included in subsequent requests. The server validates the token, deletes it, and proceeds with business logic, ensuring each operation is executed only once.
These techniques can be combined and adapted to specific business scenarios to guarantee that each operation is performed exactly once, preserving data consistency and preventing duplicate actions.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
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.