Websockets in Go: what changes past one server

Go holds websockets well: each connection gets two goroutines, and in our test one process kept 10,000 connections open in about 200 MB and sent one message to all of them in 138 milliseconds. Past one server, each process knows only its own connections, so every message has to cross a channel the processes share, and the usual channel, Redis pub/sub, drops what is sent while a process reconnects.
This post builds a websocket server in Go with gorilla/websocket, measures it, runs two copies of it with and without Redis between them, and shows where messages get lost and how to keep them.
Which package to use
The standard library has no websocket server. The golang.org/x/net/websocket package does, and its own documentation says it lacks features found in two packages that are more actively maintained: gorilla/websocket and coder/websocket. Both implement the WebSocket protocol on top of net/http.
gorilla/websocket is the one people search for as "gorilla websockets". Its rule for each connection is short: "Connections support one concurrent reader and one concurrent writer." coder/websocket takes a context.Context in its calls and allows concurrent writes. The server below uses gorilla/websocket 1.5.3, and everything after it applies to either package.
go get github.com/gorilla/websocketA websocket server in Go
Every connection gets a reader goroutine and a writer goroutine. The reader takes what the page sends and passes it on. The writer is the only code that writes to the connection, from a queue of its own, so two messages never write at once. A hub keeps the connections of this process in a map.
package main
import (
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
const (
pongWait = 60 * time.Second // a connection silent this long is gone
pingPeriod = 50 * time.Second // so ping before pongWait runs out
writeWait = 10 * time.Second
)
// No CheckOrigin: gorilla then refuses pages from any other host.
var upgrader = websocket.Upgrader{}
type client struct {
conn *websocket.Conn
send chan []byte
}
type hub struct {
mu sync.Mutex
clients map[*client]bool
publish func(msg []byte) // where a message from a page goes
}
func (h *hub) add(c *client) {
h.mu.Lock()
h.clients[c] = true
h.mu.Unlock()
}
func (h *hub) remove(c *client) {
h.mu.Lock()
if h.clients[c] {
delete(h.clients, c)
close(c.send)
}
h.mu.Unlock()
}
// broadcast hands a message to every connection of this process.
func (h *hub) broadcast(msg []byte) {
h.mu.Lock()
defer h.mu.Unlock()
for c := range h.clients {
select {
case c.send <- msg:
default: // its queue is full, a reader too slow to keep: let it go
delete(h.clients, c)
close(c.send)
}
}
}
// writer is the one goroutine that writes to this connection.
func (c *client) writer() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case msg, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
if err := c.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
// reader is the one goroutine that reads from it.
func (h *hub) reader(c *client) {
defer func() {
h.remove(c)
c.conn.Close()
}()
c.conn.SetReadLimit(64 << 10)
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error {
return c.conn.SetReadDeadline(time.Now().Add(pongWait))
})
for {
_, msg, err := c.conn.ReadMessage()
if err != nil {
return
}
h.publish(msg)
}
}
func main() {
h := &hub{clients: map[*client]bool{}}
h.publish = h.broadcast // one process: straight to its own pages
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return // Upgrade has already answered with an HTTP error
}
c := &client{conn: conn, send: make(chan []byte, 32)}
h.add(c)
go c.writer()
go h.reader(c)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}Run it with go run ., and a page served from the same host connects with the WebSocket API of the browser:
const socket = new WebSocket( 'ws://localhost:8080/ws' );
socket.onopen = () => socket.send( 'hello' );
socket.onmessage = ( event ) => console.log( event.data );Open it in two tabs and each one prints what either sends. These details in that code decide how it behaves under real use:
- The origin check. A page on any site can open a websocket to your server, and the standard leaves refusing it to the server. With no
CheckOriginof yours, gorilla/websocket refuses a request whoseOriginnames another host. A function that returnstruefor every request lets every site in, so list your own hosts there instead. - One writer. Concurrent writes to one gorilla connection corrupt it. Here only
writer()writes, andbroadcast()hands it messages through its channel. - A slow reader is dropped. A phone on a bad network can stop reading while others keep sending. Its queue of 32 fills, and the hub lets it go rather than wait for it, so one slow page never holds up the rest.
- Ping and pong. The server pings every 50 seconds, and a browser answers each ping with a pong by itself, as RFC 6455 requires. Each pong moves the read deadline 60 seconds on, so a connection whose network went away with no close frame is found within a minute. The ping also keeps proxies from closing an idle connection: nginx closes a proxied websocket that sends nothing for 60 seconds, by default.
Once it runs on a public address, our WebSocket test connects to it from a browser and explains any close code, and our post on WebSocket error 1006 helps when a browser only says the connection failed.
What one process holds
We opened 10,000 connections to this server from a test client in Go on the same laptop, a MacBook Pro with an M1 Max, Go 1.26.1:
| Measure | Result |
|---|---|
| Memory of the server, idle | 11 MB |
| With 10,000 connections | 208 MB, about 20 KB each |
| Opening all 10,000 | 0.4 s |
| One message to all 10,000 | 138 ms |
Those 20 KB hold the read and write buffers of each connection, 4 KB each by default, and the stacks of its two goroutines. A server with a few gigabytes of memory holds far more connections than most apps ever have open, so in Go the first limit is rarely the number of connections.
The first runs failed in the operating system, not in Go. macOS keeps 128 connections waiting to be accepted (kern.ipc.somaxconn), which a client opening hundreds at once overflows, and gives outgoing connections local ports from 49152 to 65535, about 16,000, which ran out while closed connections still held theirs. On a Linux server the limit to raise first is open files, ulimit -n, as each connection is one.
Past one server
The map in hub lives in the memory of one process. A second process, for a deploy without downtime, a second machine or a second region, has a map of its own, and a message sent on one never reaches the pages connected to the other. We started two copies, opened 4,000 connections split between them, and sent one message on the first:
| Setup | Pages on the first | Pages on the second |
|---|---|---|
| Two processes, nothing between them | 2,000 of 2,000 | 0 of 2,000 |
| The same, through Redis pub/sub | 2,000 of 2,000 | 2,000 of 2,000 |
The usual fix is a channel all processes share. With Redis, each process publishes what its pages send and subscribes to what the others publish, and its hub sends that to its own pages. The change to main(), with go-redis:
// main.go, in main(): every process publishes what its pages send,
// and hands what Redis brings to its own pages.
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
h.publish = func(msg []byte) { rdb.Publish(ctx, "chat", msg) }
go func() {
for m := range rdb.Subscribe(ctx, "chat").Channel() {
h.broadcast([]byte(m.Payload))
}
}()With it, all 4,000 pages got the message within 31 ms.
What Redis pub/sub drops
Redis pub/sub delivers at most once: a message goes to the subscribers connected at that moment, and to nobody later. go-redis subscribes again by itself after a network error, which keeps the server running, and what was published in between is gone. We sent 1,000 messages, 2 ms apart, to 200 pages on the two processes:
- The subscribers cut off once. With
CLIENT KILL TYPE pubsubin the middle, every page missed one message in two runs of three, and none in the third. go-redis was back within a few milliseconds, and nothing told the pages a message was missing. - Redis restarted. Stopped and started again, down for about half a second, the pages got 743 to 745 of the 1,000. The code above drops the error
Publishreturns, so the server said nothing either.
A chat that loses one message in a thousand loses messages every day. Keeping them takes a few more parts, each one yours to build and run:
- Ids and a log. Give each message an id and keep the recent ones, in Redis Streams or your database, so a reader can ask for everything after the last id it saw.
- Reconnects in the page. The WebSocket of a browser never reconnects by itself. Your page code reconnects after a growing delay and sends the last id it has, and the server replays what came after.
- Deploys. A restart closes every connection of that process, and all its pages reconnect at once to the others, so they need room for them.
- Who is online. Presence across processes needs a shared list whose entries expire, or a process that crashes leaves its users online.
Our post on WebSockets in JavaScript builds the page side of this, a client that reconnects and asks for what it missed, tested against a server that drops, restarts and stops answering.
Or keep the connections elsewhere
| Setup | Where connections live | What you run |
|---|---|---|
| One Go process | In its memory | The server, a proxy, its deploys |
| Several, through Redis | In each process | Those, plus Redis, ids, a log and replay |
| A hosted service | On its servers | Your app, sending one request for each event |
With a hosted realtime service, the browsers connect to its servers. Your Go app sends each event in one HTTPS request, from the handler that saved the change, and the service delivers it to every page in the room, whichever of your servers sent it.
Go on WordPlus Cloud
There is no Go package of ours. The HTTP API of WordPlus Cloud is signed JSON over HTTPS, so any Go server can use it, and the docs have a whole app server in Go written on it alone: wordplus.go, one file of about 860 lines on the standard library and golang.org/x/crypto, checked against the published test values, and main.go with the rules and routes of an example app. Copy wordplus.go into your module.
Your app decides who may join each room. This is the room of an order, for its customer, keeping its last 10 events:
// Who may join each room, as your app decides it.
func roomRule(room, user string) (*wordplus.Room, string) {
if m := orders.FindStringSubmatch(room); m != nil {
if user == "" || orderOwner(m[1]) != user {
return nil, "forbidden"
}
return &wordplus.Room{History: 10, Sealed: true}, ""
}
return nil, "no_rule"
}After your own work is saved, send to everyone in the room, sealed with its key and kept for pages that reconnect:
// In the handler that marked order 1042 shipped.
_, err := app.Emit("order:1042", "updated", map[string]any{"status": "shipped"}, true, 10)The page gets its settings from your /api/realtime/config route and joins:
import { connect } from '@wordplus/realtime';
const rt = await connect( await ( await fetch( '/api/realtime/config' ) ).json() );
const order = rt.join( 'order:1042' );
order.on( 'updated', ( data ) => showStatus( data.status ) );That Emit is one HTTPS request, so it works the same from any of your servers, a cron job or a queue worker. Beyond it:
- Any server, any room. Each of your servers sends to any room through the same API, and WordPlus Cloud delivers to every page in it.
- Nothing lost on a reconnect. A room keeps its last events for five minutes, so a page that drops and comes back gets what it missed, in order.
- Every page of one user.
app.EmitToUser("42", "notice", data)reaches every tab and device they have open. - Sealed on the way. Sent with
truefor sealed, as above, an event is encrypted with keys made from a local key on your server, which WordPlus Cloud never sees. - What pages send comes to you. A webhook brings it to your Go server, and
app.Webhook()checks its signature before your handler sees it. - More than events. Who is online, calls that ring in every tab, group calls and live streams come on the same connection, with tokens your Go server signs.
Jobs for a server of your own
A hosted service does not suit every job. Your Go code hears what pages send through a webhook, an HTTP request, and not in a loop beside each connection. A game whose server answers each move within milliseconds belongs on a server of its own, and Go is a good language for one. So does a protocol of your own that other programs speak over a plain websocket. And an internal tool for a few hundred people may never need more than the one process at the top of this post.
Start with the Go server
The Go page of the docs has the files and every route, and the HTTP API overview explains the same API for a server in Ruby, Java, Rust or any other language. The same question has other answers in Node.js, PHP and Django and Flask.
WordPlus Cloud for Apps is priced by concurrent connections, starting from 1,000, billed monthly or yearly, and our post on realtime pricing explains how counting by the connection works. Our WebSocket API page shows rooms, presence and events in each stack, the apps page the rest of what it does, and the apps pricing has the numbers. Questions about your integration? Write to us.