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
This commit is contained in:
1 parent
6d4842f4a3
commit
050c9dd0a1
2 files changed
+220
-14
No files matched your search
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user