Practice scene spike grab a red envelope

Practice spike grab a red envelope scene common solution

Article Address: blog.piaoruiqing.com/blog/2019/0...

Foreword

Spike scene almost everywhere in life, whether it is buying merchandise, or Spring Festival ticket grab a ubiquitous red envelopes, will involve spike scene. In the interview, spike design business has become a hot topic for the interviewer and the candidate Jinjin Lock Road.

Next, we will share grab a red envelope for the implementation spike scene, common implementation includes a red envelope business, bottlenecks and optimization.

analysis

Scenes

There are a lot of red envelopes of application scenarios, such as random red envelopes, red envelopes and other quotas, even in conjunction with other red varieties such as promotional services rob shopping allowance. But from a technical point of view, regardless of how many games are played changes, the core is similar of:

  • Stability: Go On large burst of traffic to ensure the envelopes can be successfully distributed.
  • Accurate: the data must be properly distributed over the situation does not arise.

business

Grab a red envelope may be due to different business needs to produce many variants, designed to be abstract enough not to grab the cash and grab a red envelope red envelope shopping allowance to write multiple copies of similar code to grab a red envelope of post-operation can be used as a message, by different service module themselves.

technology

Grab a red envelope core business is not complicated, the key point is to cope with high concurrency, resource contention and so on.

  • High concurrency: asynchronous, extended lateral load balancing, limiting the like.

  • Reading and writing less: cache.

  • Resource contention: other atomic operation, the cache can be controlled, or database level script Lua Save As used inventory operations.

Scheme I - pre-allocation

Applicable scene

Red number is relatively reasonable , very few generate surplus inventory situation, the magnitude of the situation is not the user.

  • Advantages: simple, easy to deal with very high concurrency cache
  • Inadequate: the frequent issuance of a large number of red envelopes will lead to more write-once assigned a large number of records, if not many people receive, will have a lot of invalid data.

A brief description

Pre-allocated at the time of issuing a red envelope, based on the total amount and the number of red envelopes, in accordance with the established allocation algorithm, created all of the red envelope allocation record in advance. Just assign the red record time of collection to be updated.

More suitable system issued a red envelope (for all user groups, a label, red issue will be receiving basic finish), red envelopes are not suitable user group (can not control the number of recipients of red envelopes, red envelopes case when the number is far greater than the number of groups , the more invalid data, such as payment in a group of 10 people as a red number 1000).

Implementation details

Process

  • In the rush to open before the red envelope, red envelope pre-allocated to receive a good record, to receive the recording of user ID is negative.

  • After opening rush, the only open entrance to receive a red envelope

  • The core operation is to receive a red envelope allocated to update records:

    -- 此处划重点 ( ̄▽ ̄)"
    UPDATE IGNORE record SET user_id = {userId}, gmt_receive = UNIX_TIMESTAMP() WHERE red_envelop_id = 1 AND user_id < 0 LIMIT 1;
    -- red_envelop_id + user_id 有唯一约束
    复制代码

Red envelopes release record

ID total amount Quantity ...
1 100 3 ...

Red envelope allocation record

unique: 红包ID+领取用户ID

ID Red envelope ID Money Receive a user ID Receive time ...
1 1 10 -1 0 ...
2 1 60 -2 0 ...
3 1 30 -3 0 ...

Remark

  • UPDATE IGNORE ... LIMIT 1 : To solve the resource contention issues, ensuring concurrent requests receive red packets of data correctness.
  • red_envelop_id+ user_id: Creating indexes and unique constraints, to ensure the same for the same user can only receive a red envelope.
  • Pre-assigned user_ida negative value: Because red_envelop_id+ user_idhas a unique constraint.
  • For small-scale activities generally traffic in this way to achieve simple, low cost, not only with the introduction of the cache case a basic MySQL can Go On.
[Copyright]
This article published in Pu Ruiqing's blog , allows non-commercial use reproduced, reprinted but must retain the original author Pu Ruiqing and links: blog.piaoruiqing.com . If the authorization aspects of consultation or cooperation, please contact E-mail: piaoruiqing @ Gmail. COM .

Option II - Real-time allocation

Applicable scene

Number of recipients can not be estimated, frequent refund, as the group red envelopes (remaining refund frequent)

Implementation details

Process

  • Before rush to open the red envelopes information loaded into the cache, load time can be some of the first long
  • Grab a red envelope: read (not the load) from the cache, the cache allocation envelopes atomic updates (if payment is completed directly returns a failure)
  • Written to the database (data validity check) after the cache update

Red envelopes release record

ID total amount Quantity balance The remaining amount ...
1 100 3 100 3 ...

Red envelope allocation record

unique: 红包ID+领取用户ID

ID Red envelope ID Money Receive a user ID Receive time ...
... ... ... ... ...

Remark

  • First cache load time for a little longer: there may be a large burst of traffic when a red envelope just began issuing, this time to load the cache DB inappropriate.
  • Cache database can not ensure strong and consistent: the correctness of the data by the database maintenance, such as: cache deducted the amount of red envelopes, but the anomaly occurred while updating the database, then the cache does not need to be rolled back, until a cache miss can be reloaded . (so the cache may be time for a few seconds, not too long)
  • Update the cache may consider using Lua script to ensure atomicity.
  • Real-time allocation will not produce red invalid record for most scenes, but to achieve more complex than pre-allocated.

Details and Optimization

  • Client click frequency control can reduce the flow to a certain extent.

  • After the red light led out in a buffer layer of intercepting all the requests, the direct return failure.

  • Gateway limiting layer.

Epilogue

Spike scenario characterized by high concurrency, reading and writing small, resource contention, each point will need to select the appropriate solution, such as the use of caching frequently read to solve the problem, the use of the queue solve database performance bottlenecks in accordance with its business scenarios.

Grab a red envelope for business, the pre-allocation and real-time allocations are effective solutions, advantages and disadvantages, what specific choice will depend on business needs.

Welcome to public concern number (Code poetic):

[Copyright]
This article published in Pu Ruiqing's blog , allows non-commercial use reproduced, reprinted but must retain the original author Pu Ruiqing and links: blog.piaoruiqing.com . If the authorization aspects of consultation or cooperation, please contact E-mail: piaoruiqing @ Gmail. COM .

Guess you like

Origin juejin.im/post/5d6b86c651882559734090b3