spin

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 1 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

Spin

Go 1.24 License MIT

Spin is durable execution for Go programs that should ship as a single binary, not as a cluster.

Embedded, single-process durable execution for Go: replayable workflows, append-only event history in Pebble, durable timers that do not pin workers on time.Sleep, and optional WASM activities. No Postgres, no Temporal cluster, and no operations tax for local agents, CLIs, and sidecar-style workloads.

Personal side project: Spin is built and maintained by a solo developer in spare time—not a team-operated platform or commercial product. Expect embedded-scope APIs, pragmatic trade-offs, and a roadmap shaped by real-world side-project constraints rather than enterprise SLAs.

go get github.com/yavuzselimilik/spin

Why Spin exists

Durable workflows (Temporal, Cadence, and others) solve the right problem: survive process crashes, sleep for hours or days, and replay deterministically from an event history. They shine when you operate a multi-service control plane at scale.

For a local AI agent, CLI tool, or single-binary sidecar, wiring in a full cluster is often disproportionate: more infrastructure, more versioning, and a slower development loop. Spin is a deliberately scoped alternative: one process, one DataDir, Go-native API. It keeps the replay-log mental model, but embeds it in your process the way SQLite embeds relational storage.

Temporal is excellent at scale. Spin is for the smaller cases where a cluster would be the wrong level of machinery.

Architecture

One-page mental model: workflow code talks to a replay context; the engine appends CBOR events to Pebble, schedules durable sleeps on a hashed timing wheel, and wakes workflows through a worker pool.

System overview: components and data flow.

flowchart LR
  subgraph app["Application"]
    WF[Workflow func]
  end
  subgraph spin["Spin Engine"]
    CTX[Replay Context]
    SCH[Worker pool]
    TW[Timing wheel]
  end
  subgraph persist["DataDir"]
    PB[(Pebble event log)]
    LK[.spin.lock]
  end
  WF --> CTX
  CTX -->|append Step Activity Sleep| PB
  CTX -->|suspend| TW
  TW -->|wake workflowID| SCH
  SCH --> CTX
  PB -->|load history| CTX
Event-sourced durability (Pebble + CBOR)

Problem: workflow state must survive crashes without an external database. Decision: append-only per-workflow events in embedded Pebble, encoded with CBOR. Mechanism: on each run the workflow function re-enters from the top; Step, ExecuteActivity, and Sleep consume matching history or append new events (internal/engine/context.go, internal/storage/pebble.go).

Event log keys: monotonic sequence per workflow ID.

flowchart LR
  subgraph keys["Pebble keys"]
    K1["evt/order-1/00000000000000000001"]
    K2["evt/order-1/00000000000000000002"]
    K3["evt/order-1/..."]
  end
  WF[WorkflowID] --> K1
  K1 -->|AppendEvent CBOR| K2
  K2 --> K3

Replay-from-top: history is the source of truth; divergence fails closed.

sequenceDiagram
  participant Eng as Engine
  participant CTX as ReplayContext
  participant PB as Pebble
  Eng->>PB: LoadEvents(workflowID)
  PB-->>CTX: event history
  loop each Step Sleep Activity
    CTX->>CTX: expectEvent or run live fn
  end
  alt mismatch
    CTX-->>Eng: ErrReplayMismatch
  end

Activities: first run records output; replay reads the log and skips the closure.

On the first pass, ExecuteActivity runs your closure and appends EventActivityRecorded to Pebble. The return bytes live in Payload, and InputHash holds SHA-256 of the input argument. On later runs (crash recovery or timer wakeup), the engine replays from the top: the closure is not invoked again, and the return value comes from Payload. The hash is not a substitute for the output; it proves that replay is using the same activity name with the same inputs. A different input on replay returns ErrReplayMismatch.

Activities are at-least-once across a process crash: if the process dies after an external side effect succeeds but before its result is persisted, Spin must invoke the closure again during recovery. Make activity side effects idempotent (for example, use the workflow ID as an idempotency key). Put HTTP, database, and filesystem I/O inside activities or WASM guests; the workflow function body should orchestrate through Step, Sleep, and ExecuteActivity.

Typed workflow state is snapshotted as EventWorkflowStateSnapshot (default CBOR via StateCodec[T]).

Hashed timing wheel (durable sleep)

Problem: time.Sleep inside workflow code breaks determinism and pins worker goroutines. Decision: O(1) hashed timing wheel (internal/timer/timing_wheel.go) with 3600 slots, container/list buckets, and a configurable tick (default 1s). Mechanism: Sleep persists EventWorkflowSuspended, registers AddTask(workflowID, delay), and returns a suspend signal. Each tick advances currentSlot, decrements Rounds for long delays, and emits ready IDs on an unbuffered Output channel. If no receiver is ready, a short-lived goroutine performs the send so the ticker loop keeps moving.

  currentSlot ──►  [slot i] ──► linked list of Task{WorkflowID, Rounds}
  each tick:      currentSlot = (currentSlot + 1) % 3600
                  Rounds > 0  → stay in bucket, Rounds--
                  Rounds == 0 → emit WorkflowID on Output channel

Durable sleep lifecycle: suspend, wheel, re-enqueue, replay, then continue.

sequenceDiagram
  participant WF as Workflow
  participant CTX as ReplayContext
  participant PB as Pebble
  participant TW as TimingWheel
  participant WQ as WorkQueue
  WF->>CTX: Sleep(3s)
  CTX->>PB: EventWorkflowSuspended
  CTX->>TW: AddTask(workflowID, 3s)
  Note over CTX: workflow returns suspended
  loop each tick
    TW->>TW: tick slot decrement Rounds
  end
  TW->>WQ: Output workflowID
  WQ->>CTX: reload events replay then continue

AddTask slot math: Rounds counts full wheel rotations (3600 slots per round).

flowchart TD
  delay[delay duration] --> ticks["ticks = max(1, delay / Tick)"]
  ticks --> calc["rounds = ticks / 3600; remainder = ticks % 3600"]
  calc --> normalize["if remainder == 0: rounds--; remainder = 3600"]
  normalize --> slot["slot = (currentSlot + remainder) % 3600"]
  slot --> push["Push Task into the target slot list"]
  push --> note[Rounds tracks full wheel rotations]

Timers are quantized to Tick; delays below one tick are scheduled for one tick.

Timer recovery: deadline is in the log, not in the wheel.

Each suspend stores Timestamp (when the sleep started) and the requested duration in the event payload. The real deadline is wakeAt = Timestamp + duration. The in-memory timing wheel is only a scheduler hint; after a crash it is rebuilt from Pebble. On Engine.Start, PendingSleep computes remaining = wakeAt - now. If now is still before wakeAt, only remaining time is passed to AddTask, so the sleep does not restart from the full duration. If now is already past wakeAt, the workflow is enqueued immediately. During replay, Sleep applies the same deadline rule: if the deadline has not passed, it re-suspends for the remaining interval.

Example: Sleep(7 days) at T0, process exits at T0+1 day, stays down until T0+4 days. On Start, wakeAt is still T0+7 days, so roughly 3 days remain—not a fresh 7-day timer. The demo GIF under Demo shows the same idea with a shorter sleep.

sequenceDiagram
  participant Log as Pebble suspend event
  participant Eng as Engine Start
  participant TW as TimingWheel
  Note over Log: wakeAt = Timestamp + duration
  Eng->>Log: PendingSleep now
  alt now before wakeAt
    Eng->>TW: AddTask remaining only
  else now after wakeAt
    Eng->>Eng: enqueue immediately
  end

Recovered remaining is at least one Tick (default 1s).

DAG as workflow contract

Problem: step order must be explicit and cycles should be rejected before traffic reaches a workflow. Decision: optional Graph at registration: DFS cycle detection (internal/engine/dag.go) and runtime predecessor checks (ErrDAGViolation). Clarify: the graph is a contract layer for allowed structure and ordering; it does not auto-schedule parallel step goroutines. Steps within one workflow run sequentially; WorkerCount only parallelizes different workflow IDs.

Registration vs runtime enforcement.

flowchart TB
  subgraph register["Registration time"]
    G[Graph AddEdge]
    V[DFS Validate no cycle]
    R[RegisterWithGraph]
    G --> V --> R
  end
  subgraph runtime["Runtime Step"]
    S[ctx.Step name]
    P{all predecessors in completedSteps?}
    S --> P
    P -->|yes| Run[run step fn append EventStepCompleted]
    P -->|no| Err[ErrDAGViolation]
  end
  R -.->|graph attached| S

Payment demo graph: edges are contracts; Go code chooses charge vs refund.

flowchart LR
  validate --> charge
  validate --> refund
  charge --> receipt
  refund --> receipt
Execution loop, WASM, and crash recovery

Workers drain a shared workQueue; bridgeTimingWheel feeds timer wakeups. Each workflow ID is serialized with a per-ID mutex, so timer callbacks cannot execute concurrently with another run of the same workflow ID (internal/engine/engine.go).

Workers, timing wheel bridge, and per-workflowID lock.

flowchart TB
  TW[TimingWheel Output] --> B[bridgeTimingWheel]
  B --> WQ[workQueue chan]
  Run[RunWorkflow] --> WQ
  WQ --> W1[worker 1]
  WQ --> W2[worker N]
  W1 --> L{per workflowID mutex}
  W2 --> L
  L --> Exec[executeWorkflow load replay run]

Scheduling and backpressure: bounded queue, no drops, no fleet-scale admission control.

The shared workQueue is a buffered channel (capacity 256). When it is full, enqueue blocks until a worker drains an ID, so workflow IDs are not dropped. WorkerCount (default GOMAXPROCS) limits how many workflow runs can execute at once, and the per-ID mutex prevents concurrent execution of the same workflow ID. The scheduler also skips enqueue for IDs already marked as running. Pending timer tasks live in the timing wheel’s in-memory slot lists; there is no global cap on pending sleeps or wakeup rate. If many workflows fire at once, the queue backs up, spare goroutines may deliver timing-wheel output when the channel is busy, and memory grows with pending tasks plus Pebble history. That is intentional for embedded workloads, but it is not a fleet-scale admission-control system. Use a cluster orchestrator when you need that class of protection.

Strict replay (internal/engine/replay.go) returns ErrReplayMismatch on any divergence. Optional wazero activities run with WasmConfig bounds (duration, module size, LRU compile cache).

WASM activity path (optional).

sequenceDiagram
  participant CTX as Context
  participant WZ as wazero
  participant G as WASM guest
  CTX->>WZ: compile cache run
  WZ->>G: run inputPtr inputLen outPtr outCap
  G-->>CTX: bytes written to linear memory

Crash recovery on Start: resume every non-terminal workflow from the log.

sequenceDiagram
  participant Eng as Engine
  participant PB as Pebble
  participant TW as TimingWheel
  Eng->>PB: scan incomplete workflows
  PB-->>Eng: history + latest lifecycle event
  alt pending sleep deadline is in the future
    Eng->>TW: AddTask remaining delay
  else runnable or sleep deadline has passed
    Eng->>Eng: enqueue workflowID on workQueue
  end

Built on

Spin’s timing wheel and DAG logic are stdlib-only; there is no third-party scheduler. These four direct dependencies carry persistence, serialization, isolation, and locking:

Library Role in Spin
Pebble Embedded LSM for append-only workflow events under DataDir/events. Pure Go—no RocksDB/CGO or remote database.
fxamacker/cbor/v2 CBOR for StateEvent records and StateCodec[T] snapshots—compact and stable across restarts.
wazero Zero-CGO WebAssembly runtime for optional ExecuteWasm activities in-process.
gofrs/flock Exclusive lock on {DataDir}/.spin.lock (ErrDataDirLocked)—single-writer DataDir by design.

Code showcase

Inspect a workflow

The public inspection API is deliberately small: it is enough for a CLI or embedded status endpoint without adding a control plane.

info, err := eng.Workflow("order-1")
// info.Status: pending, queued, running, sleeping, completed, or failed
// info.WakeAt is set while sleeping; info.Error is set when failed.

history, err := eng.History("order-1")
// ordered, read-only event history for debugging or display
package main

import (
	"context"
	"os"
	"time"

	"github.com/yavuzselimilik/spin"
)

type OrderState struct{ Phase int }

func main() {
	dir, _ := os.MkdirTemp("", "spin-*")
	defer os.RemoveAll(dir)

	eng, _ := spin.New[OrderState](spin.Config{DataDir: dir, Tick: time.Second})
	g := spin.NewGraph()
	g.AddEdge("validate", "ship")
	_ = eng.RegisterWithGraph("order", g, func(ctx spin.Context[OrderState], s *OrderState) error {
		if err := ctx.Step("validate", func() error { s.Phase++; return nil }); err != nil {
			return err
		}
		if err := ctx.Sleep(2 * time.Second); err != nil { // durable; not time.Sleep
			return err
		}
		return ctx.Step("ship", func() error {
			// First run: closure runs, output in Payload. Replay: return Payload, verify InputHash, skip closure.
			_, err := ctx.ExecuteActivity("notify", []byte("order-1"), func() ([]byte, error) {
				return []byte("sent"), nil
			})
			return err
		})
	})

	_ = eng.Start(context.Background())
	_ = eng.RunWorkflow("order-1", "order", &OrderState{})
	_ = eng.Shutdown(context.Background())
}

Demo

cmd/demo runs order, payment, and onboarding workflows (DAG, branching, activities, durable sleep) in one process.

go run ./cmd/demo
SPIN_DEMO_PERSIST=1 go run ./cmd/demo   # restart while sleeping to see recovery

Durable sleep survives process restart

Stop the demo during a sleep (Ctrl+C), run it again with SPIN_DEMO_PERSIST=1, and the engine recovers remaining sleep time from Pebble on Start rather than restarting the full original duration. WASM guest ABI: cmd/demo/reference/.

Deterministic workflow code

Workflow functions must be deterministic with respect to the event log: the same sequence of Step, ExecuteActivity, and Sleep calls must be reproduced on every replay. Spin does not statically analyze your Go code; violations usually surface at the next replay boundary as ErrReplayMismatch.

Avoid in the workflow function Use instead
time.Now(), time.Sleep ctx.Sleep; wall-clock needs belong in an activity or in state you persist
rand.*, uuid.New(), other nondeterministic IDs Generate inside ExecuteActivity; pass bytes back to the workflow
http.Get, database calls, filesystem I/O ctx.ExecuteActivity with idempotent side effects; persisted results replay from Payload
Goroutines that change control flow Sequential Step / ExecuteActivity

ctx.Now() exists but is wired to wall clock; it is not recorded in history. Branching on ctx.Now() during replay is unsafe because replay time can differ from the first run. Step handlers are skipped on replay (only EventStepCompleted is consumed), so durable workflow state should come from activity outputs or from StateCodec[T] snapshots written at step, suspend, and completion boundaries.

Safety model

Spin fails closed on replay divergence and enforces single-writer durability:

  • Strict replay — Step, ExecuteActivity, and Sleep must match the persisted log; mismatch → ErrReplayMismatch + EventWorkflowFailed.
  • Per-workflow lock — no concurrent runs of the same workflow ID (including timer wakeups).
  • State snapshots — after each successful Step, sleep suspend, and completion (StateCodec[T] override supported).
  • Runtime DAG — RegisterWithGraph enforces predecessor completion before Step.
  • Activity integrity — persisted output and SHA-256 input hash are replayed without invoking the closure; activities remain at-least-once if a crash happens before persistence.
  • WASM bounds — MaxRunDuration, MaxModuleBytes; compile cache LRU; load trusted bytecode only.
  • Single-process DataDir — flock on .spin.lock; second process gets ErrDataDirLocked.

Trade-offs

Trade-off Rationale
Single-node, single-writer gofrs/flock on DataDir; no cluster or split-brain story
Replay-from-top Simple correctness; very long histories mean more replay work (no compaction story yet)
Deterministic workflow code Same class as Temporal—see Deterministic workflow code; no static checker, fail-closed replay
Timer resolution Default 1s tick; delays below one tick are scheduled for one tick
No admission control Work queue blocks at 256 slots; no wakeup rate limits—embedded scope, not fleet-scale load shedding
DAG ≠ parallel executor Graph enforces order; parallel steps within one workflow are not scheduled yet
WASM Bounded runtime/size; host loads bytecode—defense in depth, not full multi-tenant isolation
Not a Temporal replacement No signals, queries, child workflows, or multi-tenant namespaces

When to use Spin: embedded agents, CLIs, sidecars, tests, prototypes—one binary, one DataDir, minimal ops.

When to use Temporal: multi-service production, operators, visibility, and fleet-scale workflow orchestration.

Testing

go test ./...
go vet ./...
go test -race ./...

Integration tests (crash recovery, replay, concurrency) live under test/integration/.

License

MIT — see LICENSE. Third-party dependency licenses are listed in THIRD_PARTY_NOTICES.md.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrDAGViolation = engine.ErrDAGViolation

ErrDAGViolation is returned when a step runs before its DAG predecessors.

View Source
var ErrReplayMismatch = engine.ErrReplayMismatch

ErrReplayMismatch is returned when workflow code diverges from the event log.

View Source
var ErrWorkflowCompleted = engine.ErrWorkflowCompleted

ErrWorkflowCompleted is returned when a completed workflow ID is reused.

View Source
var ErrWorkflowFailed = engine.ErrWorkflowFailed

ErrWorkflowFailed is returned when a failed workflow is started again without retry support.

View Source
var ErrWorkflowNotFound = engine.ErrWorkflowNotFound

ErrWorkflowNotFound is returned when an ID has no workflow history.

Functions

This section is empty.

Types

type Config

type Config = engine.Config

Config configures the SPIN engine.

type Context

type Context[T any] = engine.Context[T]

Context is the workflow SDK surface.

type Engine

type Engine[T any] = engine.Engine[T]

Engine runs registered workflows with replay and persistence.

func New

func New[T any](cfg Config) (*Engine[T], error)

New creates a new Engine.

type Graph

type Graph = engine.Graph

Graph validates workflow step dependencies.

func NewGraph

func NewGraph() *Graph

NewGraph creates an empty dependency graph.

type HistoryEvent

type HistoryEvent = engine.HistoryEvent

HistoryEvent is one public event-history entry.

type StateCodec

type StateCodec[T any] = engine.StateCodec[T]

StateCodec marshals workflow state for durable snapshots.

type WasmConfig

type WasmConfig = engine.WasmConfig

WasmConfig limits WASM activity execution.

type WorkflowInfo

type WorkflowInfo = engine.WorkflowInfo

WorkflowInfo is a read-only view of a workflow instance.

type WorkflowStatus

type WorkflowStatus = engine.WorkflowStatus

WorkflowStatus describes a workflow's lifecycle state.

Directories

Path Synopsis
cmd
demo command
internal

Jump to

Keyboard shortcuts

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