Un million de WebSockets et c'est parti

Salut à tous! Je m'appelle Sergey Kamardin et je suis développeur chez Mail.Ru.

Cet article explique comment nous avons développé le serveur WebSocket à charge élevée avec Go.

Si vous êtes familier avec les WebSockets, mais que vous en savez peu sur Go, j'espère que vous trouverez toujours cet article intéressant en termes d'idées et de techniques d'optimisation des performances.

1. Introduction

Pour définir le contexte de notre histoire, il convient de dire quelques mots sur les raisons pour lesquelles nous avons besoin de ce serveur.

Mail.Ru possède de nombreux systèmes avec état. Le stockage des e-mails des utilisateurs est l'un d'entre eux. Il existe plusieurs façons de suivre les changements d'état au sein d'un système et les événements du système. La plupart du temps, cela se fait soit par une interrogation périodique du système, soit par des notifications système concernant ses changements d'état.

Les deux méthodes ont leurs avantages et leurs inconvénients. Mais en ce qui concerne le courrier, plus vite un utilisateur reçoit un nouveau courrier, mieux c'est.

L'interrogation des e-mails implique environ 50 000 requêtes HTTP par seconde, dont 60% renvoient l'état 304, ce qui signifie qu'il n'y a pas de changement dans la boîte aux lettres.

Par conséquent, afin de réduire la charge sur les serveurs et d'accélérer la livraison du courrier aux utilisateurs, la décision a été prise de réinventer la roue en écrivant un serveur éditeur-abonné (également appelé bus, courtier de messages ou événement). canal) qui recevraient des notifications sur les changements d'état d'une part, et les abonnements à ces notifications d'autre part.

Précédemment:

Maintenant:

Le premier schéma montre ce que c'était avant. Le navigateur a régulièrement interrogé l'API et posé des questions sur les changements de stockage (service de boîte aux lettres).

Le deuxième schéma décrit la nouvelle architecture. Le navigateur établit une connexion WebSocket avec l'API de notification, qui est un client du serveur Bus. Dès réception d'un nouvel e-mail, le stockage envoie une notification à ce sujet au bus (1) et au bus à ses abonnés (2). L'API détermine la connexion pour envoyer la notification reçue et l'envoie au navigateur de l'utilisateur (3).

Alors aujourd'hui, nous allons parler de l'API ou du serveur WebSocket. Pour l'avenir, je vais vous dire que le serveur aura environ 3 millions de connexions en ligne.

2. La manière idiomatique

Voyons comment nous implémenterions certaines parties de notre serveur en utilisant des fonctionnalités Go simples sans aucune optimisation.

Avant de continuer net/http, parlons de la façon dont nous enverrons et recevrons des données. Les données qui se trouvent au- dessus du protocole WebSocket (par exemple les objets JSON) seront ci-après dénommées paquets .

Commençons par implémenter la Channelstructure qui contiendra la logique d'envoi et de réception de tels paquets via la connexion WebSocket.

2.1. Structure de la chaîne

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

Je voudrais attirer votre attention sur le lancement de deux goroutines de lecture et d'écriture. Chaque goroutine nécessite sa propre pile de mémoire qui peut avoir une taille initiale de 2 à 8 Ko selon le système d'exploitation et la version de Go.

Concernant le nombre mentionné ci-dessus de 3 millions de connexions en ligne, nous aurons besoin de 24 Go de mémoire (avec la pile de 4 Ko) pour toutes les connexions. Et c'est sans la mémoire allouée pour la Channelstructure, les paquets sortants ch.sendet autres champs internes.

2.2. Goroutines E / S

Jetons un œil à l'implémentation du «reader»:

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

Ici, nous utilisons le bufio.Readerpour réduire le nombre d' read()appels système et pour en lire autant que la buftaille du tampon le permet. Dans la boucle infinie, nous nous attendons à ce que de nouvelles données arrivent. N'oubliez pas les mots: attendez - vous à ce que de nouvelles données arrivent Nous y reviendrons plus tard.

Nous laisserons de côté l'analyse et le traitement des paquets entrants, car ce n'est pas important pour les optimisations dont nous parlerons. Cependant, cela bufmérite notre attention maintenant: par défaut, il est de 4 Ko ce qui signifie encore 12 Go de mémoire pour nos connexions. Il existe une situation similaire avec le "rédacteur":

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

Nous parcourons le canal des paquets sortants c.sendet les écrivons dans la mémoire tampon. Il s'agit, comme nos lecteurs attentifs peuvent déjà le deviner, de 4 Ko et 12 Go de mémoire supplémentaires pour nos 3 millions de connexions.

2.3. HTTP

Nous avons déjà une Channelimplémentation simple , nous devons maintenant obtenir une connexion WebSocket avec laquelle travailler. Comme nous sommes toujours sous le titre Idiomatic Way , faisons-le de la manière correspondante.

Remarque: si vous ne savez pas comment fonctionne WebSocket, il convient de mentionner que le client passe au protocole WebSocket au moyen d'un mécanisme HTTP spécial appelé Upgrade. Après le traitement réussi d'une demande de mise à niveau, le serveur et le client utilisent la connexion TCP pour échanger des trames WebSocket binaires. Voici une description de la structure du cadre à l'intérieur de la connexion.
import ( "net/http" "some/websocket" ) http.HandleFunc("/v1/ws", func(w http.ResponseWriter, r *http.Request) { conn, _ := websocket.Upgrade(r, w) ch := NewChannel(conn) //... })

Veuillez noter que cela http.ResponseWriterpermet d'allouer de la mémoire pour bufio.Readeret bufio.Writer(tous deux avec une mémoire tampon de 4 Ko) pour l' *http.Requestinitialisation et l'écriture de la réponse.

Quelle que soit la bibliothèque WebSocket utilisée, après une réponse réussie à la demande de mise à niveau, le serveur reçoit des tampons d'E / S avec la connexion TCP après l' responseWriter.Hijack()appel.

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.

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