More than one instance

11 min read · Edit this page on GitHub

What this covers: what a borgo process keeps to itself, what that means when two or more of them run behind a load balancer, and what an app does about each. One instance needs none of this page.

A borgo instance is the pair borgo start supervises, the Go front and its render service. The two halves cannot be split, so scaling out is running more pairs, each with its own public port, behind something that spreads requests over them. borgo has no cluster mode and no shared state of its own: an instance does not know the others exist. Everything below follows from that.

What is shared and what is not#

What Where it lives With several instances
Sessions the signed cookie work on any instance that has the same SESSION_SECRET — sessions and the key
The CSRF token a cookie, echoed by the request works on any instance: nothing is kept on the server
WebSocket topics, borgo.Push the relay, in memory Push reaches the sockets of its own instance — FanOut and Deliver
borgo.Subscribers, borgo.Disconnect, the __count event the same relay each answers for the sockets of the instance it runs in
borgo.SSEHub memory Publish reaches the streams of its own instance — event streams
The page cache, borgo.Revalidate memory, and the instance's own disk one copy per instance, dropped per instance — cached pages
The sign-in limit, borgo.Limit memory counted per instance — limits
borgo.Uploads a directory on local disk a file is on the instance that saved it — uploads
A map in your own code: a revocation cutoff, a rate limiter memory per instance, like borgo's own
The database wherever it is shared, which is why it is the usual answer to the rows above

The caps a process puts on itself — BORGO_MAX_SOCKETS, BORGO_MAX_STREAMS, BORGO_MAX_INFLIGHT, BORGO_HASH_SLOTS — are per instance too, and that is what they are for: each bounds what one process holds.

Sessions and the key#

A session is a cookie signed with SESSION_SECRET, verified by the Go front of whichever instance receives the request, with no lookup anywhere. Give every instance the same key and a session written by one is read by all. Give them different keys and a visitor is signed in on one instance and anonymous on the next, request by request.

What an app adds on top is not automatically shared. A CheckSession that reads a map in memory revokes on the instance that recorded the cutoff and nowhere else: keep the cutoffs in the database.

Rotating the key has one more step than on a single instance, because a rolling restart has both generations running at once. An instance still on the old configuration cannot read a session the new key signed, so for the length of the rollout a visitor who signed in on a new instance is anonymous on an old one. To avoid that, let every instance learn the new key before any instance signs with it:

  1. On every instance, add the new key to SESSION_SECRET_PREVIOUS and leave SESSION_SECRET as it is. Roll that out. A key in that list verifies and never signs, so nothing changes yet, and every instance can now read both.
  2. Swap them: the new key becomes SESSION_SECRET, the old one goes to SESSION_SECRET_PREVIOUS. Roll that out. Whichever instance a request reaches during the rollout reads both keys.
  3. Take the old key out once the longest session it signed has run out.

WebSocket topics: FanOut and Deliver#

The relay is in the process. borgo.Push hands an event to the sockets that process holds, and with two instances behind a balancer half the subscribers of a topic hear nothing. The cure is a bus every instance can publish to and listen on — Postgres LISTEN/NOTIFY, Redis, NATS — and borgo does not choose one. It provides the two ends:

  • borgo.FanOut(send) sets where Push sends an event. With one set, Push checks the event as it would at delivery — the topic, the size, that the data encodes — hands it to send with the data already JSON, and returns what send returns. It delivers nothing itself.
  • borgo.Deliver(topic, event, data) gives an event to the sockets of this process and to no bus. It is what the listening end calls with what the bus brought.

So every event takes one road: out through the bus, and back to every instance, the sender among them. An instance that cannot reach the bus fails its Push, and the handler that called it knows, instead of telling half the room.

Here are both ends on Postgres. What borgo needs is the same on any bus:

// what crosses the bus: one event, as Push encoded it
type busEvent struct {
	Topic string          `json:"t"`
	Event string          `json:"e"`
	Data  json.RawMessage `json:"d"`
}

// Notify is the sending half of the bus: one payload to every listener.
type Notify func(ctx context.Context, payload string) error

// NOTIFY refuses a payload of 8000 bytes or more
const notifyLimit = 7999

// fanOutOver makes every borgo.Push of this process a NOTIFY
func fanOutOver(notify Notify) {
	borgo.FanOut(func(topic, event string, data json.RawMessage) error {
		payload, err := json.Marshal(busEvent{Topic: topic, Event: event, Data: data})
		if err != nil {
			return err
		}
		if len(payload) > notifyLimit {
			return errors.New("the event " + topic + "/" + event + " is too large for NOTIFY: push an id and let the page fetch the rest")
		}
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		return notify(ctx, string(payload))
	})
}

// received is what the listening half calls with each payload it is handed
func received(payload string) {
	var e busEvent
	if err := json.Unmarshal([]byte(payload), &e); err != nil {
		log.Printf("bus: a payload that is not an event: %v", err)
		return
	}
	if err := borgo.Deliver(e.Topic, e.Event, e.Data); err != nil {
		log.Printf("bus: %v", err)
	}
}

The sending half is one statement, and database/sql is enough for it, with any Postgres driver:

notify := func(ctx context.Context, payload string) error {
	_, err := db.ExecContext(ctx, "select pg_notify('borgo', $1)", payload)
	return err
}
fanOutOver(notify) // in main, before borgo.Serve

The listening half is the driver's, and it is not shown here because database/sql has no call for it: a pool hands out connections and takes them back, and LISTEN belongs to one connection that stays open and waits. Each Postgres driver has its own way to hold such a connection and be told of a notification — WaitForNotification on a connection in pgx, a Listener in lib/pq. Whichever it is, the loop around it has four duties:

  • open a connection of its own, outside the pool, and issue LISTEN borgo;
  • call received(payload) for each notification;
  • when the connection drops, reconnect with a pause and issue LISTEN again — a notification sent while nobody was listening is gone;
  • run in a goroutine started from main, and stop when the process does.

What this gives, and what it does not:

  • The 8000 bytes are Postgres's. A NOTIFY payload must be shorter than that in the default configuration, and the envelope above spends a few dozen of them. A socket can carry 1 MB; the bus cannot. The check above turns an event that would not fit into an error from Push, and the fix is the one borgo's own message for a large event names: push an id, and let the page fetch the rest.
  • A Push is now a round trip to the database, on the request that made it. A database that is slow makes Push slow, and one that is down makes it fail.
  • No delivery guarantee, as before. The relay never had one, and the bus adds a second place to miss an event: an instance whose listening connection was down has subscribers who missed what was sent meanwhile and whose sockets never closed, so their onOpen({ reconnected }) did not fire. A page that must not miss an event refetches on a timer or on its next action as well.
  • A connection pooler in transaction mode does not carry LISTEN. The listening connection goes to Postgres directly, or through a pooler in session mode.
  • Only Push is fanned out. An event a browser publishes with channel.publish is relayed to the sockets of the instance that received it and is not handed to FanOut. Where every subscriber must see what a browser sends, send it through a Go route that calls Push.
  • Authorization does not change. CanSubscribe is asked by the instance a socket connects to, with the session, as on one instance; what crosses the bus is events for topics, and each instance delivers them to the sockets it already admitted.
  • borgo.FanOut(nil) removes it, and Push delivers to this process's sockets again. A test that wants no bus calls nothing.

Event streams#

A borgo.SSEHub is a value in one process: Publish writes to the streams that process holds. The cure has the same shape as for topics, without a helper, because a hub is yours and so is its event: send what you would have published through the bus, and let each instance's listener call Publish on its own hub. A stream written by hand with borgo.SSE is one request on one instance and needs nothing.

Cached pages#

A page with revalidate is rendered once per instance and kept in that instance's memory, with a copy under its own BORGO_CACHE_DIR. borgo.Revalidate and borgo.RevalidateTag are calls into the cache of the process they run in: the handler that wrote the data drops the copy on the instance that served the write, and every other instance goes on serving its copy until its window ends.

Two ways to live with that:

  • Short windows. With revalidate = 30 every instance is at most thirty seconds behind, whatever was or was not invalidated. For most pages this is the whole answer.
  • Invalidate on every instance. A page with revalidate = "manual" never goes stale by the clock, so a copy an invalidation did not reach is kept until the instance restarts. Carry the invalidation over the same bus as the events, on a channel of its own:
// the handler that wrote the data tells every instance, this one included
func revalidateEverywhere(ctx context.Context, notify Notify, tag string) error {
	return notify(ctx, tag)
}

// each instance's listener, for the channel the tags travel on
func tagReceived(tag string) {
	if err := borgo.RevalidateTag(tag); err != nil {
		log.Printf("bus: revalidate %q: %v", tag, err)
	}
}

A copy is keyed to the build that rendered it, so a new build starts cold on every instance and no instance serves a page another build made.

Limits counted in memory#

The sign-in limit and every borgo.Limit keep their counts in the process. Behind a balancer that spreads a client's requests over N instances, each instance counts the part it saw, and the allowance a client meets is up to N times the number you wrote: ten failed sign-ins a minute is up to thirty with three instances. The same is true of a limiter of your own that counts in a map.

What an app does depends on what the limit is for. One that protects a resource of the instance — hashing, a slow handler — is right per instance, and needs nothing. For one that is a promise about a client, divide the number by the instance count and accept the imprecision, or make the balancer send a client to the same instance, or count in something shared: the proxy's own rate limiting, which sees every request before it is spread, or a table. Auth.OnEvent reports each failed sign-in with its address, which is where a shared count of those starts.

Uploads#

borgo.Uploads writes to Dir and reads from Dir, a directory on the instance's disk. A file saved by one instance is a 404 on the next, since a key that names no file there is a 404. Dir has to be storage every instance sees: a network file system or a shared volume mounted at the same path on each. The files are created 0600 in a directory created 0700, so the instances have to run as the same user. Storage that is not a file system needs a different answer: see file storage beyond local disk.

Rolling deploys#

A rolling deploy is more than one instance for a few minutes, with one difference: the instances are not the same build.

  • Send requests only to an instance that is ready. Point the balancer's health check at /readyz: 200 once the render service answers and the app's own checks pass, 503 before, and 503 again from the moment the instance is told to stop.
  • Let an instance leave before it closes. BORGO_SHUTDOWN_DELAY keeps a stopping instance serving, with /readyz at 503, for as long as the balancer takes to notice. Then it stops accepting, finishes what is in flight within BORGO_SHUTDOWN_TIMEOUT, and ends its streams; the sockets and streams it held reconnect by themselves, to whichever instance the balancer gives them.
  • A tab outlives the build it loaded. The props a client navigation fetches name the build that made them, by its client entry. A tab running another build loads the next page whole, so new data is never rendered by old components.
  • An instance serves the files of its own build. While two builds are in rotation, a document from one can ask the other for a chunk it does not have. For a client navigation that is one of the cases the runtime falls back from with a full page load. For the scripts of a freshly loaded document there is nothing to fall back to, and that page is not interactive until it is reloaded. borgo does nothing about this. Keep the window short, or switch instead of rolling — start the whole new set, wait for /readyz, move the balancer in one step — or have the balancer keep a client on one instance for the length of the rollout.
  • Migrations run once, before the new instances start: see the database.

What does not need attention#

The CSRF token is a cookie compared with what the request echoes, with nothing kept on the server. The key between a front and its render service is minted per boot and never leaves the pair. /healthz, /readyz and /metrics answer for the instance that was asked, which is what a balancer and a scraper want: scrape each instance at its own address, not through the balancer, where every scrape would be a different instance's numbers.