Files
uptimesebi/internal/schedule/schedule.go
T
Sebastian UnterschützandClaude Opus 5.5 050c9dd0a1
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
feat(schedule): spread monitor runs evenly over their interval
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

437 lines
14 KiB
Go

// Package schedule distributes due checks to checker instances.
//
// It runs inside the API, which is the only component with Redis access.
// Per region, a sorted set holds each monitor's next due time. Dispatch
// moves due monitors into the queue of a randomly chosen live instance of
// that region and schedules their next run in the same atomic step, so any
// 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"
"strings"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
// StaleAfter is how long an instance may stay silent before its queued jobs
// are given to others. Instances poll at least every PollInterval.
const (
PollInterval = 20 * time.Second
StaleAfter = 45 * time.Second
)
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"
jobsPrefix = "sched:jobs:"
// jobsTTL drops queues of instances that vanished together with every
// API replica that could have recovered them.
jobsTTL = 10 * time.Minute
)
func keyDue(region string) string { return "sched:due:" + region }
func keyInstances(region string) string { return "sched:instances:" + region }
// Scheduler is safe for concurrent use.
type Scheduler struct {
rdb redis.UniversalClient
now func() time.Time
}
// New returns a Scheduler on rdb.
func New(rdb redis.UniversalClient) *Scheduler {
return &Scheduler{rdb: rdb, now: time.Now}
}
// Entry is one dispatched run.
type Entry struct {
MonitorID uuid.UUID
ScheduledAt time.Time
}
// Monitor is the schedule-relevant part of a monitor.
type Monitor struct {
ID uuid.UUID
Interval time.Duration
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
// 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, 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(first), Member: id})
}
for _, r := range previousRegions {
if !keep[r] {
p.ZRem(ctx, keyDue(r), id)
}
}
return nil
})
return err
}
// Remove unschedules a monitor from regions. Runs already queued for an
// instance are dropped at dispatch or job resolution.
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())
}
return nil
})
return err
}
// Reconcile makes Redis match want, the full set of enabled monitors as read
// 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. 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, false); err != nil {
return err
}
for _, r := range m.Regions {
if byRegion[r] == nil {
byRegion[r] = map[string]bool{}
}
byRegion[r][m.ID.String()] = true
}
}
wanted := map[string]bool{}
for _, m := range want {
wanted[m.ID.String()] = true
}
asOfMS := asOf.UnixMilli()
ids, err := s.rdb.HKeys(ctx, keyIntervals).Result()
if err != nil {
return err
}
for _, id := range ids {
if wanted[id] {
continue
}
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
return err
}
}
regions, err := s.rdb.SMembers(ctx, keyRegions).Result()
if err != nil {
return err
}
for _, r := range regions {
members, err := s.rdb.ZRange(ctx, keyDue(r), 0, -1).Result()
if err != nil {
return err
}
for _, id := range members {
if byRegion[r][id] {
continue
}
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
return err
}
}
}
return nil
}
// pruneScript removes a monitor from a hash or sorted set unless it was
// 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, 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
if redis.call('TYPE', KEYS[1]).ok == 'zset' then
redis.call('ZREM', KEYS[1], ARGV[1])
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
`)
// Heartbeat records that instance of region is alive.
func (s *Scheduler) Heartbeat(ctx context.Context, region string, instance uuid.UUID) error {
return s.rdb.ZAdd(ctx, keyInstances(region), redis.Z{Score: float64(s.now().UnixMilli()), Member: instance.String()}).Err()
}
// dispatchScript runs per region.
//
// 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
local q = ARGV[4] .. inst
for _, job in ipairs(redis.call('LRANGE', q, 0, -1)) do
local m = string.sub(job, 1, string.find(job, '|', 1, true) - 1)
if redis.call('HEXISTS', KEYS[3], m) == 1 then
redis.call('ZADD', KEYS[1], 'LT', now, m)
end
end
redis.call('DEL', q)
redis.call('ZREM', KEYS[2], inst)
end
local live = redis.call('ZRANGE', KEYS[2], 0, -1)
if #live == 0 then return 0 end
local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now, 'WITHSCORES', 'LIMIT', 0, ARGV[3])
local n = 0
for i = 1, #due, 2 do
local m, at = due[i], tonumber(due[i + 1])
local interval = tonumber(redis.call('HGET', KEYS[3], m))
if interval == nil then
redis.call('ZREM', KEYS[1], m)
else
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
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
end
return n
`)
// Dispatch hands due runs of every region to random live instances and
// returns how many it dispatched.
func (s *Scheduler) Dispatch(ctx context.Context) (int, error) {
regions, err := s.rdb.SMembers(ctx, keyRegions).Result()
if err != nil {
return 0, err
}
now := s.now()
total := 0
for _, r := range regions {
n, err := dispatchScript.Run(ctx, s.rdb,
[]string{keyDue(r), keyInstances(r), keyIntervals, keyPhases},
now.UnixMilli(), now.Add(-StaleAfter).UnixMilli(), 1000, jobsPrefix, int(jobsTTL.Seconds()),
).Int()
if err != nil {
return total, fmt.Errorf("schedule: dispatch %s: %w", r, err)
}
total += n
}
return total, nil
}
// QueueLen returns how many runs wait for instance.
func (s *Scheduler) QueueLen(ctx context.Context, instance uuid.UUID) (int64, error) {
return s.rdb.LLen(ctx, jobsPrefix+instance.String()).Result()
}
// LastSeen returns when instance last polled in region, or zero if it is
// not registered.
func (s *Scheduler) LastSeen(ctx context.Context, region string, instance uuid.UUID) (time.Time, error) {
score, err := s.rdb.ZScore(ctx, keyInstances(region), instance.String()).Result()
if errors.Is(err, redis.Nil) || score == 0 {
return time.Time{}, nil
}
return time.UnixMilli(int64(score)), err
}
// Take pops up to max queued runs for instance, waiting up to wait for the
// first one. It returns within about a second once ctx is done, so long polls
// do not hold up shutdown or cancelled requests.
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, error) {
if max <= 0 {
return nil, nil
}
q := jobsPrefix + instance.String()
raw, err := s.rdb.LPopCount(ctx, q, max).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return nil, err
}
deadline := time.Now().Add(wait)
for len(raw) == 0 && ctx.Err() == nil {
left := time.Until(deadline)
if left <= 0 {
return nil, nil
}
// BLPOP blocks server side and ignores ctx, so wait in slices.
first, err := s.blpop(ctx, min(left, time.Second), q)
if errors.Is(err, redis.Nil) {
continue
}
if err != nil {
return nil, err
}
raw = []string{first[1]}
if max > 1 {
more, err := s.rdb.LPopCount(ctx, q, max-1).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return nil, err
}
raw = append(raw, more...)
}
}
out := make([]Entry, 0, len(raw))
for _, r := range raw {
if e, ok := parseEntry(r); ok {
out = append(out, e)
}
}
return out, nil
}
// blpop is BLPOP with a timeout below a second, which go-redis would round
// up to one (Redis takes fractions of seconds since 6.0).
func (s *Scheduler) blpop(ctx context.Context, timeout time.Duration, key string) ([]string, error) {
if timeout >= time.Second {
return s.rdb.BLPop(ctx, timeout, key).Result()
}
return s.rdb.Do(ctx, "BLPOP", key, strconv.FormatFloat(timeout.Seconds(), 'f', 3, 64)).StringSlice()
}
// Release returns instance's queued runs to its region and forgets it.
func (s *Scheduler) Release(ctx context.Context, region string, instance uuid.UUID) error {
// Marking the instance stale lets the dispatch script do the handover,
// which keeps that logic in one place.
if err := s.rdb.ZAdd(ctx, keyInstances(region), redis.Z{Score: 0, Member: instance.String()}).Err(); err != nil {
return err
}
_, err := s.Dispatch(ctx)
return err
}
// Instances returns the live instance count per region.
func (s *Scheduler) Instances(ctx context.Context, region string) (int64, error) {
min := strconv.FormatInt(s.now().Add(-StaleAfter).UnixMilli(), 10)
return s.rdb.ZCount(ctx, keyInstances(region), min, "+inf").Result()
}
// overdueScript counts the runs of a region due before a cutoff: those not
// dispatched yet and those waiting in an instance's queue.
//
// KEYS: due set, instance set.
// ARGV: cutoff ms, job queue prefix.
var overdueScript = redis.NewScript(`
local cutoff = tonumber(ARGV[1])
local n = redis.call('ZCOUNT', KEYS[1], '-inf', cutoff)
for _, inst in ipairs(redis.call('ZRANGE', KEYS[2], 0, -1)) do
for _, job in ipairs(redis.call('LRANGE', ARGV[2] .. inst, 0, -1)) do
local at = tonumber(string.sub(job, string.find(job, '|', 1, true) + 1))
if at ~= nil and at <= cutoff then n = n + 1 end
end
end
return n
`)
// Overdue returns how many runs of region were due more than late ago and
// have not started: runs not dispatched, as when the region has no live
// instance, and runs left in the queue of an instance too busy to take them.
func (s *Scheduler) Overdue(ctx context.Context, region string, late time.Duration) (int64, error) {
return overdueScript.Run(ctx, s.rdb, []string{keyDue(region), keyInstances(region)},
s.now().Add(-late).UnixMilli(), jobsPrefix).Int64()
}
func parseEntry(s string) (Entry, bool) {
id, at, ok := strings.Cut(s, "|")
if !ok {
return Entry{}, false
}
mid, err := uuid.Parse(id)
if err != nil {
return Entry{}, false
}
ms, err := strconv.ParseFloat(at, 64)
if err != nil {
return Entry{}, false
}
return Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}, true
}