Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
preface
Today, I would like to share with you some knowledge about idempotence in distributed, which belongs to the foundation and focus of distributed. After learning this article, you can learn the following knowledge:
- What is idempotence
- Why is idempotency guaranteed
- How do you guarantee idempotency
What is idempotence?
Take a specific example, for example, in a seckill system, for a seckill product, multiple times to initiate the order button, for the order interface, the interface must ensure that only one order record can be inserted, inventory can only be deducted once, this is idempotent.
Why is idempotency guaranteed?
For a single-node deployment system, you can add a map to the memory. After receiving a client request, you can add a key to the map. When the id is requested again next time, you can query the map.
For distributed, because the system is deployed on different machines, the above method cannot be used to solve the problem, but this problem must be considered, otherwise it will lead to a lot of problems, such as network fluctuation, the front end does not do shake prevention, etc., will cause the interface to be repeated requests.
Such as the deployment of the three machines, each machine A instance of the deployment of A system, when the user to launch A client request, because the network jam, although the background have receives the request, but the front return request fails, the user to submit A request, again much this leads to submit A request at A time, if not controlled, will generate multiple order information.
Spend elder brother also be met before a possible idempotence scene, WeChat pay friends should know the result, when we call WeChat unified payment, and complete the payment, WeChat platform will be carried out in the callback, then there will be a kind of situation, if we receive WeChat callback, but no return success brought WeChat, WeChat platform will continue to return to the business platform, In this case, we need to keep the interface idempotent.
How do you guarantee idempotency?
In distributed systems, idempotency can be guaranteed in three ways:
- Add a unique identifier on each request, such as an order ID when an order is paid. The same order ID can only be processed once;
- Add records in the database, for example, after wechat callback, modify the order status, or add record serial number, so that when wechat callback each time, the interface first check the database judgment, if there is already a record, directly return;
- Add a Redis middleware. In fact, this is similar to map in a stand-alone system. After each request is processed, the unique ID of the request will be recorded in Redis.