I build a system that runs agents on remote machines. A Go process on the machine streams events to browsers and phones through a relay. The relay is a Worker on Cloudflare Durable Objects that holds a WebSocket to the machine and one to each client, and forwards frames.
On Durable Objects, incoming WebSocket messages are billed and outgoing messages are not. Incoming messages count against requests at a 20:1 ratio. Every incoming message also runs the object’s handler, so an object that keeps receiving messages cannot hibernate either.
So on this relay, the number of messages is something you design. This post covers three ways to cut it. Up front: I did not measure how much any of them saves. What I can say is structural, counted from the messages that are no longer sent.
1. Batch events into one frame
Sending small events such as token deltas or state changes one at a time means paying per event. The sender holds them and ships them in one frame. That adds latency, so a window bounds it.
A batch is flushed on whichever of these comes first:
- Time. The window opens when the first event enters an empty batch and closes after a fixed delay. That is the latency bound.
- Count. A cap on events per frame.
- Bytes. A budget well under the frame cap. If the next event would exceed it, flush first.
package batch
import (
"context"
"errors"
"time"
)
type Event struct {
Name string `json:"event,omitempty"`
Data string `json:"data"`
}
// Frame is one message on the shared control socket.
type Frame struct {
Type string `json:"type"`
StreamID string `json:"stream_id"`
Event string `json:"event,omitempty"` // single-event form (older peers)
Data string `json:"data,omitempty"`
Events []Event `json:"events,omitempty"` // batched form, 2+ events
}
type Config struct {
Window time.Duration // latency bound
MaxEvents int
MaxBytes int // well under the frame cap
}
type WriteFunc func(context.Context, Frame) error
// Forward batches events from in until it closes or ctx ends. Whatever was
// accepted is flushed before returning, on every exit path.
func Forward(ctx context.Context, cfg Config, streamID string, in <-chan Event, write WriteFunc) (err error) {
var batch []Event
size := 0
timer := time.NewTimer(cfg.Window)
timer.Stop()
defer timer.Stop()
flush := func(wctx context.Context) error {
if len(batch) == 0 {
return nil
}
f := Frame{Type: "stream_data", StreamID: streamID}
if len(batch) == 1 { // a batch of one stays wire-compatible with old peers
f.Event, f.Data = batch[0].Name, batch[0].Data
} else {
f.Events = batch
}
batch, size = nil, 0
timer.Stop()
return write(wctx, f)
}
// The terminal frame must follow every accepted event, even when ctx has
// been cancelled. A write on a cancelled context would also tear down the
// shared socket, so use a detached context with its own deadline.
defer func() {
wctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
defer cancel()
err = errors.Join(err, flush(wctx))
}()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
if err := flush(context.WithoutCancel(ctx)); err != nil {
return err
}
case ev, ok := <-in:
if !ok {
return nil
}
n := len(ev.Name) + len(ev.Data)
if size+n > cfg.MaxBytes { // would overflow: ship what we have first
if err := flush(context.WithoutCancel(ctx)); err != nil {
return err
}
}
if len(batch) == 0 {
timer.Reset(cfg.Window) // the window opens with the first event
}
batch = append(batch, ev)
size += n
if size >= cfg.MaxBytes || len(batch) >= cfg.MaxEvents {
if err := flush(context.WithoutCancel(ctx)); err != nil {
return err
}
}
}
}
}
Three things are easy to get wrong.
A batch of one goes out in the old single-event form. An older peer that knows nothing about batches can still read it. The new form only appears when it saves something.
The window opens on the first event, not on a ticker. With a free-running ticker, an event that arrives just after a tick waits a whole window, and the goroutine wakes even when nothing is happening.
Accepted events go out before the terminal frame on every exit path. The WebSocket library used here closes the connection when you write with a cancelled context, and that connection is shared by every stream. So the last flush uses context.WithoutCancel with its own short deadline. Flushing on a cancelled context would drop the batch and take the other streams down with it. The regression test cancels with two events pending and checks that both arrive in one frame and that the context passed to the write was not cancelled.
func TestCancelFlushesAcceptedEventsOnADetachedContext(t *testing.T) {
s := &sink{}
in := make(chan Event)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
done <- Forward(ctx, Config{Window: time.Hour, MaxEvents: 100, MaxBytes: 1 << 20}, "s1", in, s.write)
}()
in <- Event{Data: "a"}
in <- Event{Data: "b"}
cancel()
err := <-done
if !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v", err)
}
if len(s.frames) != 1 || len(s.frames[0].Events) != 2 {
t.Fatalf("accepted events were dropped: %+v", s.frames)
}
if s.errs[0] != nil {
t.Fatalf("flush ran on a cancelled context: %v", s.errs[0])
}
}
The new form is used only when the receiver declares it can read it. The receiver sets accept_batches on its subscribe request, and a sender that does not know the field ignores it and keeps sending single events. That way the sender, relay and client can be deployed in any order. The relay is the part that needs care. Durable Objects hibernate, so in-memory state cannot be relied on. Subscriptions are stored with the socket and replayed when the machine reconnects. If the stored subscription forgets the flag, every replay silently drops the stream back to unbatched frames. Nothing breaks, so it only shows up as cost.
Responses larger than the frame cap are split, but anything that fits is not, because each chunk is a billed message. Splitting bit me once. The chunk index had omitempty, so Go’s encoding/json dropped index 0, and every first chunk went out without an index. Small responses never hit it, so the bug lived for a while. The test now checks that the key is present in the JSON on the wire, instead of round-tripping through the same struct. Chunking also made it possible to send huge diffs, but the real fix was not sending them: send only the list of changed files, and fetch one file’s contents when it is needed.
2. Replace polling with a subscription, and keep the poll as a fallback
The first implementation asked “what changed?” on timers. It reread the conversation list every few seconds and asked the server every few seconds whether the machine was online. A poll through the relay is two incoming messages: the client’s request and the machine’s response. One screen polling every T seconds costs 7200 / T messages per hour, even if it is just left open on a desk.
The machine already knows when a conversation changes, so it can send that without being asked. The stream sends one snapshot first, then an upsert for every change.
The important question is when the fallback poll may stop. A subscription that opened does not mean data will arrive. The relay may accept it while the machine never answers. Stop polling when the stream opens, and a stream that delivers nothing silences the poll forever. So “live” is set by the first frame.
// `live` means "data arrived", not "the socket opened".
export function createFeed(open) {
const state = { live: false, items: new Map() };
open({
snapshot(items) {
state.items = new Map(items.map((i) => [i.id, i]));
state.live = true;
},
upsert(item) {
state.items.set(item.id, item);
state.live = true;
},
closed() {
state.live = false; // keep the last items; the fallback poll refreshes them
},
});
return state;
}
// The fallback poll runs only when the stream is not delivering.
export const shouldPoll = (state, foreground) => foreground && !state.live;
On a drop, live goes back to false and the last known list stays. Old rows beat an empty screen. The poll runs only when the screen is visible and the stream is not live. For environments where the subscription cannot work at all (an older host, for example), the poll interval widens through 5, 10, 20 and 30 seconds while nothing changes.
Other rules I kept:
- One stream per key, shared by reference count. Five screens subscribing separately is worse than five polls.
- Reset the backoff only after a connection has stayed up for 30 seconds. Resetting on every open retries a flapping connection at the shortest interval forever.
- After a refused subscription, wait before retrying, even on a “retry now” signal such as returning to the foreground. A refusal is not a transient failure, and following the signal would make a tight loop.
In one place the stream stands in for another signal: the poll for whether the machine is online. In this system, online status is computed from the time of the last check-in, and nothing is written when a machine disappears, so there is no event to announce that it went offline. The rule became: while the stream is flowing, it is itself evidence of presence and the poll stops; when it drops, the poll resumes.
Stopping the poll exposed a hidden bug. The client’s transport remembers conversations it has seen and uses that to start per-conversation subscriptions. Conversations that arrived on the list stream were not being remembered. With the poll running nobody noticed; once it stopped, new conversations arrived on the stream but could not be subscribed to. The fix was to record stream-delivered conversations in the transport as well. When you remove a redundant poll, look for what it was quietly filling in.
3. If nobody needs the connection, do not hold it
The resident process on the machine keeps an outbound WebSocket to the relay so that clients can reach it. Most of the day nobody is looking. The connection still exists, and liveness messages still flow over it.
The resident process already calls the server periodically to say it is alive. I added one field to that reply: whether the connection is needed right now. No new poll, no new endpoint, and the same call wakes the process back up.
package idle
// HeartbeatReply is the answer to the heartbeat the host already sends.
// Needed is a pointer so that an older server that never sends the field
// is distinguishable from one that says "no".
type HeartbeatReply struct {
Needed *bool `json:"needed,omitempty"`
}
// KeepConnection reports whether the host should hold its relay connection.
// Unknown stays connected: an old server never sent the field, and a failed
// heartbeat is not evidence that nobody needs us.
func KeepConnection(reply HeartbeatReply, err error) bool {
return err != nil || reply.Needed == nil || *reply.Needed
}
The host disconnects only when told explicitly that it is not needed. An older server that does not send the field, and a failed call, both mean “stay connected”.
The price: work addressed to a sleeping host waits until the next heartbeat flips the answer and the host reconnects. That is at most one heartbeat plus connection setup. Anything that retries against a sleeping host needs a longer grace period than that. The real change had to extend its retry grace for exactly this reason. If “needed” flips on every heartbeat, the host connects and disconnects every time, so a minimum uptime after waking is the usual fix (not in the code above).
When not to use this
- Messages are free. Batching, shared subscriptions and sleep are all complexity. If a five-line poll is enough, it is better.
- Latency is critical. For something like input echo, a window of delay is a regression. Neither can the first request after idling absorb a heartbeat of delay.
- “The stream is down” cannot be told from “nothing happened”. Without a protocol that sends a snapshot first, keep the poll.
- The current state cannot be reread on reconnect. A subscription is an optimization over a source you can reread (resumable streams).
Send fewer messages
When every message is billed, send fewer of them. Batch them, wait to be told instead of asking, and disconnect when nobody is there. Build each one so that when the stream stops, it falls back to the safe side: single events, polling, staying connected.