Files
uptimesebi/internal/schedule/schedule.go
T
Sebastian UnterschützandClaude Opus 5.5 94c529a97e
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m48s
ci / test (pull_request) Successful in 13m35s
ci / build (pull_request) Successful in 10m22s
ci / image (pull_request) Successful in 3m35s
fix(schedule): drop runs left queued for too long; shorter result claims
A checker that fell behind kept working off runs from minutes ago while
dispatch queued newer runs of the same monitors behind them, so a backlog
never shrank: pawhost and realtoxmedia stayed at about 50K overdue checks.
Queued runs now record when they were dispatched, and Take drops runs
that waited longer than two intervals. A newer run of the monitor has
been queued by then, since the next run is due at most one and a half
intervals after a dispatch. uptimesebi_checks_stale_total counts them.

Result claims, one Redis key per check result, lived 2 hours although
retries come within minutes. At about 530 results a second that was
4.5 million keys and 1.1 GiB of the shared Redis. They now live 10
minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 19:41:54 +01:00

502 lines
16 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
// DispatchedAt is when the run was queued; zero for runs queued before
// dispatch times were recorded.
DispatchedAt 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) .. '|' .. string.format('%.0f', now))
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
}
// staleAfter is how many intervals a queued run may wait before Take drops
// it. By then a newer run of the monitor has been dispatched, since the next
// run is due at most one and a half intervals after the last dispatch, so
// a checker that fell behind catches up instead of working off runs that
// are out of date.
const staleAfter = 2
// 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. Runs queued for longer than
// staleAfter intervals are dropped; Take returns how many.
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, int, error) {
if max <= 0 {
return nil, 0, nil
}
q := jobsPrefix + instance.String()
deadline := time.Now().Add(wait)
stale := 0
for ctx.Err() == nil {
raw, err := s.rdb.LPopCount(ctx, q, max).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return nil, stale, err
}
if len(raw) == 0 {
left := time.Until(deadline)
if left <= 0 {
return nil, stale, 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, stale, 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, stale, err
}
raw = append(raw, more...)
}
}
out, n, err := s.fresh(ctx, raw)
if err != nil {
return nil, stale, err
}
stale += n
if len(out) > 0 {
return out, stale, nil
}
}
return nil, stale, nil
}
// fresh parses popped runs and drops those queued for longer than
// staleAfter intervals. It returns the rest and how many it dropped.
func (s *Scheduler) fresh(ctx context.Context, raw []string) ([]Entry, int, error) {
entries := make([]Entry, 0, len(raw))
var ids []string
for _, r := range raw {
if e, ok := parseEntry(r); ok {
entries = append(entries, e)
if !e.DispatchedAt.IsZero() {
ids = append(ids, e.MonitorID.String())
}
}
}
if len(ids) == 0 {
return entries, 0, nil
}
vals, err := s.rdb.HMGet(ctx, keyIntervals, ids...).Result()
if err != nil {
return nil, 0, err
}
interval := make(map[uuid.UUID]time.Duration, len(ids))
for i, v := range vals {
str, _ := v.(string)
if ms, err := strconv.ParseInt(str, 10, 64); err == nil {
interval[uuid.MustParse(ids[i])] = time.Duration(ms) * time.Millisecond
}
}
now := s.now()
out := entries[:0]
for _, e := range entries {
// Removed monitors are left to the caller, which drops them.
if iv, ok := interval[e.MonitorID]; ok && !e.DispatchedAt.IsZero() && now.Sub(e.DispatchedAt) > staleAfter*iv {
continue
}
out = append(out, e)
}
return out, len(entries) - len(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.match(job, '^[^|]*|([^|]*)'))
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()
}
// parseEntry parses a queued run: "monitor|scheduled ms|dispatched ms",
// or without the dispatch time as queued by older releases.
func parseEntry(s string) (Entry, bool) {
parts := strings.Split(s, "|")
if len(parts) < 2 || len(parts) > 3 {
return Entry{}, false
}
mid, err := uuid.Parse(parts[0])
if err != nil {
return Entry{}, false
}
ms, err := strconv.ParseFloat(parts[1], 64)
if err != nil {
return Entry{}, false
}
e := Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}
if len(parts) == 3 {
d, err := strconv.ParseFloat(parts[2], 64)
if err != nil {
return Entry{}, false
}
e.DispatchedAt = time.UnixMilli(int64(d))
}
return e, true
}