hourglass

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

hourglass

Delayed jobs and cron for Go: SQLite embedded, sharded MySQL/TiDB + etcd cluster — same engine, same API.

h, _ := hourglass.Open("sqlite://./hourglass.db")
defer h.Close()

h.Register("email:welcome", handler)
h.Submit(ctx, "email:welcome", payload, hourglass.Delay(24*time.Hour))
h.Every(ctx, "report:daily", "0 9 * * *")   // cron, registered handler
h.Cancel(ctx, id, "user asked")             // wins until the fire moment

go h.Run(ctx)                               // 1s ticks: admit -> wheel -> fire

CLI reads the same store: hourglass stats, hourglass dlq ls, hourglass dlq replay.

Design

Precision is not a polling interval. The database holds the long horizon — a job due in two days is a quiet row. The wheel holds the precision — a lookahead window admitted in CAS batches, fired from memory at the second, zero DB reads between admission windows.

Fire path:

flowchart TD
    S["Submit"] -->|"INSERT waiting"| R[("job row<br/>state · due · shard · epoch")]
    R -->|"due enters lookahead"| AL["admission loop<br/>scan + CAS batch"]
    AL -->|"waiting → acquired<br/>epoch stamped"| W["hierarchical wheel<br/>fires at the second"]
    W -->|"due reached"| WP["worker pool<br/>gRPC executor"]
    WP -->|"complete / dead / retry"| RT[("receipts + dead letters<br/>queryable rows")]
    R -.->|"cancel wins<br/>until fire moment"| RT
    RT -.->|"quiescence watermark:<br/>quiet store = zero scans"| AL

Job states (terminal rows persist as receipts until retention):

stateDiagram-v2
    [*] --> waiting: submit
    waiting --> acquired: CAS admission (epoch)
    acquired --> fired: wheel fires
    fired --> completed: handler ok
    fired --> dead: retries exhausted
    fired --> waiting: retry backoff / reschedule_at
    waiting --> canceled: cancel
    acquired --> canceled: cancel until fire moment
    acquired --> waiting: overflow · recovery · reclaim
    completed --> waiting: cron next occurrence
    dead --> waiting: dlq replay

Cluster — ownership, not a leader:

flowchart TB
    ETCD["etcd<br/>shard leases + epoch generations"]
    DB[("MySQL / TiDB<br/>jobs + receipts, partitioned")]
    NA["node-a<br/>engines: shards 0–31"]
    NB["node-b<br/>engines: shards 32–255"]
    NC["node-c<br/>joins → claims free shards"]

    NA -.->|"claim · keepalive · epoch bump"| ETCD
    ETCD -.->|"watch: ownership loss"| NB
    NC -.->|"claim"| ETCD
    NA --> DB
    NB --> DB
    NC --> DB

Shards are logical and over-allocated, mapped onto partitions by a directory — adding a node claims free shards, no data moves. Handoff is graceful (drain the wheel, release) or lease-expiry (new owner bumps the epoch, reclaims acquired rows, rescans the misfire horizon).

Contracts

  • Fire at the appointed second, never early, never skipped. Memory is a cache; the database is the owner.
  • No orphans: a crashed node's in-flight jobs are reclaimed by lease expiry and re-fired within the misfire horizon.
  • Cancel wins until the fire moment; epoch fencing stops a zombie node's late shots.
  • Every fire is a receipt — "did this side effect happen?" is a SELECT.

Hard parts

