01 What is interface idempotency

Interface idempotence means that the results of one or multiple requests for the same operation are consistent without side effects caused by multiple clicks. For an example of the simplest, and that is to pay, after users buy goods payment, your payment is successful, but to return the result of network anomaly, right now the money has been buckled, users click on the button again, this time will be the second deductions, successful, user queries the balance back to find more buckles money, running water record into two… , which does not guarantee the idempotency of the interface

02 Basic Ideas

The core is to determine whether two requests are the same operation. The usual method is to parse all the parameters of the request and determine whether the parameters are exactly the same. If the two parameters are the same, the submission is repeated. There is also a unique index to determine, such as shipping operations, an order can only be shipped once. Therefore, the unique order number can be used to determine whether two times are repeated submissions.

03 Concrete Implementation

  1. Define idempotent annotations to be applied to interfaces that require idempotent annotations
  2. When the project is started, idempotent annotations are scanned, specific interface URLS are parsed, URLS are bound to idempotent interfaces one by one, and map objects are generated, so as to quickly determine whether the interface needs idempotent judgment according to the URL
  3. New idempotent interceptor. Determine whether this request requires idempotent verification based on the URL (the data has been encapsulated in step 2 so you can quickly determine).
  4. A key value is generated for the request parameter according to a specific rule, based on which the specific value is obtained from Redis, or if null, it is the first (normal) access. Otherwise, the request is repeated and needs to be filtered.

04 Extension: current limiting

Scenario: A user can access an interface only 100 times per hour

Implementation: the user’s each access time is recorded in Redis, each access to obtain the first 100 access time. If the access time cannot be obtained, the user has not accessed the system for 100 times. If the time is obtained, the system checks whether the time is within one hour. If the time is within one hour, the user needs to limit traffic and cannot access the system any more. If not within one hour, the access record is removed from Redis.