Design of flash kill system
I have written an article before about the design of the promotion system and mentioned flash sales/direct discounts/juhuasuan, but in actual work, I have never really done a flash sale system, so I made a hypothetical A simple flash sale system was created to “quench the craving”, and the promotional ideas still followed the design of the previous article.
Analysis
A large amount of traffic flows in during the flash sale, and queries are frequently refreshed before the flash sale starts. If a large amount of traffic hits the database instantly, it is very easy to cause the database to collapse. Therefore, the main job of the flash sale is to filter the traffic layer by layer and finally allow as little and as smooth traffic as possible to enter the database.
Usual flash sales involve a large number of users snapping up a small amount of goods. For needs like this, simply caching the inventory can filter a large amount of traffic before actually creating an order. But but but, it doesn’t seem to be challenging at all! To increase the difficulty a little bit, suppose our flash sale is like grabbing Xiaomi mobile phones, what if 1 million people grab 100,000 mobile phones? Queuing up during Xiaomi rush sales is one method (although the experience is not very good), and our flash sale design will be based on this idea in the future.When it comes to Xiaomi, I have to say that it made me know what "luck is also a part of strength!" Front-end current limiting method: random(0, 1) ? axios.post: wait(30, 'All finished!')The following is an analysis of some code details. In principle, the original business logic should be changed as little as possible.
In addition, there are no advanced gameplay such as service circuit breaker and multi-level caching in the following article, just a relatively simple business design.
StartThe operator adds a variant to the flash sale promotion in the background and sets the flash sale inventory/flash sale discount rate/start time and end time, etc. We can get something like Such data.// promotion_variant (促销和变体表「sku」的一个中间表) { 'id': 1, 'variant_id': 1, 'promotion_id': 1, 'promotion_type': 'snap_up', 'discount_rate': 0.5, 'stock': 100, // 秒杀库存 'sold': 0, // 秒杀销量 'quantity_limit': 1, // 限购 'enabled': 1, 'product_id': 1, 'rest': { variant_name: 'xxx', // 秒杀期间变体名称 image: 'xxx', // 秒杀期间变体图片 } }
# PromotionVariantObserver.php public function saved(PromotionVariant $promotionVariant) { if ($promotionVariant->promotion_type === PromotionType::SNAP_UP) { $seconds = $promotionVariant->ended_at->getTimestamp() - time(); \Cache::put( "promotion_variants:$promotionVariant->id", $promotionVariant, $seconds ); } }
Of course, we still use the original order api, and there is no problem in passing a logo on the front end.One thing that needs explanation is that placing an order is usually divided into two stepsThe first step is to "checkout (checkout)" to generate a checkout order. The user can select the address for the checkout order. , coupons, payment methods, etc. The second step is "confirm". At this time, the order will become confirmed, the inventory will be locked, and the user can make payment. Usually if payment is not made within the stipulated time, the order is canceled and the inventory is unlocked. So in the first step, users will be filtered and queued to prevent subsequent operations such as selecting addresses and coupons from impacting the database.
# CheckoutController.php /** * @param Request $request * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response * @throws StockException */ public function snapUpCheckout(Request $request) { $variantId = $request->input('variant_id'); $quantity = $request->input('quantity', 1); // 加锁防止超卖 $lock = \Cache::lock('snap_up:' . $variantId, 10); try { // 未获取锁的消费者将阻塞在这里 $lock->block(10); $promotionVariant = \Cache::get('promotion_variants:' . $variantId); if ($promotionVariant->quantity release(); throw new StockException('库存不足'); } $promotionVariant->quantity -= $quantity; $seconds = $promotionVariant->ended_at->getTimestamp() - time(); \Cache::put( "promotion_variants:$promotionVariant->id", $promotionVariant, $seconds ); } catch (LockTimeoutException $e) { throw new StockException('库存不足'); } finally { optional($lock)->release(); } CheckoutOrder::dispatch([ 'user_id' => \Auth::id(), 'variant_id' => $variantId, 'quantity' => $quantity ]); return response('结账订单创建中'); }
# Job/CheckoutOrder.php // ... public function handle() { // 创建结账订单 // ... // 通知客户端. websocket 编程本身就是以事件为导向的,和 laravel 的 event 非常契合。 event(new OrderChecked($this->data->user_id)); } // ...
# Event/OrderChecked.php class OrderChecked implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; private $userId; /** * Create a new event instance. * * @param $userId */ public function __construct($userId) { $this->userId = $userId; } /** * App.User.{id} 是 laravel 初始化时,默认的私有频道,直接使用即可 * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new PrivateChannel('App.User.' . $this->userId); } }
// views/products/show.vue <script> import Echo from 'laravel-echo' import io from 'socket.io-client' window.io = io export default { name: 'App', methods: { async snapUpCheckout () { try { // await post -> snap-up-checkout this.toCheckout() } catch (error) { // 秒杀失败 } }, toCheckout () { // 建立 websocket 连接 const echo = new Echo({ broadcaster: 'socket.io', host: 'http://api.e-commerce.test:6001', auth: { headers: { Authorization: 'Bearer ' + this.store.auth.token } } }) // 监听私有频道 App.User.{id} 的 OrderChecked 事件 echo.private('App.User.' + this.store.user.id).listen('OrderChecked', (e) => { // redirect to checkou page }) } } } </script>
/broadcasting/auth by default for authentication. . However, because the front-end and back-end categories are used instead of blade templates, we cannot easily obtain the csrf token and session to perform some necessary authentication.
# BroadcastServiceProvider.php public function boot() { // 将认证路由改为 /api/broadcasting/auth 从而避免 csrf 验证 // 添加中间件 auth:api (jwt 使用 api.auth) 进行身份验证,避免访问 session ,并使 Auth::user() 生效。 Broadcast::routes(["prefix" => "api", "middleware" => ["auth:api"]]); require base_path('routes/channels.php'); }
// laravel-echo-server.json // 认证路由添加 api 前缀,与上面的修改对应 "authEndpoint": "/api/broadcasting/auth"
The inventory here refers to cache inventory, not database inventory. This is because even if the order is successfully created at this time, it is still in checkout status (no address, payment method, etc. have been selected) and is not visible in the personal center. The database inventory will be locked only when the user confirms the order.
So the ideal implementation here is to return the locked inventory of the order after the user disconnects the websocket connection. After the checkout order is created, a delay queue is created to return inventory to orders that have not been operated for a long time.
But, laravel-echo is a broadcast system and does not provide callbacks for client disconnect events. There are some methods to implement client events that laravel listens to, such as adding hooks to laravel-echo-server. Notify laravel, but the implementation of laravel-echo-server needs to be modified. I won’t go into details here. The focus is to provide flash sale ideas.
Summary
The above picture is a logical summary of the flash kill system. At this point, the entire flash sale process is over. Generally speaking, the amount of code is not much and the logic is relatively simple.
As can be seen from the figure, in the entire process, it interacts with mysql only in the queue. Through the current limiting of the queue, it can adapt to the endurance of mysql to the maximum extent. When mysql performance is sufficient, users can consume orders through a large number of queues at the same time, and the user will not be aware of the queuing process at all.
If you have any questions or better ideas, please leave a message for discussion~
For more Laravel-related technical articles, please visit the Laravel Tutorial column to learn!
The above is the detailed content of Design of flash kill system. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



