Home >headlines >12306 ticket grabbing, thoughts brought about by extreme concurrency!

12306 ticket grabbing, thoughts brought about by extreme concurrency!

藏色散人
藏色散人Original
2022-05-13 10:05:314332browse

12306 Ticket grabbing, thoughts brought about by extreme concurrency?

Every holiday, people who return home or go out for fun in first- and second-tier cities almost always face a problem: grabbing trains Tickets! Although tickets can be booked in most cases now, I believe everyone has a deep understanding of the situation where tickets are no longer available as soon as the tickets are released. Especially during the Spring Festival, people not only use 12306, but also consider "Zhixing" and other ticket grabbing software. Hundreds of millions of people across the country are grabbing tickets during this period. "12306 service" bears a QPS that cannot be surpassed by any flash sale system in the world. Millions of concurrency is nothing but normal! The author has specifically studied the server architecture of "12306" and learned many highlights of its system design. Here I will share with you and simulate an example: how to provide normal service when 1 million people are grabbing 10,000 train tickets at the same time. , stable service. github code address

Related recommendations: " Tens of millions of data concurrency solutions (theory and practice)"

1. Large-scale high-concurrency system architecture

High-concurrency system architecture will adopt distributed cluster deployment. The upper layer of the service has layer-by-layer load balancing and provides various disaster recovery methods (dual Fire engine room, node fault tolerance, server disaster recovery, etc.) ensure the high availability of the system, and traffic will be balanced to different servers based on different load capabilities and configuration strategies. The following is a simple schematic diagram:

12306 ticket grabbing, thoughts brought about by extreme concurrency!

1.1 Introduction to load balancing

The above figure describes the three steps that user requests to the server go through. Layer load balancing, the following is a brief introduction to these three types of load balancing:

  • OSPF (Open Shortest Link First) is an Interior Gateway Protocol (Interior Gateway Protocol, referred to as IGP) . OSPF establishes a link state database by advertising the status of network interfaces between routers and generates a shortest path tree. OSPF will automatically calculate the Cost value on the routing interface, but you can also manually specify the Cost value of the interface. The manually specified one takes precedence. Automatically calculated value. The Cost calculated by OSPF is also inversely proportional to the interface bandwidth. The higher the bandwidth, the smaller the Cost value. Paths with the same Cost value to the target can perform load balancing, and up to 6 links can perform load balancing at the same time.

  • LVS (Linux VirtualServer) is a cluster technology that uses IP load balancing technology and content-based request distribution technology. The scheduler has a very good throughput rate and evenly transfers requests to different servers for execution, and the scheduler automatically shields server failures, thus forming a group of servers into a high-performance, highly available virtual server.

  • Nginx must be familiar to everyone. It is a very high-performance http proxy/reverse proxy server. It is often used for load balancing in service development. There are three main ways for Nginx to achieve load balancing: polling, weighted polling, and ip hash polling. Below we will do special configuration and testing for Nginx's weighted polling

1.2 Demonstration of Nginx weighted polling

Nginx implements load balancing through the upstream module. The configuration of weighted polling can add a weight value to the relevant services. The configuration may be based on The performance and load capacity of the server set the corresponding load. The following is a weighted polling load configuration. I will listen to ports 3001-3004 locally and configure the weights of 1, 2, 3, and 4 respectively:

#配置负载均衡
    upstream load_rule {
       server 127.0.0.1:3001 weight=1;
       server 127.0.0.1:3002 weight=2;
       server 127.0.0.1:3003 weight=3;
       server 127.0.0.1:3004 weight=4;
    }
    ...
    server {
    listen       80;
    server_name  load_balance.com www.load_balance.com;
    location / {
       proxy_pass http://load_rule;
    }
}

Copy the code to my local /etc/hosts directory The virtual domain name address of www.load_balance.com is configured below. Next, use Go language to open four http port listening services. The following is the Go program listening on port 3001. The other few only need to modify the port:

package main

import (
"net/http"
"os"
"strings"
)

func main() {
http.HandleFunc("/buy/ticket", handleReq)
http.ListenAndServe(":3001", nil)
}

//处理请求函数,根据请求将响应结果信息写入日志
func handleReq(w http.ResponseWriter, r *http.Request) {
failedMsg :=  "handle in port:"
writeLog(failedMsg, "./stat.log")
}

//写入日志
func writeLog(msg string, logPath string) {
fd, _ := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
defer fd.Close()
content := strings.Join([]string{msg, "\r\n"}, "3001")
buf := []byte(content)
fd.Write(buf)
}

I wrote the requested port log information into the ./stat.log file, and then used the ab stress test tool to do the stress test:

ab -n 1000 -c 100 http://www.load_balance.com/buy/ticket

The results in the statistical log, 3001-3004 ports were obtained respectively The request volume of 100, 200, 300, and 400 is consistent with the weight ratio I configured in nginx, and the traffic after load is very even and random. For specific implementation, you can refer to the upstream module implementation source code of nginx. Here is a recommended article: Load balancing of the upstream mechanism in Nginx

2. Flash sale system selection

Back to the question we originally mentioned: How can the train ticket flash sale system provide normal and stable services under high concurrency conditions?

From the above introduction, we know that user flash sales traffic is evenly distributed to different servers through layers of load balancing. Even so, the QPS endured by a single machine in the cluster is also very high. How to optimize stand-alone performance to the extreme? To solve this problem, we need to understand one thing:

Usually the ticket booking system has to process the three basic stages of order generation, inventory reduction, and user payment. What our system needs to do is to ensure that train ticket orders are not oversold or undersold. Each ticket sold All must be paid to be effective, and the system must be guaranteed to withstand extremely high concurrency. How can the order of these three stages be changed to be more reasonable? Let’s analyze it:

2.1 Place an order to reduce inventory

When concurrent user requests arrive at the server When , first create an order, then deduct the inventory and wait for user payment. This order is the first solution that most of us will think of. In this case, it can also ensure that the order will not be oversold, because the inventory will be reduced after the order is created, which is an atomic operation. However, this will also cause some problems. The first is that under extreme concurrency conditions, the details of any memory operation will significantly affect performance, especially logic such as creating orders, which generally needs to be stored in a disk database, which puts pressure on the database. It is conceivable; the second is that if the user places an order maliciously and only places the order without paying, the inventory will be reduced and many orders will be sold less. Although the server can limit the IP and the number of user purchase orders, This is not a good approach either.

12306 ticket grabbing, thoughts brought about by extreme concurrency!

2.2 Pay to reduce inventory

If you wait for the user to pay for the order and reduce inventory, the first feeling is that there will be no less sales. But this is a taboo of concurrent architecture, because under extreme concurrency conditions, users may create many orders. When the inventory is reduced to zero, many users find that they cannot pay for the orders they grabbed. This is also called "oversold" . Concurrent database disk IO operations cannot be avoided

12306 ticket grabbing, thoughts brought about by extreme concurrency!

2.3 Withholding inventory

From the considerations of the above two solutions, we can get Conclusion: As long as an order is created, database IO must be operated frequently. So is there a solution that does not require direct operation of database IO? This is withholding inventory. First, the inventory is deducted to ensure that it is not oversold, and then user orders are generated asynchronously, so that the response to users will be much faster; so how to ensure that there is a lot of sales? What should the user do if they don’t pay after getting the order? We all know that orders now have a validity period. For example, if the user does not pay within five minutes, the order will expire. Once the order expires, new inventory will be added. This is also the solution adopted by many online retail companies to ensure that they sell a lot of goods. Orders are generated asynchronously and are generally processed in instant consumption queues such as MQ and Kafka. When the order volume is relatively small, orders are generated very quickly and users hardly have to queue.

12306 ticket grabbing, thoughts brought about by extreme concurrency!

#3. The art of withholding inventory

From the above analysis, it is obvious that the plan of withholding inventory is the most reasonable. Let’s further analyze the details of inventory deduction. There is still a lot of room for optimization. Where is the inventory? How to ensure correct inventory deduction under high concurrency and rapid response to user requests?

In the case of low concurrency on a single machine, our implementation of inventory deduction is usually as follows:

12306 ticket grabbing, thoughts brought about by extreme concurrency!

In order to ensure the atomicity of inventory deduction and order generation, we need to use Transaction processing, then inventory judgment, inventory reduction, and finally transaction submission. The entire process involves a lot of IO, and the operation of the database is blocked. This method is not suitable for high-concurrency flash sales systems at all.

Next, we will optimize the single-machine inventory deduction plan: Local inventory deduction. We allocate a certain amount of inventory to the local machine, reduce the inventory directly in the memory, and then create an order asynchronously according to the previous logic. The improved stand-alone system looks like this:

12306 ticket grabbing, thoughts brought about by extreme concurrency!

这样就避免了对数据库频繁的IO操作,只在内存中做运算,极大的提高了单机抗并发的能力。但是百万的用户请求量单机是无论如何也抗不住的,虽然nginx处理网络请求使用epoll模型,c10k的问题在业界早已得到了解决。但是linux系统下,一切资源皆文件,网络请求也是这样,大量的文件描述符会使操作系统瞬间失去响应。上面我们提到了nginx的加权均衡策略,我们不妨假设将100W的用户请求量平均均衡到100台服务器上,这样单机所承受的并发量就小了很多。然后我们每台机器本地库存100张火车票,100台服务器上的总库存还是1万,这样保证了库存订单不超卖,下面是我们描述的集群架构:

12306 ticket grabbing, thoughts brought about by extreme concurrency!

问题接踵而至,在高并发情况下,现在我们还无法保证系统的高可用,假如这100台服务器上有两三台机器因为扛不住并发的流量或者其他的原因宕机了。那么这些服务器上的订单就卖不出去了,这就造成了订单的少卖。要解决这个问题,我们需要对总订单量做统一的管理,这就是接下来的容错方案。服务器不仅要在本地减库存,另外要远程统一减库存。有了远程统一减库存的操作,我们就可以根据机器负载情况,为每台机器分配一些多余的“buffer库存”用来防止机器中有机器宕机的情况。我们结合下面架构图具体分析一下:

12306 ticket grabbing, thoughts brought about by extreme concurrency!

我们采用Redis存储统一库存,因为Redis的性能非常高,号称单机QPS能抗10W的并发。在本地减库存以后,如果本地有订单,我们再去请求redis远程减库存,本地减库存和远程减库存都成功了,才返回给用户抢票成功的提示,这样也能有效的保证订单不会超卖。当机器中有机器宕机时,因为每个机器上有预留的buffer余票,所以宕机机器上的余票依然能够在其他机器上得到弥补,保证了不少卖。buffer余票设置多少合适呢,理论上buffer设置的越多,系统容忍宕机的机器数量就越多,但是buffer设置的太大也会对redis造成一定的影响。虽然redis内存数据库抗并发能力非常高,请求依然会走一次网络IO,其实抢票过程中对redis的请求次数是本地库存和buffer库存的总量,因为当本地库存不足时,系统直接返回用户“已售罄”的信息提示,就不会再走统一扣库存的逻辑,这在一定程度上也避免了巨大的网络请求量把redis压跨,所以buffer值设置多少,需要架构师对系统的负载能力做认真的考量。

4. 代码演示

Go语言原生为并发设计,我采用go语言给大家演示一下单机抢票的具体流程。

4.1 初始化工作

go包中的init函数先于main函数执行,在这个阶段主要做一些准备性工作。我们系统需要做的准备工作有:初始化本地库存、初始化远程redis存储统一库存的hash键值、初始化redis连接池;另外还需要初始化一个大小为1的int类型chan,目的是实现分布式锁的功能,也可以直接使用读写锁或者使用redis等其他的方式避免资源竞争,但使用channel更加高效,这就是go语言的哲学:不要通过共享内存来通信,而要通过通信来共享内存。redis库使用的是redigo,下面是代码实现:

...
//localSpike包结构体定义
package localSpike

type LocalSpike struct {
LocalInStock     int64
LocalSalesVolume int64
}
...
//remoteSpike对hash结构的定义和redis连接池
package remoteSpike
//远程订单存储健值
type RemoteSpikeKeys struct {
SpikeOrderHashKey string //redis中秒杀订单hash结构key
TotalInventoryKey string //hash结构中总订单库存key
QuantityOfOrderKey string //hash结构中已有订单数量key
}

//初始化redis连接池
func NewPool() *redis.Pool {
return &redis.Pool{
MaxIdle:   10000,
MaxActive: 12000, // max number of connections
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", ":6379")
if err != nil {
panic(err.Error())
}
return c, err
},
}
}
...
func init() {
localSpike = localSpike2.LocalSpike{
LocalInStock:     150,
LocalSalesVolume: 0,
}
remoteSpike = remoteSpike2.RemoteSpikeKeys{
SpikeOrderHashKey:  "ticket_hash_key",
TotalInventoryKey:  "ticket_total_nums",
QuantityOfOrderKey: "ticket_sold_nums",
}
redisPool = remoteSpike2.NewPool()
done = make(chan int, 1)
done <- 1
}

4.2 本地扣库存和统一扣库存

本地扣库存逻辑非常简单,用户请求过来,添加销量,然后对比销量是否大于本地库存,返回bool值:

package localSpike
//本地扣库存,返回bool值
func (spike *LocalSpike) LocalDeductionStock() bool{
spike.LocalSalesVolume = spike.LocalSalesVolume + 1
return spike.LocalSalesVolume < spike.LocalInStock
}

注意这里对共享数据LocalSalesVolume的操作是要使用锁来实现的,但是因为本地扣库存和统一扣库存是一个原子性操作,所以在最上层使用channel来实现,这块后边会讲。统一扣库存操作redis,因为redis是单线程的,而我们要实现从中取数据,写数据并计算一些列步骤,我们要配合lua脚本打包命令,保证操作的原子性:

package remoteSpike
......
const LuaScript = `
        local ticket_key = KEYS[1]
        local ticket_total_key = ARGV[1]
        local ticket_sold_key = ARGV[2]
        local ticket_total_nums = tonumber(redis.call(&#39;HGET&#39;, ticket_key, ticket_total_key))
        local ticket_sold_nums = tonumber(redis.call(&#39;HGET&#39;, ticket_key, ticket_sold_key))
-- 查看是否还有余票,增加订单数量,返回结果值
       if(ticket_total_nums >= ticket_sold_nums) then
            return redis.call(&#39;HINCRBY&#39;, ticket_key, ticket_sold_key, 1)
        end
        return 0
`
//远端统一扣库存
func (RemoteSpikeKeys *RemoteSpikeKeys) RemoteDeductionStock(conn redis.Conn) bool {
lua := redis.NewScript(1, LuaScript)
result, err := redis.Int(lua.Do(conn, RemoteSpikeKeys.SpikeOrderHashKey, RemoteSpikeKeys.TotalInventoryKey, RemoteSpikeKeys.QuantityOfOrderKey))
if err != nil {
return false
}
return result != 0
}

我们使用hash结构存储总库存和总销量的信息,用户请求过来时,判断总销量是否大于库存,然后返回相关的bool值。在启动服务之前,我们需要初始化redis的初始库存信息:

 hmset ticket_hash_key "ticket_total_nums" 10000 "ticket_sold_nums" 0

4.3 响应用户信息

我们开启一个http服务,监听在一个端口上:

package main
...
func main() {
http.HandleFunc("/buy/ticket", handleReq)
http.ListenAndServe(":3005", nil)
}

上面我们做完了所有的初始化工作,接下来handleReq的逻辑非常清晰,判断是否抢票成功,返回给用户信息就可以了。

package main
//处理请求函数,根据请求将响应结果信息写入日志
func handleReq(w http.ResponseWriter, r *http.Request) {
redisConn := redisPool.Get()
LogMsg := ""
<-done
//全局读写锁
if localSpike.LocalDeductionStock() && remoteSpike.RemoteDeductionStock(redisConn) {
util.RespJson(w, 1,  "抢票成功", nil)
LogMsg = LogMsg + "result:1,localSales:" + strconv.FormatInt(localSpike.LocalSalesVolume, 10)
} else {
util.RespJson(w, -1, "已售罄", nil)
LogMsg = LogMsg + "result:0,localSales:" + strconv.FormatInt(localSpike.LocalSalesVolume, 10)
}
done <- 1

//将抢票状态写入到log中
writeLog(LogMsg, "./stat.log")
}

func writeLog(msg string, logPath string) {
fd, _ := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
defer fd.Close()
content := strings.Join([]string{msg, "\r\n"}, "")
buf := []byte(content)
fd.Write(buf)
}

前边提到我们扣库存时要考虑竞态条件,我们这里是使用channel避免并发的读写,保证了请求的高效顺序执行。我们将接口的返回信息写入到了./stat.log文件方便做压测统计。

4.4 单机服务压测

开启服务,我们使用ab压测工具进行测试:

ab -n 10000 -c 100 http://127.0.0.1:3005/buy/ticket

下面是我本地低配mac的压测信息

This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests


Server Software:
Server Hostname:        127.0.0.1
Server Port:            3005

Document Path:          /buy/ticket
Document Length:        29 bytes

Concurrency Level:      100
Time taken for tests:   2.339 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      1370000 bytes
HTML transferred:       290000 bytes
Requests per second:    4275.96 [#/sec] (mean)
Time per request:       23.387 [ms] (mean)
Time per request:       0.234 [ms] (mean, across all concurrent requests)
Transfer rate:          572.08 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    8  14.7      6     223
Processing:     2   15  17.6     11     232
Waiting:        1   11  13.5      8     225
Total:          7   23  22.8     18     239

Percentage of the requests served within a certain time (ms)
  50%     18
  66%     24
  75%     26
  80%     28
  90%     33
  95%     39
  98%     45
  99%     54
 100%    239 (longest request)

根据指标显示,我单机每秒就能处理4000+的请求,正常服务器都是多核配置,处理1W+的请求根本没有问题。而且查看日志发现整个服务过程中,请求都很正常,流量均匀,redis也很正常:

//stat.log
...
result:1,localSales:145
result:1,localSales:146
result:1,localSales:147
result:1,localSales:148
result:1,localSales:149
result:1,localSales:150
result:0,localSales:151
result:0,localSales:152
result:0,localSales:153
result:0,localSales:154
result:0,localSales:156
...

5.总结回顾

总体来说,秒杀系统是非常复杂的。我们这里只是简单介绍模拟了一下单机如何优化到高性能,集群如何避免单点故障,保证订单不超卖、不少卖的一些策略,完整的订单系统还有订单进度的查看,每台服务器上都有一个任务,定时的从总库存同步余票和库存信息展示给用户,还有用户在订单有效期内不支付,释放订单,补充到库存等等。

我们实现了高并发抢票的核心逻辑,可以说系统设计的非常的巧妙,巧妙的避开了对DB数据库IO的操作,对Redis网络IO的高并发请求,几乎所有的计算都是在内存中完成的,而且有效的保证了不超卖、不少卖,还能够容忍部分机器的宕机。我觉得其中有两点特别值得学习总结:

  • 负载均衡,分而治之。通过负载均衡,将不同的流量划分到不同的机器上,每台机器处理好自己的请求,将自己的性能发挥到极致,这样系统的整体也就能承受极高的并发了,就像工作的的一个团队,每个人都将自己的价值发挥到了极致,团队成长自然是很大的。

  • 合理的使用并发和异步。自epoll网络架构模型解决了c10k问题以来,异步越来被服务端开发人员所接受,能够用异步来做的工作,就用异步来做,在功能拆解上能达到意想不到的效果,这点在nginx、node.js、redis上都能体现,他们处理网络请求使用的epoll模型,用实践告诉了我们单线程依然可以发挥强大的威力。服务器已经进入了多核时代,go语言这种天生为并发而生的语言,完美的发挥了服务器多核优势,很多可以并发处理的任务都可以使用并发来解决,比如go处理http请求时每个请求都会在一个goroutine中执行,总之:怎样合理的压榨CPU,让其发挥出应有的价值,是我们一直需要探索学习的方向。

原文链接:https://juejin.cn/post/6844903949632274445

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