In this lesson · topic 5 of 7
Topic 5
Gateways, connections and crashes
6 min read
What a gateway does
A gateway server holds long-lived connections and does little else. It checks who a client is, forwards sends to the message service and writes pushed messages to the right connection. Keeping the gateway thin keeps it cheap per connection, and it lets you scale it separately from the logic behind it.
Gateways hold state, which is who is connected to them. That makes them different from ordinary web servers. A load balancer sends a new connection to any gateway, using ideas from load balancing. A long connection pins one user to one gateway for its life.
Finding the user’s gateway
When the message service has a message for user B, it must know B’s gateway. Keep a session map in a fast store. On connect, the gateway writes user B is on gateway 3. On disconnect or timeout, it removes it. The message service looks it up and sends to that gateway. If there is no entry, B is offline and the message goes to the inbox only.
The alternative is a publish and subscribe channel per user or per gateway. The gateway subscribes for the users it holds. The message service publishes and does not need a map. See partitioned logs for the streaming cousin of this idea.
When a gateway dies
All its connections drop at once. The map still names the dead gateway for a while, so messages sent there vanish into a connection that does not exist. That is acceptable only because delivery is at-least-once. The message is not acknowledged, so the server sends it again after a timeout, and by then the user has reconnected somewhere else.
In the lab, 4 gateways were each given a 0.5 percent chance of crashing per tick, which gave 14 crashesmeasured in 500 ticks. At 2 percent there were 34 crashesmeasured. With no loss and nobody going offline, the 99th percentile delay was 4 ticksmeasured against 0 ticksmeasured with no crashes. Crashes added delay, and no message was lost.
The reconnect storm
When a gateway with 100,000 users dies, 100,000 clients reconnect at once. Spread them out with random delay and exponential backoff on the client, and rate limit new connections at the gateways. See rate limiting algorithms. Without that, the survivors take the whole load together and may fall over too.
Detecting a dead connection
A connection can die without either side being told, for example when a phone leaves coverage. Both sides send a small ping on a timer and close the connection when a reply does not come. The same idea runs through failure detection. Choose the interval from the cost of the pings against how long you can accept not knowing.