Relay
Case Study
Overview
A work-stealing job scheduler for a logistics platform, replacing a single-queue worker pool that stalled under burst traffic. It runs as one process or on Kubernetes with autoscaling workers, and ships with a full logistics workspace and a 3D map whose fleet grows from horse carts to container ships.
p95 queue latency fell from 1.36 s to 672 ms against the single-queue baseline on a 12,000-job burst. On Kubernetes, KEDA scaled workers from 1 to 5 pods through a 380,000-job flood without losing a job.
Where it started
Relay started as a draft project idea, but it turned into the project that taught me logistics.
When I was building my software business, I needed to truly understand the industry I'd be providing services for, so Relay became part of my research and development.
The problem
Logistics platforms run on background jobs: routing, labels, tracking syncs and stock picks. A single queue feeding one shared worker pool stalls when traffic bursts, because one slow job (a stuck ERP call, say) holds up everything behind it.
Work-stealing workers
Each worker keeps its own local queue, topped up from a Redis Stream. When it runs dry, it steals jobs that have sat idle for 2 seconds in a peer's pending list, so a slow or crashed worker can't strand work.
relay/worker.go
func (w *Worker) Run(ctx context.Context) {
for ctx.Err() == nil {
job, ok := w.local.Pop()
if !ok {
job, ok = w.steal(ctx)
}
if !ok {
w.park(ctx, 50*time.Millisecond)
continue
}
w.exec(ctx, job)
}
}
func (w *Worker) steal(ctx context.Context) (Job, bool) {
res, _, err := w.rdb.XAutoClaim(ctx,
&redis.XAutoClaimArgs{
Stream: "relay:jobs", Group: "workers",
Consumer: w.id, MinIdle: 2 * time.Second,
Start: "0-0", Count: 1,
}).Result()
Exactly one execution
Stealing means two workers can hold the same job, so Postgres decides who runs it. A conditional update only moves a job from queued to running once; the loser simply acknowledges the message and moves on. Failed attempts retry with backoff, up to three times.
internal/store/store.go
func (s *Store) Claim(ctx context.Context, id int64, worker string, stolen bool, at time.Time) (int, bool, error) {
var attempts int
err := s.pool.QueryRow(ctx, `
UPDATE jobs SET status = 'running', worker = $2, stolen = $3, started_at = $4, attempts = attempts + 1
WHERE id = $1 AND status = 'queued' RETURNING attempts`, id, worker, stolen, at).Scan(&attempts)
if errors.Is(err, pgx.ErrNoRows) {
return 0, false, nil
}
return attempts, err == nil, err
}
The results
Relay can switch between work-stealing and the old single-queue shape at runtime, so the two can be compared on the same machine. On a 12,000-job burst, p95 queue latency fell from 1.36 s to 693 ms, and throughput rose from about 8,100 to 15,500 jobs a second.
A realm that grows
To make logistics feel alive, every delivery earns XP for its mode, and a 3D map of the network levels up with it: sailboats become container ships, horse carts become road trains, and balloons become heavy-lift jets.
internal/realm/realm.go
// Thresholds is the XP (one per delivery) needed to reach each level.
var Thresholds = []int{0, 50, 150, 400, 1000}
var Tiers = map[string][]Tier{
"sea": {
{1, "Sailboat", "Fishing quay", "Single-mast sailboats ferry crates along the coast."},
{2, "Galleon", "Merchant harbour", "Three-masted galleons carry bulk goods between ports."},
{3, "Steamship", "Age of steam", "Coal-fired steamers keep schedules whatever the wind."},
{4, "Coastal freighter", "Feeder port", "Feeder freighters shuttle stacked containers between hubs."},
{5, "Container ship", "Deep-water terminal", "Ultra-large container ships berth at your docks."},
},
From one process to a cluster
Version 2.1 runs Relay on Kubernetes without changing how it runs anywhere else. The same binary takes a role: everything in one process (still the default), just the API, or just workers. On a cluster the API and the workers scale separately, and KEDA adds worker pods, from 1 to 20, as the job stream's backlog grows.
Splitting one process into many raised problems a single process never has. The live metrics on the Runtime page lived in the API's memory, which would see no completions once the workers moved out, so worker pods now stream their metrics over Redis and every API replica replays them. Only one replica should run the simulation, so the replicas elect a leader with a Postgres lock, and another takes over within about five seconds if it disappears.
Scaling down without losing work
With autoscaling, pods get stopped all the time, so shutting down had to be as reliable as running. When a pod is told to stop, its workers finish the job in hand. Jobs still waiting in their local queues are handed back, backdated in the stream so a peer picks them up at once. Retries still waiting out their backoff are sent now, and every outcome is saved before the process exits.
Building this turned up a real bug: the code that saves outcomes used to stop on the same signal as the workers, so a job that finished during shutdown stayed “running” in Postgres forever. There's a regression test for it now, and a reaper requeues jobs left stuck by pods that die without warning.
relay/shutdown.go
// handBack releases the jobs left in local deques to the other consumers.
func (rt *Runtime) handBack(ctx context.Context) {
for _, w := range rt.workers {
left := w.local.take()
if len(left) == 0 {
continue
}
args := []any{"XCLAIM", StreamKey, GroupName, w.id, 0}
for _, j := range left {
args = append(args, j.MsgID)
}
// JUSTID leaves the delivery counter alone; IDLE backdates the
// message so peers' XAUTOCLAIM picks it up immediately.
args = append(args, "IDLE", handBackIdle.Milliseconds(), "JUSTID")
rt.rdb.Do(ctx, args...)
}
}
What the load tests taught
On a kind cluster on my laptop, a two-minute flood of 380,000 jobs took the workers from 1 to 5 pods in about 20 seconds. Every job finished, and the backlog cleared 5 seconds after the flood stopped.
The runs before that taught me more. Throughput fell to about 24 jobs a second after every scale-up, because each new pod re-ran the database schema, and CREATE INDEX IF NOT EXISTS still locks the jobs table even when the index already exists. Pods now migrate only when the schema has actually changed. The other lesson: for workers that prefetch, the pending backlog is a noisy signal. When pods keep up it looks small even under a steady flood, so KEDA scaled down mid-run and had to scale straight back up. I lengthened the scale-down window from 60 to 180 seconds and noted a second trigger as the next step.
internal/store/bootstrap.go
// Pods that scale up under load must not re-run the schema: even with IF
// NOT EXISTS, CREATE INDEX takes a SHARE lock on jobs, and every insert,
// claim and outcome write queues behind it. With several pods starting at
// once that froze the job table for tens of seconds.
func (s *Store) MigrateIfChanged(ctx context.Context) (bool, error) {
var applied string
err := s.pool.QueryRow(ctx, `SELECT value FROM relay_meta WHERE key = 'schema_hash'`).Scan(&applied)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return false, err
}
if applied == schemaHash {
return false, nil
}
if err := s.Migrate(ctx); err != nil {
return false, err
}