Milijun WebSockets i kreni

Pozdrav svima! Zovem se Sergey Kamardin i programer sam na Mail.Ru.

Ovaj članak govori o tome kako smo s Goom razvili WebSocket poslužitelj s velikim opterećenjem.

Ako ste upoznati s WebSocketsima, ali malo znate o Gou, nadam se da će vam ovaj članak ipak biti zanimljiv u smislu ideja i tehnika za optimizaciju izvedbe.

1. Uvod

Da bismo definirali kontekst naše priče, treba reći nekoliko riječi o tome zašto nam je potreban ovaj poslužitelj.

Mail.Ru ima puno sustava s državom. Korisnička pohrana e-pošte jedna je od njih. Postoji nekoliko načina za praćenje promjena stanja unutar sustava - i o događajima u sustavu. Uglavnom je to bilo putem periodičnog ispitivanja sustava ili sistemskih obavijesti o promjenama stanja.

Oba načina imaju svoje prednosti i nedostatke. Ali što se tiče pošte, što brže korisnik prima novu poštu, to bolje.

Anketiranje pošte uključuje oko 50 000 HTTP upita u sekundi, od kojih 60% vraća status 304, što znači da u poštanskom sandučiću nema promjena.

Stoga je, kako bi se smanjilo opterećenje na poslužiteljima i ubrzala dostava pošte korisnicima, donesena je odluka o ponovnom izumu kotača pisanjem poslužitelja izdavač-pretplatnik (poznat i kao sabirnica, posrednik poruka ili događaj) kanal) koji bi primao obavijesti o promjenama stanja s jedne strane i pretplate na takve obavijesti s druge strane.

Prethodno:

Sada:

Prva shema pokazuje kako je bilo prije. Preglednik je povremeno anketirao API i pitao za promjene pohrane (usluga poštanskih sandučića).

Druga shema opisuje novu arhitekturu. Preglednik uspostavlja vezu WebSocket s API-jem za obavijesti, koji je klijent sabirničkog poslužitelja. Po primitku nove e-pošte, Storage šalje obavijest o tome Busu (1), a Bus svojim pretplatnicima (2). API određuje vezu za slanje primljene obavijesti i šalje je korisničkom pregledniku (3).

Dakle, danas ćemo razgovarati o API-ju ili WebSocket poslužitelju. Gledajući naprijed, reći ću vam da će poslužitelj imati oko 3 milijuna internetskih veza.

2. Idiomatski način

Pogledajmo kako bismo implementirali određene dijelove našeg poslužitelja koristeći obične značajke Go bez ikakvih optimizacija.

Prije nego što nastavimo net/http, razgovarajmo o tome kako ćemo slati i primati podatke. Podaci koji stoje iznad protokola WebSocket (npr. JSON objekti) u daljnjem će se tekstu nazivati paketima .

Počnimo s implementacijom Channelstrukture koja će sadržavati logiku slanja i primanja takvih paketa putem veze WebSocket.

2.1. Struktura kanala

// 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 }

Želio bih vam skrenuti pažnju na pokretanje dviju goroutina za čitanje i pisanje. Svaka goroutina zahtijeva vlastiti skup memorije koji može imati početnu veličinu od 2 do 8 KB, ovisno o operativnom sustavu i verziji Go.

Što se tiče gore spomenutog broja od 3 milijuna mrežnih veza, trebat će nam 24 GB memorije (sa hrpom od 4 KB) za sve veze. I to bez memorije dodijeljene Channelstrukturi, odlaznim paketima ch.sendi ostalim unutarnjim poljima.

2.2. I / O goroutine

Pogledajmo primjenu "čitača":

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) } }

Ovdje koristimo bufio.Readerza smanjenje broja read()syscalls-a i čitanje onoliko koliko dopušta bufveličina međuspremnika. Unutar beskonačne petlje očekujemo nove podatke. Molimo upamtite riječi: očekujte nove podatke. Vratit ćemo im se kasnije.

Ostavit ćemo po strani raščlanjivanje i obradu dolaznih paketa, jer to nije važno za optimizacije o kojima ćemo razgovarati. Međutim, bufvrijedno je naše pažnje sada: prema zadanim postavkama, to je 4 KB, što znači dodatnih 12 GB memorije za naše veze. Slična je situacija sa "piscem":

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() } }

Prelazimo kroz kanal odlaznih paketa c.sendi zapisujemo ih u međuspremnik. Ovo je, kao što već mogu naslutiti pažljivi čitatelji, još 4 KB i 12 GB memorije za naših 3 milijuna veza.

2.3. HTTP

Već imamo jednostavnu Channelimplementaciju, sada moramo dobiti WebSocket vezu za rad. Kako smo još uvijek pod naslovom Idiomatski put , učinimo to na odgovarajući način.

Napomena: Ako ne znate kako WebSocket radi, treba spomenuti da se klijent prebacuje na WebSocket protokol pomoću posebnog HTTP mehanizma nazvanog Nadogradnja. Nakon uspješne obrade zahtjeva za nadogradnju, poslužitelj i klijent koriste TCP vezu za razmjenu binarnih okvira WebSocket. Ovdje je opis strukture okvira unutar veze.
import ( "net/http" "some/websocket" ) http.HandleFunc("/v1/ws", func(w http.ResponseWriter, r *http.Request) { conn, _ := websocket.Upgrade(r, w) ch := NewChannel(conn) //... })

Imajte na umu da je http.ResponseWriterdodjela memorije za bufio.Readeri bufio.Writer(oboje s međuspremnikom od 4 KB) namijenjena *http.Requestinicijalizaciji i daljnjem pisanju odgovora.

Bez obzira na korištenu knjižnicu WebSocket, nakon uspješnog odgovora na zahtjev za nadogradnjom, poslužitelj nakon responseWriter.Hijack()poziva dobiva I / O međuspremnike zajedno s TCP vezom .

Savjet: u nekim se slučajevima go:linknamemože koristiti za vraćanje međuspremnika u sync.Poolunutrašnjost net/httpputem poziva net/http.putBufio{Reader,Writer}.

Dakle, trebamo još 24 GB memorije za 3 milijuna veza.

Dakle, ukupno 72 GB memorije za aplikaciju koja još ništa ne radi!

3. Optimizacije

Pregledajmo ono o čemu smo govorili u uvodnom dijelu i prisjetimo se ponašanja korisničke veze. Nakon prelaska na WebSocket, klijent šalje paket s relevantnim događajima ili drugim riječima pretplaćuje se na događaje. Tada (ne uzimajući u obzir tehničke poruke poput ping/pong), klijent ne može ništa drugo poslati tijekom cijelog vijeka veze.

Životni vijek veze može trajati od nekoliko sekundi do nekoliko dana.

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.

That is what the server code could look like:

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. Conclusion

Premature optimization is the root of all evil (or at least most of it) in programming. Donald Knuth

Of course, the above optimizations are relevant, but not in all cases. For example if the ratio between free resources (memory, CPU) and the number of online connections is rather high, there is probably no sense in optimizing. However, you can benefit a lot from knowing where and what to improve.

Thank you for your attention!

5. References

  • //github.com/mailru/easygo
  • //github.com/gobwas/ws
  • //github.com/gobwas/ws-examples
  • //github.com/gobwas/httphead
  • Russian version of this article