Mechanism Code Proven by
Epoch fencing: a zombie node cannot fire after handoff wheel.go SetEpoch, engine.go epoch check on CAS + fire path TestWheelEpochFencingBlocksZombie, TestEpochFencingEndToEnd, TestTwoNodeShardFailoverEndToEnd
Cancel is mark-don't-remove: no removal race with the tick wheel.go Cancel + tick skip TestWheelCancelIsMarkNotRemove, TestCancelDuringPumpReReadWindow
Misfire horizon: the wheel is lossy by design; rescan covers it engine.go misfireHalo window floor TestOpenRecoversInFlightRows
Wheel overflow releases surplus to waiting (backpressure, not OOM) engine.go admit capacity + release TestWheelRejectsWhenFull, TestWheelOverflowReleaseEndToEnd
Batched fire-path writes: one statement per tick per target state engine.go pump (~32K id cap for MySQL packets) TestBenchmarkHotMinute
Never early, never skipped wheel.go tick semantics TestWheelNeverFiresEarly, TestWheelFiresAtAppointedSecond
Ownership loss is a watch event, not a discovery poll registry.go claim/lease/watch TestRegistryLeaseExpiryFreesShard, TestRegistryWatchDeliversOwnershipLoss
Graceful handoff drains one per-shard wheel join.go TestJoinClaimsShardsAndFiresJobs, TestGracefulHandoffMovesShardWithoutLoss

Decisions

Only the choices whose alternative a competent engineer would defend:

Decision Rejected
DB keeps the long horizon; the wheel keeps the precision shorter polling — precision bought with permanent DB load over all pending jobs
The wheel is the core; a broker is a post-1.0 delivery sink broker-first — uncancellable after publish, delayed index on the broker's heap, three systems before the first job fires
Fencing authority is etcd epochs DB-row fencing (Temporal's shape) — couples ownership to every store dialect; etcd leases deliver loss as a watch event
Cancel of an admitted-but-unfired job is mark-don't-remove remove-under-lock — races the tick, and a slow cancel stalls the fire path
fired_record rows are the durable queue; memory is a cache in-memory push with retry — a slow executor stalls the wheel; a crash between fire and delivery orphans the job
Admission is capacity-bounded; overflow releases back to waiting unbounded wheel — the lookahead is a memory budget; without release it is an OOM, not backpressure

Measured

Gated tests (-run TestBenchmark, fake clock) — regressions fail CI:

benchmark hourglass poll-based baseline
fire precision p50 / p99 / max (5,000 jobs / 10 min) 0 / 0 / 1000 ms (1s tick) 2,000 / 4,000 / 5,000 ms (5s poll)
quiescent reads, 10 min idle, 100K pending 2 (watermark) 121 (one scan per interval, forever)
hot minute: 100K jobs due the same second 11.1s drain, 0.02 write stmts/job, zero loss unbatched path: 4+ writes/job

Cluster load, real MySQL 8.4 + etcd 3.5.17, one laptop (cmd/hourglass-bench):

jobs shards submit/s fires/s loss
20,000 16 3,051 3,805 0
50,000 8 3,242 5,877 0
50,000 32 3,699 5,553 0
100,000 32 4,061 6,346 0

Failover (hard kill, 2,000 in-flight jobs, 3 runs): takeover 2.57–3.58s (LeaseTTL-bound), 2,000/2,000 re-fired by the new owner, zero loss, zero duplication.

Latency and drain curve from a measured run (HDR, per-job source-anchored — no coordinated omission from the measuring side):

fires per second, drain curve

Defects caught by the bench suite, none visible to unit tests:

  1. Hot minute stalled silently: batched id-list statements exceeded SQLite's ~8K placeholder cap → chunk at 500 per round-trip.
  2. Reclaim was age-only: takeover right after a crash reclaimed nothing → epoch < newEpoch OR aged lease.
  3. Engines spawned after Register started handlerless: reclaimed jobs dead-lettered 2,000/2,000 → engines inherit the registry.
  4. KillForTest killed only the lease, simulating a zombie that happened to be correct → hard kill without drain, which exposed (2) and (3) in minutes.

The ~6.3K fires/s is a single-process ceiling at default knobs; the 200K/s ancestor ran broker delivery, not per-fire SQL receipts — not comparable.

# engine benchmarks, anywhere (SQLite):
go test -run '^$' -bench 'Benchmark(Submit|FirePath)' -count 10 > old.txt
benchstat old.txt new.txt

# cluster scenarios (real MySQL + etcd):
hourglass-bench -s cluster-throughput -n 20000 -shards 16
benchplot -mode percentile -o latency.svg bench-results/*.json

Limits

  • The "standalone durable time layer" category is unproven; this is a reference implementation, not a category founder. Scope frozen at v1.0.
  • Takeover is LeaseTTL-bound: 2.57–3.58s at TTL=3s, 15–20s at 15s. No loss — but every ownership change is a latency window.
  • All numbers single-host, laptop-grade.
  • 256 logical shards, fixed; rebalance is manual.

Compared

asynq river xxl-job Temporal hourglass
truth Redis zset PG rows SQL + logs sharded history SQL rows + receipts
precision 5s forwarder ~1s (leader scheduler + fetch) dispatch loop timer gate at the timestamp (wake = workflow callback through 3 hops) time wheel (0ms p50 @ 1s tick)
scheduling plane every server (redundant forwarders) elected leader central dispatcher (SPOF) shard owners shard owners
scale-out execution only execution only dispatcher-bound shards (fixed at boot) shards (movable, no data moves)
cron durability scheduler memory leader memory — may skip on election (durable = Pro) DB rows event history job row (completed → waiting)
cancel until claimed while running (cooperative) manual workflow-level until fire moment (epoch-fenced)
dependency Redis PostgreSQL DB + central 4 services + DB the SQL you run

river is the interesting neighbor: same truth model, the difference is entirely the scheduling plane — elected leader vs admission loop per shard owner. Temporal runs the same shard-owner + fencing-generation model (RangeID ≈ epoch, verified in source) with a workflow engine on top; a durable timer shouldn't need one. Compose when you need replay.

Not goals

Workflow/DAG orchestration · exactly-once delivery · step replay or a durable-execution journal · natural-language time parsing · calling models, ever · a required broker · multi-tenancy before the core is proven.

Status

v1.0 complete, frozen: embedded engine, cluster (MySQL/TiDB + etcd), gRPC executor. CI: lint, race, real-infra integration, benchmark gates. Clean-room rebuild from a production system that peaked above 200K execution commands per second — write-up.

License

MIT

Documentation

Overview

Package hourglass provides delayed jobs and cron for Go: durable truth in SQL, second-level fire precision from an in-process hierarchical time wheel. See README ("How it works") for the timing contract.

Index

Constants

View Source
const DefaultShards = 256

DefaultShards is the fixed logical shard count (Redis Cluster precedent: fixed slot count written into the schema; scaling moves ownership, never recomputes placement).

Variables

View Source
var (
	ErrEmptyTopic = errors.New("hourglass: empty topic")
	ErrMissingDue = errors.New("hourglass: no due time (use At or Delay)")
)

ErrEmptyTopic and ErrMissingDue are submit-time contract violations.

View Source
var ErrWheelFull = errors.New("hourglass: wheel at capacity")

ErrWheelFull is returned by Offer when the wheel is at capacity; the admission loop must release the surplus back to waiting.

Functions

func RegisterExecutorServer

func RegisterExecutorServer(srv *grpc.Server, es *executorServer)

RegisterExecutorServer registers the executor service on a gRPC server.

func ShardFor

func ShardFor(id string) int

ShardFor computes the shard key for a job id (fnv-1a % DefaultShards).

Types

type Clock

type Clock interface {
	Now() time.Time
}

Clock is the time seam; tests inject a deterministic clock.

type Cluster

type Cluster struct {
	// contains filtered or unexported fields
}

Cluster drives one engine per owned shard over one store. This is the scheduling-plane scale-out unit of cluster mode: adding a process adds shard ownership, and each shard's admission loop and wheel run independently (share-nothing between shards).

Ownership (which process holds which shards) is the registry's job (etcd leases + epoch fencing — README, "How it works"); Cluster is the per-process executor of whatever ownership it is handed.

func (*Cluster) Close

func (c *Cluster) Close() error

Close stops every shard engine (drains dispatch, waits for handlers).

func (*Cluster) DropShard

func (c *Cluster) DropShard(sh ScanUnit) error

DropShard stops one shard's engine (graceful handoff step 1: the registry revokes ownership, the old owner drains).

func (*Cluster) KillForTest

func (c *Cluster) KillForTest()

KillForTest stops every engine WITHOUT draining: unfired wheel entries are abandoned in the acquired state for the next owner to reclaim (hard-kill semantics; the process is gone, the rows remain).

func (*Cluster) Register

func (c *Cluster) Register(topic string, h Handler)

Register binds a handler on every shard engine, including engines added later (AddShard after Register inherits the registry — the failover bench caught reclaimed jobs firing into empty handlers).

func (*Cluster) Run

func (c *Cluster) Run(ctx context.Context)

Run drives all shards on a one-second cadence until ctx is done.

type Config

type Config struct {
	MySQL    string        // mysql dsn, e.g. "user:pass@tcp(host:3306)/hourglass"
	Etcd     []string      // etcd endpoints
	Shards   []int         // shards this node will try to own (claim races decide)
	LeaseTTL time.Duration // etcd lease ttl (default 15s)
	Engine   engineConfig  // optional engine tuning (zero values take defaults)
}

Config configures a cluster node.

type ExecAck

type ExecAck struct {
	Ok           bool
	Err          string
	RescheduleAt int64
}

ExecAck answers one request. RescheduleAt (unix seconds, 0 = none) requeues the job — self-chaining reserved from day one.

type ExecRequest

type ExecRequest struct {
	FiredId string // receipt id: the ack identity (lesson #4)
	JobId   string
	Topic   string
	Payload []byte
	Attempt int
}

ExecRequest is one execution command pushed to a remote executor.

type ExecutorClient

type ExecutorClient struct {
	// contains filtered or unexported fields
}

ExecutorClient is the client side of the exec face.

func NewExecutorClient

func NewExecutorClient(cc *grpc.ClientConn) *ExecutorClient

NewExecutorClient builds an exec client on a live connection.

func (*ExecutorClient) Exec

func (c *ExecutorClient) Exec(ctx context.Context, req *ExecRequest) (*ExecAck, error)

Exec pushes one command.

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

Handle is an hourglass engine bound to one store.

func Open

func Open(dsn string) (*Handle, error)

Open connects to a store named by dsn, e.g. "sqlite:///path/to/db".

func OpenWithClock

func OpenWithClock(dsn string, clk Clock) (*Handle, error)

OpenWithClock is Open with an injected clock (deterministic tests, simulated time).

func (*Handle) Cancel

func (h *Handle) Cancel(ctx context.Context, id, reason string) error

Cancel revokes a job before its fire moment; the row persists as a receipt. Cancel after fire is rejected.

func (*Handle) Close

func (h *Handle) Close() error

Close stops the engine (workers, wheel, in-flight flushes) and releases the store.

func (*Handle) Eng

func (h *Handle) Eng() *engine

Eng exposes the internal engine for package tests (CLI integration drives admission deterministically). Not part of the stable API.

func (*Handle) Every

func (h *Handle) Every(ctx context.Context, topic, spec string) (string, error)

Every schedules a recurring job from a standard 5-field cron expression; the same job row reschedules after each completion.

func (*Handle) Get

func (h *Handle) Get(ctx context.Context, id string) (*Job, error)

Get fetches one job by id.

func (*Handle) ListDead

func (h *Handle) ListDead(ctx context.Context, topic string, limit int) ([]Job, error)

ListDead lists dead-lettered jobs, newest first, optionally filtered by topic, for `hourglass dlq ls`.

func (*Handle) Ping

func (h *Handle) Ping(ctx context.Context) error

Ping verifies the store is reachable and migrated.

func (*Handle) Register

func (h *Handle) Register(topic string, fn Handler)

Register binds a handler to a topic.

func (*Handle) ReplayAllDead

func (h *Handle) ReplayAllDead(ctx context.Context) (int, error)

ReplayAllDead requeues every dead job; returns the count.

func (*Handle) ReplayDead

func (h *Handle) ReplayDead(ctx context.Context, id string) error

ReplayDead requeues one dead job: dead -> waiting, attempts reset, due = now. The engine's next admission picks it up.

func (*Handle) Run

func (h *Handle) Run(ctx context.Context)

Run drives the engine until ctx is done: admission steps on a one- second cadence, wheel ticks between them. Blocks; run it in a goroutine.

func (*Handle) Stats

func (h *Handle) Stats(ctx context.Context) (*Stats, error)

Stats summarizes the store: job counts by state, receipt total, and how long the oldest terminal row has been kept (retention pressure).

func (*Handle) Submit

func (h *Handle) Submit(ctx context.Context, topic string, payload []byte, opts ...SubmitOption) (string, error)

Submit persists a job and returns its id.

type Handler

type Handler func(ctx context.Context, j Job) error

Handler runs one job's business logic. Handlers must be idempotent: delivery is at-least-once.

type Job

type Job struct {
	ID      string
	Topic   string
	Payload []byte
	Due     time.Time
	State   State
	Cron    string // non-empty: recurring; reschedules on completion
	// ScheduledAt is the pre-jitter time; Due is what the wheel obeys.
	ScheduledAt time.Time

	Attempts    int           // fires so far (including the current one)
	MaxAttempts int           // 1 = no retries; exhausted -> dead
	Backoff     time.Duration // delay before the next attempt

	Shard int // shard key (hash placement, computed once at submit)

	// CreatedAt is the submit time (persisted; used by stores).
	CreatedAt time.Time

	CancelReason string // set when State == canceled
}

Job is one durable delayed job.

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node is one process's membership in the scheduling fleet: the store, the shard registry, and one engine per owned shard. Adding a process adds shard ownership — that is the scale story.

func Join

func Join(cfg Config) (*Node, error)

Join connects to MySQL and etcd, claims the configured shards (races decide ownership; unclaimed shards here are simply owned by peers), and returns a ready node. Call Run to drive scheduling.

func (*Node) AddShard

func (n *Node) AddShard(ctx context.Context, shard int) error

AddShard claims one shard and starts its engine if the claim wins. A lost claim is not an error (a peer owns it).

func (*Node) Cancel

func (n *Node) Cancel(ctx context.Context, id, reason string) error

Cancel revokes a job before fire (any node).

func (*Node) Close

func (n *Node) Close() error

Close hands nothing over (use Handover per shard for graceful exit) and releases everything.

func (*Node) EnginesForTest

func (n *Node) EnginesForTest() map[string]struct{}

EnginesForTest exposes owned shard engines (bench tooling).

func (*Node) Get

func (n *Node) Get(ctx context.Context, id string) (*Job, error)

Get fetches one job by id.

func (*Node) Handover

func (n *Node) Handover(ctx context.Context, shard int) error

Handover performs the graceful handoff ordering (lesson #12): the CALLER ensures the new owner is ready first; this node then stops admitting, drains its wheel (unfired entries return to waiting), and releases the shard. No in-flight job is lost; the new owner's misfire rescan re-admits what was drained.

func (*Node) KillForTest

func (n *Node) KillForTest()

KillForTest simulates a hard kill: engines stop mid-flight (rows stay acquired) and the etcd session dies WITHOUT handover — leases expire and peers take over via reclaim. The node must not be used afterwards except Close.

func (*Node) Register

func (n *Node) Register(topic string, h Handler)

Register binds a handler on every owned engine (and engines added later).

func (*Node) Run

func (n *Node) Run(ctx context.Context)

Run drives all owned shard engines until ctx is done.

func (*Node) Submit

func (n *Node) Submit(ctx context.Context, topic string, payload []byte, opts ...SubmitOption) (string, error)

Submit persists a job; shard placement is hash(id) — any node can submit, any owner scans.

type Receipt

type Receipt struct {
	ID      string
	JobID   string
	Kind    string // fired | completed | dead | canceled
	Attempt int
	Error   string
	Reason  string // cancel reason
	At      time.Time
}

Receipt is one durable execution-log row: every state transition of interest is a row the user can SELECT. "Did this side effect happen?" is a query on every deployment shape (README: Contracts).

type ScanUnit

type ScanUnit string

ScanUnit is one unit of admission scanning: the whole table for SQLite, one partition for MySQL/TiDB.

type State

type State string

State is the lifecycle state of a job.

const (
	// Waiting: admitted by nobody yet; the quiet row.
	Waiting State = "waiting"
	// Acquired: CAS'd by an admission loop; held in the wheel.
	Acquired State = "acquired"
	// Fired: the wheel fired; handler dispatched.
	Fired State = "fired"
	// Completed: terminal success.
	Completed State = "completed"
	// Dead: terminal failure; dead-lettered.
	Dead State = "dead"
	// Canceled: revoked before fire; persists as a receipt.
	Canceled State = "canceled"
)

type StateCount

type StateCount struct {
	State State
	Count int64
}

StateCount is one row of the by-state breakdown.

type Stats

type Stats struct {
	JobsByState    []StateCount
	TotalJobs      int64
	TotalReceipts  int64
	OldestTerminal time.Time // oldest terminal row still kept (retention age)
}

Stats is the store-level overview for `hourglass stats`.

type Store

type Store interface {
	Ping(ctx context.Context) error
	Insert(ctx context.Context, j *Job) error
	Get(ctx context.Context, id string) (*Job, error)
	// Select waiting jobs in [from, to] ordered by due time, limit n.
	Select(ctx context.Context, unit ScanUnit, from, to time.Time, n int) ([]Job, error)
	// Acquire CAS's waiting -> acquired for exactly these ids, under
	// this epoch; it returns only the winners, re-read from the store.
	Acquire(ctx context.Context, unit ScanUnit, epoch uint64, ids []string) ([]Job, error)
	// contains filtered or unexported methods
}

Store is the persistence seam: the database keeps the long horizon. SQLite implements one scan unit (embedded); MySQL/TiDB implement shard-scoped scans plus lease reclaim (cluster).

type StoreExt

type StoreExt interface {
	Store
	Reclaim(ctx context.Context, unit ScanUnit, epoch uint64, ttl time.Duration) (int, error)
}

StoreExt is the cluster-only extension: lease-based reclaim (the shared database as arbiter; etcd only owns epochs).

type SubmitOption

type SubmitOption func(*submitConfig)

SubmitOption mutates a job before it is persisted.

func At

func At(t time.Time) SubmitOption

At schedules the job at an exact time.

func Delay

func Delay(d time.Duration) SubmitOption

Delay schedules the job relative to submit time.

func InShard

func InShard(n int) SubmitOption

InShard forces the shard placement (tests, ops tooling; default is hash(id)).

func Jitter

func Jitter(w time.Duration) SubmitOption

Jitter disperses the due time by rand(0, w), drawn once at submit and stored: hot minutes melt before they form (README). Default zero.

func Retries

func Retries(n int) SubmitOption

Retries sets additional attempts after the first failure. Retries(2) = 3 total attempts. Default 0 (single attempt).

func RetryBackoff

func RetryBackoff(d time.Duration) SubmitOption

RetryBackoff sets the delay before a failed attempt refires. Default 30s. The delay is constant; exponential growth is a v1.x knob.

Directories

Path Synopsis
cmd
benchplot command
benchplot renders SVG charts from hourglass-bench artifacts (bench-results/*.json).
benchplot renders SVG charts from hourglass-bench artifacts (bench-results/*.json).
hourglass command
hourglass-bench command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL