Compare commits

..
2 Commits
Author SHA1 Message Date
Sebi 9d1d6a2544 Merge pull request 'feat(schedule): spread monitor runs evenly over their interval' (#174) from feat/schedule-phase into main
ci / lint (push) Successful in 12m50s
ci / test (push) Successful in 13m53s
ci / build (push) Successful in 20m40s
ci / image (push) Successful in 4m21s
release / release (push) Successful in 42m44s
2026-11-29 15:07:46 +00:00
Sebastian UnterschützandClaude Opus 5.5 050c9dd0a1 feat(schedule): spread monitor runs evenly over their interval
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m40s
ci / test (pull_request) Failing after 13m52s
ci / build (pull_request) Skipped
ci / image (pull_request) Skipped
A monitor's next run was its last due time plus the interval, so monitors
created together, by an import or a test, stayed due in the same second
for good, and late runs all gathered at the dispatch time. In prod, regions
fell behind in waves every interval although the checkers kept up on
average.

Each monitor now has a fixed phase within its interval, from its ID.
After the first run, still right away, it runs on its phase; late runs
snap to their next slot. Reconcile adds lost monitors on their phase, so
rebuilding a schedule causes no burst either. Monitors scheduled before
phases existed keep the old rule until reconciliation adds their phase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 16:06:40 +01:00
2 changed files with 220 additions and 14 deletions

No files matched your search

+74 -12
View File
@@ -7,12 +7,18 @@
// number of API replicas can dispatch concurrently without a leader, and a
// lost job never stops a monitor from running again.
//
// Each monitor has a fixed phase within its interval, derived from its ID.
// After its first run, which is right away, a monitor runs on its phase, so
// runs spread evenly over the interval however the monitors were created,
// and late runs do not all gather at the moment they were dispatched.
//
// Instances announce themselves by polling. One that stops polling is
// considered gone after StaleAfter; its queued jobs return to the region.
package schedule
import (
"context"
"encoding/binary"
"errors"
"fmt"
"strconv"
@@ -33,6 +39,8 @@ const (
const (
keyRegions = "sched:regions"
keyIntervals = "sched:intervals"
// keyPhases holds each monitor's phase within its interval, in ms.
keyPhases = "sched:phases"
// keyTouched records when each monitor was last upserted, so a
// reconciliation based on an older database read leaves it alone.
keyTouched = "sched:touched"
@@ -69,20 +77,55 @@ type Monitor struct {
Regions []string
}
// phaseOf returns the phase of monitor id within interval, in ms. The ID's
// random bits spread the phases of all monitors evenly.
func phaseOf(id uuid.UUID, interval time.Duration) int64 {
ms := interval.Milliseconds()
if ms <= 0 {
return 0
}
return int64(binary.BigEndian.Uint64(id[8:]) % uint64(ms))
}
// nextSlot returns the first time after now, in ms, at which a monitor with
// phase and interval, both in ms, runs. dispatchScript computes the same.
func nextSlot(now, phase, interval int64) int64 {
if interval <= 0 {
return now
}
off := (now - phase) % interval
if off < 0 {
off += interval
}
return now - off + interval
}
// Upsert schedules m in its regions and removes it from others it was in.
// A monitor new to a region runs right away; an existing schedule keeps its
// phase so edits do not cause bursts.
// time so edits do not cause bursts.
func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []string) error {
return s.upsert(ctx, m, previousRegions, true)
}
// upsert is Upsert; without runNow, a monitor new to a region first runs on
// its phase instead of right away.
func (s *Scheduler) upsert(ctx context.Context, m Monitor, previousRegions []string, runNow bool) error {
now := s.now().UnixMilli()
id := m.ID.String()
phase := phaseOf(m.ID, m.Interval)
first := now
if !runNow {
first = nextSlot(now, phase, m.Interval.Milliseconds())
}
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HSet(ctx, keyIntervals, id, int64(m.Interval/time.Millisecond))
p.HSet(ctx, keyIntervals, id, m.Interval.Milliseconds())
p.HSet(ctx, keyPhases, id, phase)
p.HSet(ctx, keyTouched, id, now)
keep := map[string]bool{}
for _, r := range m.Regions {
keep[r] = true
p.SAdd(ctx, keyRegions, r)
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(now), Member: id})
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(first), Member: id})
}
for _, r := range previousRegions {
if !keep[r] {
@@ -99,6 +142,7 @@ func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []str
func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string) error {
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HDel(ctx, keyIntervals, id.String())
p.HDel(ctx, keyPhases, id.String())
p.HDel(ctx, keyTouched, id.String())
for _, r := range regions {
p.ZRem(ctx, keyDue(r), id.String())
@@ -112,11 +156,12 @@ func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string)
// from the database at asOf. It repairs drift after a Redis failover or a
// missed update and is safe to run from several replicas. Monitors upserted
// after asOf are kept even if want lacks them: they were created while the
// database was being read.
// database was being read. Monitors it adds back first run on their phase,
// so recovering a lost schedule causes no burst.
func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Time) error {
byRegion := map[string]map[string]bool{}
for _, m := range want {
if err := s.Upsert(ctx, m, nil); err != nil {
if err := s.upsert(ctx, m, nil, false); err != nil {
return err
}
for _, r := range m.Regions {
@@ -139,7 +184,7 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
if wanted[id] {
continue
}
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched}, id, asOfMS).Err(); err != nil {
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
return err
}
}
@@ -156,7 +201,7 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
if byRegion[r][id] {
continue
}
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched}, id, asOfMS).Err(); err != nil {
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
return err
}
}
@@ -168,7 +213,8 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
// upserted at or after asOf. Checking and removing in one step closes the
// window in which a concurrent upsert would be undone.
//
// KEYS: hash or sorted set to prune, touched hash. ARGV: monitor id, asOf ms.
// KEYS: hash or sorted set to prune, touched hash, phase hash.
// ARGV: monitor id, asOf ms.
var pruneScript = redis.NewScript(`
local touched = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '0')
if touched >= tonumber(ARGV[2]) then return 0 end
@@ -177,6 +223,7 @@ if redis.call('TYPE', KEYS[1]).ok == 'zset' then
else
redis.call('HDEL', KEYS[1], ARGV[1])
redis.call('HDEL', KEYS[2], ARGV[1])
redis.call('HDEL', KEYS[3], ARGV[1])
end
return 1
`)
@@ -188,8 +235,14 @@ func (s *Scheduler) Heartbeat(ctx context.Context, region string, instance uuid.
// dispatchScript runs per region.
//
// KEYS: due set, instance set, interval hash.
// KEYS: due set, instance set, interval hash, phase hash.
// ARGV: now ms, stale-before ms, batch limit, job queue prefix, queue TTL s.
//
// The next run is the monitor's first phase slot after now. A run off its
// slot, like the first one, skips a slot less than half an interval away,
// so the monitor does not run twice in quick succession. Monitors without
// a phase, scheduled before phases existed, run every interval from their
// last due time until reconciliation adds one.
var dispatchScript = redis.NewScript(`
local now = tonumber(ARGV[1])
for _, inst in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', ARGV[2])) do
@@ -216,8 +269,17 @@ for i = 1, #due, 2 do
local q = ARGV[4] .. live[math.random(#live)]
redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at))
redis.call('EXPIRE', q, ARGV[5])
local nxt = at + interval
if nxt <= now then nxt = now + interval end
local nxt
local phase = tonumber(redis.call('HGET', KEYS[4], m) or '')
if phase == nil then
nxt = at + interval
if nxt <= now then nxt = now + interval end
else
nxt = now - ((now - phase) % interval) + interval
if (at - phase) % interval ~= 0 and nxt - now < interval / 2 then
nxt = nxt + interval
end
end
redis.call('ZADD', KEYS[1], nxt, m)
n = n + 1
end
@@ -236,7 +298,7 @@ func (s *Scheduler) Dispatch(ctx context.Context) (int, error) {
total := 0
for _, r := range regions {
n, err := dispatchScript.Run(ctx, s.rdb,
[]string{keyDue(r), keyInstances(r), keyIntervals},
[]string{keyDue(r), keyInstances(r), keyIntervals, keyPhases},
now.UnixMilli(), now.Add(-StaleAfter).UnixMilli(), 1000, jobsPrefix, int(jobsTTL.Seconds()),
).Int()
if err != nil {
+146 -2
View File
@@ -100,11 +100,20 @@ func TestDispatchReschedulesAndKeepsRegionsApart(t *testing.T) {
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() before next interval = %d, want 0", n)
}
*now = now.Add(30 * time.Second)
// The next run is on the monitor's phase, at least half an interval
// after the first one.
next := dueAt(t, s, "eu", m.ID)
if off := (next.UnixMilli() - phaseOf(m.ID, m.Interval)) % m.Interval.Milliseconds(); off != 0 {
t.Errorf("next run %v is %dms off its phase", next, off)
}
if gap := next.Sub(*now); gap < m.Interval/2 || gap > 3*m.Interval/2 {
t.Errorf("next run %v after the first, want between half and one and a half intervals", gap)
}
*now = next
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
if n := mustDispatch(t, s); n != 2 {
t.Errorf("Dispatch() after interval = %d, want 2", n)
t.Errorf("Dispatch() on the next slot = %d, want 2", n)
}
// Leaving a region stops runs there.
@@ -177,6 +186,9 @@ func TestRemoveAndReconcile(t *testing.T) {
if len(got) != 1 || got[0].MonitorID != keep.ID {
t.Errorf("jobs after Reconcile = %+v, want only %v", got, keep.ID)
}
if s.rdb.HExists(ctx, keyPhases, gone.ID.String()).Val() {
t.Error("Reconcile left the phase of a removed monitor")
}
}
func TestTakeWaits(t *testing.T) {
@@ -277,3 +289,135 @@ func TestOverdueCountsRunsLeftBehind(t *testing.T) {
t.Errorf("Overdue() after the instance took the runs = %d, want 0", n)
}
}
func dueAt(t *testing.T, s *Scheduler, region string, id uuid.UUID) time.Time {
t.Helper()
score, err := s.rdb.ZScore(context.Background(), keyDue(region), id.String()).Result()
if err != nil {
t.Fatalf("no due time for %v in %s: %v", id, region, err)
}
return time.UnixMilli(int64(score))
}
// TestPhaseSpreadsBurst creates many monitors at once. Their first runs are
// right away; after that they spread over the interval instead of all
// running in the same second again.
func TestPhaseSpreadsBurst(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
const monitors = 600
for range monitors {
if err := s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil); err != nil {
t.Fatal(err)
}
}
perSecond := make([]int, 180)
for sec := range perSecond {
_ = s.Heartbeat(ctx, "eu", in)
perSecond[sec] = mustDispatch(t, s)
takeAll(t, s, in)
*now = now.Add(time.Second)
}
if perSecond[0] != monitors {
t.Errorf("first second dispatched %d, want all %d first runs", perSecond[0], monitors)
}
total, peak := 0, 0
for _, n := range perSecond[60:] {
total += n
peak = max(peak, n)
}
if total != 2*monitors {
t.Errorf("seconds 60 to 180 dispatched %d runs, want %d: one per monitor and minute", total, 2*monitors)
}
// 10 per second on average; all 600 at once without phases.
if peak > 30 {
t.Errorf("busiest second dispatched %d runs, want them spread at about 10 per second", peak)
}
}
// TestLateRunSnapsToPhase dispatches runs long overdue. Each comes back on
// its own phase instead of all gathering at the dispatch time.
func TestLateRunSnapsToPhase(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
ms := []Monitor{}
for range 50 {
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
ms = append(ms, m)
_ = s.Upsert(ctx, m, nil)
}
_ = s.Heartbeat(ctx, "eu", in)
mustDispatch(t, s)
// No instance for three intervals.
*now = now.Add(3*time.Minute + 7*time.Second)
_ = s.Heartbeat(ctx, "eu", in)
if n := mustDispatch(t, s); n != len(ms) {
t.Fatalf("Dispatch() of the overdue runs = %d, want %d", n, len(ms))
}
distinct := map[time.Time]bool{}
for _, m := range ms {
got := dueAt(t, s, "eu", m.ID)
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
if !got.Equal(want) {
t.Errorf("monitor next due %v, want its next slot %v", got, want)
}
distinct[got] = true
}
if len(distinct) < len(ms)-5 {
t.Errorf("%d monitors share %d due times, want them apart", len(ms), len(distinct))
}
}
// TestReconcileAddsOnPhase rebuilds a lost schedule without a burst.
func TestReconcileAddsOnPhase(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
ms := []Monitor{}
for range 20 {
ms = append(ms, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}})
}
if err := s.Reconcile(ctx, ms, *now); err != nil {
t.Fatal(err)
}
for _, m := range ms {
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
if got := dueAt(t, s, "eu", m.ID); !got.Equal(want) {
t.Errorf("reconciled monitor due %v, want its slot %v", got, want)
}
}
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() right after Reconcile = %d, want 0", n)
}
}
// TestPhaseFallback covers monitors scheduled before phases existed.
func TestPhaseFallback(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
s.rdb.HDel(ctx, keyPhases, m.ID.String())
mustDispatch(t, s)
if got, want := dueAt(t, s, "eu", m.ID), now.Add(time.Minute); !got.Equal(want) {
t.Errorf("monitor without phase next due %v, want one interval later, %v", got, want)
}
}
func TestNextSlot(t *testing.T) {
for _, c := range []struct{ now, phase, interval, want int64 }{
{now: 100, phase: 30, interval: 60, want: 150},
{now: 150, phase: 30, interval: 60, want: 210},
{now: 10, phase: 30, interval: 60, want: 30},
{now: 100, phase: 0, interval: 0, want: 100},
} {
if got := nextSlot(c.now, c.phase, c.interval); got != c.want {
t.Errorf("nextSlot(%d, %d, %d) = %d, want %d", c.now, c.phase, c.interval, got, c.want)
}
}
}