search
HomeBackend DevelopmentPHP TutorialPHP's method to solve blocking high-concurrency inventory prevention and control overstocking such as snap sales, flash sales, property grabs, and lottery draws

Nowadays, in the e-commerce industry, flash salesrush buying activities have become a common promotional method for merchants. However, the inventory quantity is limited, and if the number of people placing orders at the same time exceeds the inventory quantity, it will cause the product to be oversold or even the inventory to become negative. Another example: rush to buy train tickets, rush to buy real estate in forums, lottery and even popular Weibo comments can also cause blocking high concurrency problems. If no measures are taken, the server may be paralyzed in an instant. How to solve this problem?
Here are some ideas that I think are more feasible:

Option 1: Use message
queue to implement
can be based on messages
queue such as MemcacheQ. The specific implementation plan is as follows Let’s express itFor example, if there are 100 tickets for users to grab, then they can put these 100 tickets in the cache and do not lock them when reading and writing. When the amount of concurrency is large, about 500 people may successfully grab tickets, so that requests after 500 can be directly transferred to the static page at the end of the event. It is impossible for 400 out of 500 people to get the goods. Therefore, only the first 100 people can purchase successfully according to the order in which they enter the
queue. The next 400 people will go directly to the event end page. Of course, entering 500 people is just an example. You can adjust the number yourself. The activity end page must use a static page, not a database. This reduces the pressure on the database.
Option 2: When there are multiple servers, it can be implemented in the form of offloading

Suppose there are m tickets, n product servers receive requests, and x requests are forwarded randomly by the routing server
Directly Allocate m/n tickets to each product server
Make
counter in the memory of each product server, for example, allow m/n*(1+0.1) people to come in. When the memory
counter is full: People who enter later will jump directly to the static page where the activity ends,
notify the routing server that it will no longer be routed to this server (this is worth discussing).
The m/n*(1+0.1) individuals who come in from all the product servers are then forwarded to a payment server and enter the payment process to see who is faster. There are few people at this time, so locking and so on is simple.

Option 3. If it is a single server, you can use Memcache lock to implement

product_key is the ticket key
product_lock_key is the ticket lock key
When product_key exists in memcached, all users can Enter the order process.
When entering the payment process, first store add(product_lock_key, “1″) in memcached,
If the return is successful, enter the payment process.
If it fails, it means that someone has already entered the payment process, and the thread waits for N seconds and performs the add operation recursively.

Option 4: Use file exclusive lock

When processing an order request, use flock to lock a file. If the lock fails, it means that other orders are being processed. At this time, either wait or directly prompt the user "Server is busy" "
This article is going to talk about the fourth solution. The approximate code is as follows

Blocking (waiting) mode:
<?php $fp = fopen("lock.txt", "w+");
if(flock($fp,LOCK_EX))
{
//..处理订单
flock($fp,LOCK_UN);
}
fclose($fp);
?>




Non-blocking mode:
<?php $fp = fopen("lock.txt", "w+");
if(flock($fp,LOCK_EX | LOCK_NB))
{
//..处理订单
flock($fp,LOCK_UN);
}
else
{
echo "系统繁忙,请稍后再试";
}

fclose($fp);
?>


The above introduces PHP's ideas and methods to solve blocking high-concurrency inventory prevention and control overflows such as rush buying, flash sales, property grabbing, lottery, etc., including queues, flash sales, number of people, and counters. I hope friends who are interested in PHP tutorials can helped.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment