En million WebSockets og Go

Hej allesammen! Mit navn er Sergey Kamardin og jeg er udvikler hos Mail.Ru.

Denne artikel handler om, hvordan vi udviklede den højt belastede WebSocket-server med Go.

Hvis du er fortrolig med WebSockets, men kun ved lidt om Go, håber jeg, at du stadig vil finde denne artikel interessant med hensyn til ideer og teknikker til optimering af ydeevne.

1. Introduktion

For at definere konteksten i vores historie skal der siges et par ord om, hvorfor vi har brug for denne server.

Mail.Ru har mange statefulde systemer. Bruger-e-mail-opbevaring er en af ​​dem. Der er flere måder at holde styr på tilstandsændringer i et system - og om systemhændelser. For det meste er dette enten gennem periodisk systemafstemning eller systemunderretninger om dets tilstandsændringer.

Begge veje har deres fordele og ulemper. Men når det kommer til mail, jo hurtigere en bruger modtager ny mail, jo bedre.

Mail-polling involverer ca. 50.000 HTTP-forespørgsler pr. Sekund, hvoraf 60% returnerer 304-status, hvilket betyder, at der ikke er nogen ændringer i postkassen.

For at reducere belastningen på serverne og for at fremskynde levering af mail til brugerne blev det derfor besluttet at genopfinde hjulet ved at skrive en udgiver-abonnentserver (også kendt som en bus, meddelelsesmægler eller begivenheds- kanal), der på den ene side modtager underretninger om tilstandsændringer og på den anden side abonnementer på sådanne meddelelser.

Tidligere:

Nu:

Den første ordning viser, hvordan det var før. Browseren pollede periodisk API'en og spurgte om ændringer i lager (postkassetjeneste).

Den anden ordning beskriver den nye arkitektur. Browseren opretter en WebSocket-forbindelse med notifikations-API'en, som er en klient til Bus-serveren. Efter modtagelse af ny e-mail sender Storage en meddelelse om det til Bus (1) og Bus til sine abonnenter (2). API bestemmer forbindelsen til at sende den modtagne meddelelse og sender den til brugerens browser (3).

Så i dag skal vi tale om API'en eller WebSocket-serveren. Ser jeg fremad, fortæller jeg dig, at serveren vil have omkring 3 millioner onlineforbindelser.

2. Den idiomatiske måde

Lad os se, hvordan vi ville implementere visse dele af vores server ved hjælp af almindelige Go-funktioner uden nogen optimeringer.

net/httpLad os tale om, hvordan vi sender og modtager data, inden vi fortsætter . Dataene, der står over WebSocket-protokollen (f.eks. JSON-objekter), vil herefter blive betegnet som pakker .

Lad os begynde at implementere den Channelstruktur, der indeholder logikken i at sende og modtage sådanne pakker via WebSocket-forbindelsen.

2.1. Kanalstruktur

// Packet represents application level data. type Packet struct { ... } // Channel wraps user connection. type Channel struct { conn net.Conn // WebSocket connection. send chan Packet // Outgoing packets queue. } func NewChannel(conn net.Conn) *Channel { c := &Channel{ conn: conn, send: make(chan Packet, N), } go c.reader() go c.writer() return c }

Jeg vil gerne henlede opmærksomheden på lanceringen af ​​to læse- og skrivegoroutiner. Hver goroutine kræver sin egen hukommelsesstak, der muligvis har en indledende størrelse på 2 til 8 KB afhængigt af operativsystem og Go-version.

Med hensyn til det ovennævnte antal på 3 millioner onlineforbindelser har vi brug for 24 GB hukommelse (med stakken på 4 KB) til alle forbindelser. Og det er uden den hukommelse, der er allokeret til Channelstrukturen, de udgående pakker ch.sendog andre interne felter.

2.2. I / O goroutines

Lad os se på implementeringen af ​​"læseren":

func (c *Channel) reader() { // We make a buffered read to reduce read syscalls. buf := bufio.NewReader(c.conn) for { pkt, _ := readPacket(buf) c.handle(pkt) } }

Her bruger vi til bufio.Readerat reducere antallet af read()syscalls og til at læse så mange som tilladt af bufbufferstørrelsen. Inden for den uendelige løkke forventer vi, at der kommer nye data. Husk ordene: forvent nye data at komme. Vi vender tilbage til dem senere.

Vi lader parsing og behandling af indgående pakker til side, da det ikke er vigtigt for de optimeringer, vi vil tale om. Det er dog bufvores opmærksomhed værd nu: Som standard er det 4 KB, hvilket betyder yderligere 12 GB hukommelse til vores forbindelser. Der er en lignende situation med "forfatteren":

func (c *Channel) writer() { // We make buffered write to reduce write syscalls. buf := bufio.NewWriter(c.conn) for pkt := range c.send { _ := writePacket(buf, pkt) buf.Flush() } }

Vi gentager på tværs af den udgående pakkekanal c.sendog skriver dem til bufferen. Dette er, som vores opmærksomme læsere allerede kan gætte, yderligere 4 KB og 12 GB hukommelse til vores 3 millioner forbindelser.

2.3. HTTP

Vi har allerede en simpel Channelimplementering, nu skal vi få en WebSocket-forbindelse til at arbejde med. Da vi stadig er under overskriften Idiomatic Way , lad os gøre det på den tilsvarende måde.

Bemærk: Hvis du ikke ved, hvordan WebSocket fungerer, skal det nævnes, at klienten skifter til WebSocket-protokollen ved hjælp af en særlig HTTP-mekanisme kaldet Upgrade. Efter en vellykket behandling af en opgraderingsanmodning bruger serveren og klienten TCP-forbindelsen til at udveksle binære WebSocket-rammer. Her er en beskrivelse af rammestrukturen inde i forbindelsen.
import ( "net/http" "some/websocket" ) http.HandleFunc("/v1/ws", func(w http.ResponseWriter, r *http.Request) { conn, _ := websocket.Upgrade(r, w) ch := NewChannel(conn) //... })

Bemærk, at der http.ResponseWriterforetages hukommelsesallokering til bufio.Readerog bufio.Writer(begge med 4 KB-buffer) til *http.Requestinitialisering og yderligere skrivning af svar.

Uanset hvilket anvendt WebSocket-bibliotek modtager serveren efter et vellykket svar på opgraderingsanmodningen I / O-buffere sammen med TCP-forbindelsen efter responseWriter.Hijack()opkaldet.

Hint: in some cases the go:linkname can be used to return the buffers to the sync.Pool inside net/http through the call net/http.putBufio{Reader,Writer}.

Thus, we need another 24 GB of memory for 3 million connections.

So, a total of 72 GB of memory for the application that does nothing yet!

3. Optimizations

Let’s review what we talked about in the introduction part and remember how a user connection behaves. After switching to WebSocket, the client sends a packet with the relevant events or in other words subscribes for events. Then (not taking into account technical messages such as ping/pong), the client may send nothing else for the whole connection lifetime.

The connection lifetime may last from several seconds to several days.

So for the most time our Channel.reader() and Channel.writer() are waiting for the handling of data for receiving or sending. Along with them waiting are the I/O buffers of 4 KB each.

Now it is clear that certain things could be done better, couldn’t they?

3.1. Netpoll

Do you remember the Channel.reader() implementation that expected new data to come by getting locked on the conn.Read() call inside the bufio.Reader.Read()? If there was data in the connection, Go runtime "woke up" our goroutine and allowed it to read the next packet. After that, the goroutine got locked again while expecting new data. Let's see how Go runtime understands that the goroutine must be "woken up".

If we look at the conn.Read() implementation, we’ll see the net.netFD.Read() call inside it:

// net/fd_unix.go func (fd *netFD) Read(p []byte) (n int, err error) { //... for { n, err = syscall.Read(fd.sysfd, p) if err != nil { n = 0 if err == syscall.EAGAIN { if err = fd.pd.waitRead(); err == nil { continue } } } //... break } //... }
Go uses sockets in non-blocking mode. EAGAIN says there is no data in the socket and not to get locked on reading from the empty socket, OS returns control to us.

We see a read() syscall from the connection file descriptor. If read returns the EAGAIN error, runtime makes the pollDesc.waitRead() call:

// net/fd_poll_runtime.go func (pd *pollDesc) waitRead() error { return pd.wait('r') } func (pd *pollDesc) wait(mode int) error { res := runtime_pollWait(pd.runtimeCtx, mode) //... }

If we dig deeper, we’ll see that netpoll is implemented using epoll in Linux and kqueue in BSD. Why not use the same approach for our connections? We could allocate a read buffer and start the reading goroutine only when it is really necessary: when there is really readable data in the socket.

On github.com/golang/go, there is the issue of exporting netpoll functions.

3.2. Getting rid of goroutines

Suppose we have netpoll implementation for Go. Now we can avoid starting the Channel.reader() goroutine with the inside buffer, and subscribe for the event of readable data in the connection:

ch := NewChannel(conn) // Make conn to be observed by netpoll instance. poller.Start(conn, netpoll.EventRead, func() { // We spawn goroutine here to prevent poller wait loop // to become locked during receiving packet from ch. go Receive(ch) }) // Receive reads a packet from conn and handles it somehow. func (ch *Channel) Receive() { buf := bufio.NewReader(ch.conn) pkt := readPacket(buf) c.handle(pkt) }

It is easier with the Channel.writer() because we can run the goroutine and allocate the buffer only when we are going to send the packet:

func (ch *Channel) Send(p Packet) { if c.noWriterYet() { go ch.writer() } ch.send <- p }
Note that we do not handle cases when operating system returns EAGAIN on write() system calls. We lean on Go runtime for such cases, cause it is actually rare for such kind of servers. Nevertheless, it could be handled in the same way if needed.

After reading the outgoing packets from ch.send (one or several), the writer will finish its operation and free the goroutine stack and the send buffer.

Perfect! We have saved 48 GB by getting rid of the stack and I/O buffers inside of two continuously running goroutines.

3.3. Control of resources

A great number of connections involves not only high memory consumption. When developing the server, we experienced repeated race conditions and deadlocks often followed by the so-called self-DDoS — a situation when the application clients rampantly tried to connect to the server thus breaking it even more.

For example, if for some reason we suddenly could not handle ping/pong messages, but the handler of idle connections continued to close such connections (supposing that the connections were broken and therefore provided no data), the client appeared to lose connection every N seconds and tried to connect again instead of waiting for events.

It would be great if the locked or overloaded server just stopped accepting new connections, and the balancer before it (for example, nginx) passed request to the next server instance.

Moreover, regardless of the server load, if all clients suddenly want to send us a packet for any reason (presumably by cause of bug), the previously saved 48 GB will be of use again, as we will actually get back to the initial state of the goroutine and the buffer per each connection.

Goroutine pool

We can restrict the number of packets handled simultaneously using a goroutine pool. This is what a naive implementation of such pool looks like:

package gopool func New(size int) *Pool { return &Pool{ work: make(chan func()), sem: make(chan struct{}, size), } } func (p *Pool) Schedule(task func()) error { select { case p.work <- task: case p.sem <- struct{}{}: go p.worker(task) } } func (p *Pool) worker(task func()) { defer func() { <-p.sem } for { task() task = <-p.work } }

Now our code with netpoll looks as follows:

pool := gopool.New(128) poller.Start(conn, netpoll.EventRead, func() { // We will block poller wait loop when // all pool workers are busy. pool.Schedule(func() { Receive(ch) }) })

So now we read the packet not only upon readable data appearance in the socket, but also upon the first opportunity to take up the free goroutine in the pool.

Similarly, we’ll change Send():

pool := gopool.New(128) func (ch *Channel) Send(p Packet) { if c.noWriterYet() { pool.Schedule(ch.writer) } ch.send <- p }

Instead of go ch.writer(), we want to write in one of the reused goroutines. Thus, for a pool of N goroutines, we can guarantee that with N requests handled simultaneously and the arrived N + 1 we will not allocate a N + 1 buffer for reading. The goroutine pool also allows us to limit Accept() and Upgrade() of new connections and to avoid most situations with DDoS.

3.4. Zero-copy upgrade

Let’s deviate a little from the WebSocket protocol. As was already mentioned, the client switches to the WebSocket protocol using a HTTP Upgrade request. This is what it looks like:

GET /ws HTTP/1.1 Host: mail.ru Connection: Upgrade Sec-Websocket-Key: A3xNe7sEB9HixkmBhVrYaA== Sec-Websocket-Version: 13 Upgrade: websocket HTTP/1.1 101 Switching Protocols Connection: Upgrade Sec-Websocket-Accept: ksu0wXWG+YmkVx+KQR2agP0cQn4= Upgrade: websocket

That is, in our case we need the HTTP request and its headers only for switch to the WebSocket protocol. This knowledge and what is stored inside the http.Request suggests that for the sake of optimization, we could probably refuse unnecessary allocations and copyings when processing HTTP requests and abandon the standard net/http server.

For example, the http.Request contains a field with the same-name Header type that is unconditionally filled with all request headers by copying data from the connection to the values strings. Imagine how much extra data could be kept inside this field, for example for a large-size Cookie header.

But what to take in return?

WebSocket implementation

Unfortunately, all libraries existing at the time of our server optimization allowed us to do upgrade only for the standard net/http server. Moreover, neither of the (two) libraries made it possible to use all the above read and write optimizations. For these optimizations to work, we must have a rather low-level API for working with WebSocket. To reuse the buffers, we need the procotol functions to look like this:

func ReadFrame(io.Reader) (Frame, error) func WriteFrame(io.Writer, Frame) error

If we had a library with such API, we could read packets from the connection as follows (the packet writing would look the same):

// getReadBuf, putReadBuf are intended to // reuse *bufio.Reader (with sync.Pool for example). func getReadBuf(io.Reader) *bufio.Reader func putReadBuf(*bufio.Reader) // readPacket must be called when data could be read from conn. func readPacket(conn io.Reader) error { buf := getReadBuf() defer putReadBuf(buf) buf.Reset(conn) frame, _ := ReadFrame(buf) parsePacket(frame.Payload) //... }

In short, it was time to make our own library.

github.com/gobwas/ws

Ideologically, the ws library was written so as not to impose its protocol operation logic on users. All reading and writing methods accept standard io.Reader and io.Writer interfaces, which makes it possible to use or not to use buffering or any other I/O wrappers.

Besides upgrade requests from standard net/http, ws supports zero-copy upgrade, the handling of upgrade requests and switching to WebSocket without memory allocations or copyings. ws.Upgrade() accepts io.ReadWriter (net.Conn implements this interface). In other words, we could use the standard net.Listen() and transfer the received connection from ln.Accept() immediately to ws.Upgrade(). The library makes it possible to copy any request data for future use in the application (for example, Cookie to verify the session).

Below there are benchmarks of Upgrade request processing: standard net/http server versus net.Listen() with zero-copy upgrade:

BenchmarkUpgradeHTTP 5156 ns/op 8576 B/op 9 allocs/op BenchmarkUpgradeTCP 973 ns/op 0 B/op 0 allocs/op

Switching to ws and zero-copy upgrade saved us another 24 GB — the space allocated for I/O buffers upon request processing by the net/http handler.

3.5. Summary

Let’s structure the optimizations I told you about.

  • A read goroutine with a buffer inside is expensive. Solution: netpoll (epoll, kqueue); reuse the buffers.
  • A write goroutine with a buffer inside is expensive. Solution: start the goroutine when necessary; reuse the buffers.
  • With a storm of connections, netpoll won’t work. Solution: reuse the goroutines with the limit on their number.
  • net/http is not the fastest way to handle Upgrade to WebSocket. Solution: use the zero-copy upgrade on bare TCP connection.

Sådan ser serverkoden ud:

import ( "net" "github.com/gobwas/ws" ) ln, _ := net.Listen("tcp", ":8080") for { // Try to accept incoming connection inside free pool worker. // If there no free workers for 1ms, do not accept anything and try later. // This will help us to prevent many self-ddos or out of resource limit cases. err := pool.ScheduleTimeout(time.Millisecond, func() { conn := ln.Accept() _ = ws.Upgrade(conn) // Wrap WebSocket connection with our Channel struct. // This will help us to handle/send our app's packets. ch := NewChannel(conn) // Wait for incoming bytes from connection. poller.Start(conn, netpoll.EventRead, func() { // Do not cross the resource limits. pool.Schedule(func() { // Read and handle incoming packet(s). ch.Recevie() }) }) }) if err != nil { time.Sleep(time.Millisecond) } }

4. Konklusion

For tidlig optimering er roden til alt ondt (eller i det mindste det meste) i programmering. Donald Knuth

Selvfølgelig er ovenstående optimeringer relevante, men ikke i alle tilfælde. For eksempel, hvis forholdet mellem ledige ressourcer (hukommelse, CPU) og antallet af onlineforbindelser er ret højt, er der sandsynligvis ingen mening i at optimere. Du kan dog have meget ud af at vide, hvor og hvad du skal forbedre.

Tak for din opmærksomhed!

5. Referencer

  • //github.com/mailru/easygo
  • //github.com/gobwas/ws
  • //github.com/gobwas/ws-eksempler
  • //github.com/gobwas/httphead
  • Russisk version af denne artikel