According to news on March 4, Kubi Rubik's Cube will launch the "Xiaoku Tablet 2Lite" tablet computer on March 5, with an initial price of 649 yuan. It is reported that the new tablet is equipped with Unisoc’s T606 processor, which uses a 12nm process and consists of two 1.6GHz ArmCortex-A75 CPUs and six ArmCortex-A55 processors. The screen uses a 10.95-inch IPS eye-protection screen with a resolution of 1280x800 and a brightness as high as 350 nits. In terms of imaging, Xiaoku Tablet 2Lite has a 13-megapixel main camera on the rear and a 5-megapixel selfie lens on the front. It also supports 4G Internet access/calls, Bluetooth 5.0, and Wi-Fi5. In addition, the official claimed that this tablet&l

According to news on April 26, ZTE’s 5G portable Wi-Fi U50S is now officially on sale, starting at 899 yuan. In terms of appearance design, ZTE U50S Portable Wi-Fi is simple and stylish, easy to hold and pack. Its size is 159/73/18mm and is easy to carry, allowing you to enjoy 5G high-speed network anytime and anywhere, achieving an unimpeded mobile office and entertainment experience. ZTE 5G portable Wi-Fi U50S supports the advanced Wi-Fi 6 protocol with a peak rate of up to 1800Mbps. It relies on the Snapdragon X55 high-performance 5G platform to provide users with an extremely fast network experience. Not only does it support the 5G dual-mode SA+NSA network environment and Sub-6GHz frequency band, the measured network speed can even reach an astonishing 500Mbps, which is easily satisfactory.

