Un millón de WebSockets y listo

¡Hola a todos! Mi nombre es Sergey Kamardin y soy desarrollador en Mail.Ru.

Este artículo trata sobre cómo desarrollamos el servidor WebSocket de alta carga con Go.

Si está familiarizado con WebSockets, pero sabe poco sobre Go, espero que este artículo le resulte interesante en términos de ideas y técnicas para la optimización del rendimiento.

1. Introducción

Para definir el contexto de nuestra historia, conviene decir algunas palabras sobre por qué necesitamos este servidor.

Mail.Ru tiene muchos sistemas con estado. El almacenamiento de correo electrónico del usuario es uno de ellos. Hay varias formas de realizar un seguimiento de los cambios de estado dentro de un sistema y de los eventos del sistema. En su mayoría, esto es a través de encuestas periódicas del sistema o notificaciones del sistema sobre sus cambios de estado.

Ambas formas tienen sus pros y sus contras. Pero cuando se trata de correo, cuanto más rápido reciba un nuevo correo, mejor.

El sondeo de correo implica aproximadamente 50.000 consultas HTTP por segundo, el 60% de las cuales devuelven el estado 304, lo que significa que no hay cambios en el buzón.

Por lo tanto, para reducir la carga en los servidores y acelerar la entrega de correo a los usuarios, se tomó la decisión de reinventar la rueda escribiendo un servidor editor-suscriptor (también conocido como bus, agente de mensajes o evento- canal) que recibiría notificaciones sobre cambios de estado, por un lado, y suscripciones para tales notificaciones, por el otro.

Previamente:

Ahora:

El primer esquema muestra cómo era antes. El navegador sondeó periódicamente la API y preguntó acerca de los cambios de almacenamiento (servicio de buzón).

El segundo esquema describe la nueva arquitectura. El navegador establece una conexión WebSocket con la API de notificación, que es un cliente del servidor de bus. Al recibir un nuevo correo electrónico, Storage envía una notificación al Bus (1) y Bus a sus suscriptores (2). La API determina la conexión para enviar la notificación recibida y la envía al navegador del usuario (3).

Así que hoy vamos a hablar sobre la API o el servidor WebSocket. De cara al futuro, les diré que el servidor tendrá alrededor de 3 millones de conexiones en línea.

2. La forma idiomática

Veamos cómo implementaríamos ciertas partes de nuestro servidor usando funciones simples de Go sin ninguna optimización.

Antes de continuar net/http, hablemos de cómo enviaremos y recibiremos datos. Los datos que se encuentran por encima del protocolo WebSocket (por ejemplo, objetos JSON) se denominarán en lo sucesivo paquetes .

Comencemos a implementar la Channelestructura que contendrá la lógica de enviar y recibir dichos paquetes a través de la conexión WebSocket.

2.1. Estructura de canal

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

Me gustaría llamar su atención sobre el lanzamiento de dos gorutinas de lectura y escritura. Cada goroutine requiere su propia pila de memoria que puede tener un tamaño inicial de 2 a 8 KB, según el sistema operativo y la versión de Go.

Con respecto al número mencionado anteriormente de 3 millones de conexiones en línea, necesitaremos 24 GB de memoria (con la pila de 4 KB) para todas las conexiones. Y eso sin la memoria asignada para la Channelestructura, los paquetes salientes ch.sendy otros campos internos.

2.2. Gorutinas de E / S

Echemos un vistazo a la implementación del "lector":

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

Aquí usamos bufio.Readerpara reducir el número de read()llamadas al sistema y leer tantas como lo permita el buftamaño del búfer. Dentro del ciclo infinito, esperamos que lleguen nuevos datos. Recuerde las palabras: espere que lleguen nuevos datos. Volveremos a ellos más tarde.

Dejaremos de lado el análisis y procesamiento de los paquetes entrantes, ya que no es importante para las optimizaciones de las que hablaremos. Sin embargo, bufmerece nuestra atención ahora: por defecto, son 4 KB, lo que significa otros 12 GB de memoria para nuestras conexiones. Existe una situación similar con el "escritor":

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

Iteramos a través del canal de paquetes salientes c.sendy los escribimos en el búfer. Esto es, como ya pueden adivinar nuestros lectores atentos, otros 4 KB y 12 GB de memoria para nuestras 3 millones de conexiones.

2.3. HTTP

Ya tenemos una Channelimplementación simple , ahora necesitamos obtener una conexión WebSocket para trabajar. Como todavía estamos bajo el encabezado Camino Idiomático , hagámoslo de la manera correspondiente.

Nota: Si no sabe cómo funciona WebSocket, debe mencionarse que el cliente cambia al protocolo WebSocket por medio de un mecanismo HTTP especial llamado Upgrade. Después del procesamiento exitoso de una solicitud de actualización, el servidor y el cliente utilizan la conexión TCP para intercambiar marcos WebSocket binarios. Aquí hay una descripción de la estructura del marco dentro de la conexión.
import ( "net/http" "some/websocket" ) http.HandleFunc("/v1/ws", func(w http.ResponseWriter, r *http.Request) { conn, _ := websocket.Upgrade(r, w) ch := NewChannel(conn) //... })

Tenga en cuenta que http.ResponseWriterhace la asignación de memoria para bufio.Readery bufio.Writer(ambos con búfer de 4 KB) para *http.Requestinicialización y escritura de respuesta adicional.

Independientemente de la biblioteca WebSocket utilizada, después de una respuesta exitosa a la solicitud de actualización, el servidor recibe búferes de E / S junto con la conexión TCP después de la responseWriter.Hijack()llamada.

Sugerencia: en algunos casos, go:linknamese puede usar para devolver los búferes al sync.Poolinterior a net/httptravés de la llamada net/http.putBufio{Reader,Writer}.

Por tanto, necesitamos otros 24 GB de memoria para 3 millones de conexiones.

Entonces, ¡un total de 72 GB de memoria para la aplicación que aún no hace nada!

3. Optimizaciones

Repasemos de lo que hablamos en la parte de introducción y recordemos cómo se comporta una conexión de usuario. Después de cambiar a WebSocket, el cliente envía un paquete con los eventos relevantes o, en otras palabras, se suscribe a los eventos. Entonces (sin tener en cuenta mensajes técnicos como ping/pong), el cliente no puede enviar nada más durante toda la vida útil de la conexión.

La duración de la conexión puede durar desde varios segundos hasta varios días.

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