According to news on April 17, HMD teamed up with the well-known beer brand Heineken and the creative company Bodega to launch a unique flip phone - The Boring Phone. This phone is not only full of innovation in design, but also returns to nature in terms of functionality, aiming to lead people back to real interpersonal interactions and enjoy the pure time of drinking with friends. Boring mobile phone adopts a unique transparent flip design, showing a simple yet elegant aesthetic. It is equipped with a 2.8-inch QVGA display inside and a 1.77-inch display outside, providing users with a basic visual interaction experience. In terms of photography, although it is only equipped with a 30-megapixel camera, it is enough to handle simple daily tasks.

According to news on July 12, the Honor Magic V3 series was officially released today, equipped with the new Honor Vision Soothing Oasis eye protection screen. While the screen itself has high specifications and high quality, it also pioneered the introduction of AI active eye protection technology. It is reported that the traditional way to alleviate myopia is "myopia glasses". The power of myopia glasses is evenly distributed to ensure that the central area of sight is imaged on the retina, but the peripheral area is imaged behind the retina. The retina senses that the image is behind, promoting the eye axis direction. grow later, thereby deepening the degree. At present, one of the main ways to alleviate the development of myopia is the "defocus lens". The central area has a normal power, and the peripheral area is adjusted through optical design partitions, so that the image in the peripheral area falls in front of the retina.

According to news on April 3, Taipower’s upcoming M50 Mini tablet computer is a device with rich functions and powerful performance. This new 8-inch small tablet is equipped with an 8.7-inch IPS screen, providing users with an excellent visual experience. Its metal body design is not only beautiful but also enhances the durability of the device. In terms of performance, the M50Mini is equipped with the Unisoc T606 eight-core processor, which has two A75 cores and six A55 cores, ensuring a smooth and efficient running experience. At the same time, the tablet is also equipped with a 6GB+128GB storage solution and supports 8GB memory expansion, which meets users’ needs for storage and multi-tasking. In terms of battery life, M50Mini is equipped with a 5000mAh battery and supports Ty

At work, ppt is an office software often used by professionals. A complete ppt must have a good ending page. Different professional requirements give different ppt production characteristics. Regarding the production of the end page, how can we design it more attractively? Let’s take a look at how to design the end page of ppt! The design of the ppt end page can be adjusted in terms of text and animation, and you can choose a simple or dazzling style according to your needs. Next, we will focus on how to use innovative expression methods to create a ppt end page that meets the requirements. So let’s start today’s tutorial. 1. For the production of the end page, any text in the picture can be used. The important thing about the end page is that it means that my presentation is over. 2. In addition to these words,

According to news on May 13, vivoX100s was officially released tonight. In addition to excellent images, the new phone also performs very well in terms of signal. According to vivo’s official introduction, vivoX100s uses an innovative universal signal amplification system, which is equipped with up to 21 antennas. This design has been re-optimized based on the direct screen to balance many signal requirements such as 5G, 4G, Wi-Fi, GPS, and NFC. This makes vivoX100s the mobile phone with the strongest signal reception capability in vivo’s history. The new phone also uses a unique 360° surround design, with antennas distributed around the body. This design not only enhances the signal strength, but also optimizes various daily holding postures to avoid problems caused by improper holding methods.

According to news on July 29, the Honor X60i mobile phone is officially on sale today, starting at 1,399 yuan. In terms of design, the Honor X60i mobile phone adopts a straight screen design with a hole in the center and almost unbounded ultra-narrow borders on all four sides, which greatly broadens the field of view. Honor X60i parameters Display: 6.7-inch high-definition display Battery: 5000mAh large-capacity battery Processor: Dimensity 6080 processor (TSMC 6nm, 2x2.4G A76+6×2G A55) System: MagicOS8.0 system Other features: 5G signal enhancement, smart capsule, under-screen fingerprint, dual MIC, noise reduction, knowledge Q&A, photography capabilities: rear dual camera system: 50 million pixels main camera, 2 million pixels auxiliary lens, front selfie lens: 8 million pixels, price: 8GB
