What Temporal Got Right
Distilled from studying temporal/common/persistence/
Single Factory, Many Backends
DataStoreFactory is the sole interface any database driver must implement.
Cassandra, PostgreSQL, SQLite — all satisfy one interface.
Swapping backends is a config change.
id + opaque DataBlob
Complex domain objects (ActivityInfo, TimerInfo, MutableState) are
serialized to protobuf/JSON blobs. Backends store
id + bytes, not per-field columns.
Domain model changes never touch the schema.
Layered Concerns
Store layer (raw CRUD + blobs) → Manager layer (serialization + business logic) → Client layer (metrics, retry, rate-limit). Each layer adds one responsibility. Callers only see the outermost layer.
Key insight we borrow for Dagu
Temporal stores execution state as opaque blobs alongside a few indexed key columns
(namespace_id, workflow_id, run_id). Dagu's equivalent: a records table with
collection + id + data + encoding + created_at + updated_at + expires_at.
No per-domain columns. Domain model evolves freely inside the blob.
Current State
The friction that motivates this refactoring
30
separate file-store packages
~9k
lines to rewrite per new backend
0
shared storage seams
∞
file-I/O duplication
Original Architecture — Each Store Owned Its Own File I/O
Shallow modules
Each store's interface is almost as complex as its implementation — mostly file I/O boilerplate wrapping JSON marshal/unmarshal.
No backend seam
To add PostgreSQL you must rewrite all 30 stores independently. There is no single interface to implement.
Duplicated I/O logic
Atomic writes, directory scanning, prefix filtering, cursor pagination, and file locking are reimplemented in every package.
DELETION TEST
Delete the file I/O logic inside any single store (e.g. filedagrun) —
the complexity (directory creation, atomic rename, JSON parse, prefix scan) does not vanish; it
moves to a shared FileBackend where it belongs once.
This is the seam we are making real.
Backend Abstraction Layer
STRONGThe primary refactoring — the seam that makes every other backend possible
FILES INVOLVED
Problem
Every store package independently manages file I/O. There is no common interface that separates what to store (domain logic) from how to store it (file system). A caller wanting to use PostgreSQL instead has no single abstraction to implement — they must rewrite 30 packages. The interface of each file store is nearly as complex as its implementation, violating Deep Module.
internal/persis/backend.go — THE SEAM (Collection: 8 methods, Backend: 2 methods)
// Package persis defines the storage backend interface for Dagu's control plane. package persis import ( "context" "errors" "time" ) // Encoding identifies the serialization format of Record.Data. type Encoding string const ( EncodingJSON Encoding = "json" EncodingProto Encoding = "proto3" // reserved; not yet supported ) // Record is the universal storage primitive for all control-plane data. // Every store (runs, users, secrets, queues, etc.) persists as Records. // Domain model changes never require schema changes — they live inside Data. type Record struct { // ID uniquely identifies this record within its collection. // Use "/" as a separator for hierarchical IDs. // Example: "mydag/run-abc/attempt-0" ID string Data []byte // opaque serialized payload (JSON only; proto3 reserved, not yet supported) Encoding Encoding // describes Data's format CreatedAt time.Time UpdatedAt time.Time // ExpiresAt, when non-nil, hints that this record may be deleted after // this time. Used for heartbeat / lease / TTL records. ExpiresAt *time.Time } // ListQuery controls what List returns. type ListQuery struct { Prefix string // only records whose ID starts with this value Since *time.Time // CreatedAt >= Since Until *time.Time // CreatedAt < Until Cursor string // opaque token from a prior Page.NextCursor Limit int // 0 = backend default } // Page is the result of a List call. type Page struct { Records []*Record NextCursor string // empty = no more records exist } // Collection is a named, isolated namespace of Records. // Implementations must be safe for concurrent use. type Collection interface { // Get returns the record identified by id, or ErrNotFound. Get(ctx context.Context, id string) (*Record, error) // Put creates or replaces a record. Put(ctx context.Context, rec *Record) error // Create atomically inserts rec, returning ErrConflict when the // record already exists. Used for backend-neutral "must not exist" // semantics — the create-if-absent half of optimistic concurrency. Create(ctx context.Context, rec *Record) error // Delete removes the record with the given id. // Returns nil if the record does not exist. Delete(ctx context.Context, id string) error // CompareAndDelete atomically removes expected.ID only when the // current record still matches expected. ErrConflict on mismatch. CompareAndDelete(ctx context.Context, expected *Record) error // List returns a page of records ordered by CreatedAt ascending. List(ctx context.Context, q ListQuery) (*Page, error) // CompareAndSwap atomically updates record id only when its current Data // equals expected. Returns ErrConflict when it does not match. // Used for optimistic concurrency on DAGRunStatus. CompareAndSwap(ctx context.Context, id string, expected, next []byte) error // Claim atomically removes one record matching q and returns it. // Used by queue adapters for atomic dequeue. // Returns ErrNotFound when no matching record exists. Claim(ctx context.Context, q ListQuery) (*Record, error) } // Backend is the sole interface a new database driver must implement. // It creates named Collections and manages lifecycle. type Backend interface { // Collection returns the collection with the given name. // Collections are created lazily; the name becomes the logical table. Collection(name string) Collection // Close releases all backend resources (connections, file handles, etc.). Close() error } // Sentinel errors returned by Collection methods. var ( ErrNotFound = errors.New("persis: record not found") ErrConflict = errors.New("persis: compare-and-swap conflict") )
Before → After
Before
1,400 ln
removed
300 ln
250 ln
200 ln
150 ln
200 ln
650 ln
Add PostgreSQL → rewrite all 30 stores
After
~60 ln
~70 ln
~50 ln
~60 ln
~70 ln
~50 ln
THE SEAM
persis.Backend interface
Collection(name) · Close()
~400 ln
future
future
Add PostgreSQL → Backend + Collection for collection-backed stores; separate lock and DAGRunStore work remains
What a Store Adapter Looks Like
The domain store interface (exec.DAGRunStore) is unchanged.
Only the implementation becomes a thin JSON adapter over persis.Collection.
BEFORE — internal/persis/filedagrun/store.go (excerpt)
func (s *Store) LatestAttempt( ctx context.Context, name string, ) (exec.DAGRunAttempt, error) { // navigate directory tree... root := s.dagRunRootDir(name) dirs, err := os.ReadDir(root) if err != nil { ... } // sort, find latest, open file... for _, d := range dirs { aDir := filepath.Join(root, d.Name(), "attempt") files, _ := os.ReadDir(aDir) // parse filenames, check timestamps... for _, f := range files { data, _ := os.ReadFile( filepath.Join(aDir, f.Name()), ) // unmarshal JSONL, pick last line... } } // ... 40 more lines of file wrangling }
AFTER — internal/persis/dagrun/store.go (same method)
type Store struct { col persis.Collection // "dag_runs" } func (s *Store) LatestAttempt( ctx context.Context, name string, ) (exec.DAGRunAttempt, error) { page, err := s.col.List(ctx, persis.ListQuery{ Prefix: name + "/", Limit: 1, }) if err != nil { return nil, err } if len(page.Records) == 0 { return nil, exec.ErrDAGRunIDNotFound } var status exec.DAGRunStatus json.Unmarshal(page.Records[0].Data, &status) return &attempt{status: status}, nil } // Testable with any mock Collection. // Zero file-system dependencies.
How FileBackend Implements Backend
The file.Backend consolidates all existing file I/O patterns
from the 30 store packages into a single implementation. The data layout is preserved —
this is a non-destructive refactoring.
Directory layout (unchanged on disk)
Future SQL backend schema (entire schema)
Collection(name) → directory
Each collection is a subdirectory. Collection("dag_runs") opens/creates {dataDir}/dag_runs/.
ID "/" → path separator
id = "mydag/run-1/att-0" maps to dag_runs/mydag/run-1/att-0.json. Prefix queries become directory scans.
Claim → file lock + rename
Atomic dequeue: lock directory, pick first matching file, read + delete atomically. SQL equivalent: SELECT FOR UPDATE SKIP LOCKED.
Benefits: Leverage and Locality
Leverage
9 methods unlock every collection-backed control-plane store including the distributed ones — they now run on CompareAndSwap + Create alone. Adding a new database still requires a backend-specific exec.DAGRunStore.
Locality
All file I/O complexity lives in one place (file/backend.go). Bugs in directory scanning, atomic writes, or cursor pagination are fixed once.
Testability
Domain store adapters become pure Go — no filesystem fixtures needed. Test with an in-memory Collection mock. Backend gets its own integration tests.
Schema stability
Collection-backed SQL records can keep a stable envelope as fields evolve. DAG-run remains a separate backend-specific store, so it is not covered by this generic schema claim.
Incremental migration
Port one store at a time. File layout on disk is unchanged. Run old and new implementations side-by-side during migration.
Simpler wiring
One backend := file.New(dir) call replaces 30+ individual store constructor calls in cmd/context.go.
Codec / Serialization Layer
WORTH EXPLORINGSecondary refactoring — complements Candidate 1 but not required for it
Problem
Every store adapter will call json.Marshal/Unmarshal directly.
This duplicates encoding error handling, makes it hard to add proto3 support later,
and provides no hook for schema versioning.
Solution
A thin persis/codec.go with two generic helpers:
// Encode marshals v to JSON, returning the bytes and encoding. func Encode(v any) ([]byte, Encoding, error) // Decode unmarshals rec.Data into *v using rec.Encoding. func Decode[T any](rec *Record, v *T) error
Benefits
- → One place to change encoding later (currently JSON-only; file backend rejects non-JSON)
- → One place to add a version field for future migrations
- → Store adapters become 2-line encode/decode calls
- → Codec is tested in isolation, independently of backend
Recommendation: implement this alongside Candidate 1 — the marginal cost is ~50 lines
and it prevents scattered json.Marshal calls from proliferating
across 30 adapters.
Proposed Package Structure
What moves where
BEFORE — internal/persis/
AFTER — internal/persis/
Wiring Change in cmd/context.go
BEFORE — 30+ separate constructors
// context.go — NewContext() drs := filedagrun.New(cfg.Paths.DAGRunsDir, ...) // queue had its own file-backed constructor here; that package is now removed ps := fileproc.New(cfg.Paths.ProcDir, ...) sm := fileserviceregistry.New(cfg.Paths.ServiceRegistryDir) dls := filedistributed.NewDAGRunLeaseStore(...) ads := filedistributed.NewActiveDistributedRunStore(...) dts := filedistributed.NewDispatchTaskStore(...) whs := filedistributed.NewWorkerHeartbeatStore(...) us := fileuser.New(cfg.Paths.UsersDir, ...) ss := filesecret.New(cfg.Paths.SecretsDir, ...) // ... 20+ more lines like this
AFTER — current branch wiring
// context.go — NewContext() drs := file.NewDAGRunStore(cfg, ...) ds := file.NewDAGStore(cfg, ...) qs := store.NewQueueStore(file.NewCollection(cfg.Paths.QueueDir)) ps := file.NewProcStore(cfg) sr := file.NewServiceRegistry(cfg) leaseCollection := file.NewCollectionWithLockRoot(filepath.Join(distributedDir, "leases"), distributedDir) activeRunCollection := file.NewCollectionWithLockRoot(filepath.Join(distributedDir, "active-runs"), distributedDir) dls := store.NewDAGRunLeaseStore(leaseCollection) ads := store.NewActiveDistributedRunStore(activeRunCollection) dts := store.NewDispatchTaskStore(file.NewCollection(distributedDir)) us := store.NewUserStore(file.NewCollection(cfg.Paths.UsersDir), ...) ss := store.NewSecretStore(file.NewCollection(cfg.Paths.SecretsDir), encryptor) // DAG-run, DAG definition, proc, and service-registry wiring should go through the file backend boundary instead of leaf file packages. // Agent config/model/soul/memory/OAuth/session wiring follows the same file boundary for CLI, server, worker, and snapshots. // Service stores such as audit, event, notification, incident, workspace, license, token secret, and upgrade cache also go through the same file boundary. // frontend.NewServer receives backend-neutral StoreFactories; cmd/process supplies the file-backed factory bundle.
Collection Naming & ID Conventions
Collections map to directories (FileBackend) or rows in a single records table (SQL).
IDs use / as a hierarchy separator — prefix queries support tree traversal.
| Collection | Domain | ID Format | Notes |
|---|---|---|---|
| dag_runs | DAGRunStore | {dagName}/{runID}/{attemptID} | Prefix by dagName or dagName/runID for scoped queries. CAS used for status updates. |
| queue_items | QueueStore | {queueName}/{high|low}_{uuid} | Priority encoded in ID sort order. Claim = atomic dequeue. |
| proc_entries | ProcStore (collection backend only) | {group}/{procName} | Not used by the file backend. File-backed proc uses internal/persis/file/proc and keeps the released .proc layout. |
| dispatch_tasks | DispatchTaskStore | {taskID} | Claim for atomic worker assignment. |
| worker_heartbeats | WorkerHeartbeatStore | {workerID} | ExpiresAt for stale-worker detection. |
| dag_run_leases | DAGRunLeaseStore | {queueName}/{attemptKey} | ExpiresAt for lease expiry. |
| active_runs | ActiveDistributedRunStore | {dagName}/{runID} | Coordinator's index of live runs. |
| users | UserStore | {userID} | Username lookup via in-memory index rebuilt on List. |
| secrets | SecretStore | {workspace}/{secretName} | Adapter encrypts Data before Put, decrypts after Get. |
| api_keys | APIKeyStore | {keyID} | Simple CRUD. |
| webhooks | WebhookStore | {webhookID} | DAG-name lookup via prefix or in-memory index. |
| audit_log | AuditStore | {YYYY-MM-DD}/{uuid} | Append-only. Since/Until on ListQuery for time-range queries. |
| events | EventStore | {YYYY-MM-DDHH}/{eventID} | Committed vs inbox via ID prefix convention. |
| sessions | SessionStore | {userID}/{sessionID} | Prefix by userID for user-scoped listing. |
| agent_memory | MemoryStore | global or dag/{dagName} | Plain text blob in Data (EncodingJSON = "raw"). |
| service_registry | ServiceRegistry | {serviceName}/{instanceID} | ExpiresAt for stale instance detection. |
| notifications | NotificationStore | {notificationID} | Adapter handles per-field encryption. |
| base_config | BaseConfigStore | config | Single-record collections. Get("config") / Put. |
filedag/, behind file.NewDAGStore),
step execution logs, artifact outputs, and any user-managed files remain on disk as-is.
The Backend only owns control-plane metadata — the records that describe what runs, not the artifacts of running.
Migration Strategy
Incremental, non-destructive — one store at a time
Why this is safe
- • FileBackend maps collection IDs to the same directory layout for collection-backed stores. No data migration.
- • DAG-run is a strict compatibility refactor: physical paths, sidecar files, status log shape, indexes, and lock behavior must not change.
- • Removing
filedagrunmeans removing the legacy package/API, not moving file-layout code into the DB-neutralstorepackage. - • API, worker, and engine code must depend on persistence interfaces/factories such as
exec.DAGRunStore; only composition wiring and tests should import file backend implementations such asinternal/persis/file/dagrun. - • Old and new code can run together during porting (different stores).
- • Each store port is independently testable and reviewable.
- • File format (JSON) unchanged — existing file-backed data remains readable immediately.
How to add PostgreSQL later
- • Create
persis/sql/backend.goimplementing Backend + Collection. - • Single
recordstable schema can support the collection-backed stores. - • Distributed stores still need backend-neutral lock/claim semantics before they are portable beyond the file backend.
- • DAG-run needs a backend-specific
exec.DAGRunStoreimplementation; do not force its file-layout mechanics intopersis/store.
Status — current refactor branch as of May 27, 2026
Phase 1 Complete · Phase 2 Compatibility Refactor In Progress
The seam exists. persis.Backend and persis.Collection are live.
Queue and proc use collection-backed stores. Distributed records are collection-backed but still depend on file-backend lock behavior.
DAG-run is moved from filedagrun to internal/persis/file/dagrun as a file-backed exec.DAGRunStore; its physical paths and JSON shape remain unchanged.
Interface surface
10
Collection 8 + Backend 2 (Create added)
Stores ported
18+
collection-backed adapters plus file-backed DAG-run compatibility
Neutrality gaps
1
backend-specific DAGRunStore (distributed CAS done)
Backend surface
480
shared collection backend; DAG-run file layout remains in file/dagrun
✅ Done / preserved
- ✓
persis/backend.go— Backend, Collection, Record, ListQuery, Page - ✓
persis/codec.go— Encode(v any) ([]byte, Encoding, error), Decode[T] - ✓
persis/errors.go— ErrNotFound, ErrConflict - ✓
persis/file/— FileBackend + FileCollection (480 ln) - ✓
persis/testutil/memory.go— MemoryBackend (217 ln) - ✓
persis/store/— collection-backed adapters with tests; proc remains collection-only and is not wired to the file backend - ✓
internal/persis/filequeue— removed after queue wiring moved tostore.NewQueueStore(file.NewCollection(cfg.Paths.QueueDir)) - ✓
internal/persis/filelicense— removed; replaced infile.NewLicenseStore(cfg)(pre-creates license dir at0o700, then usesstore.NewLicenseStore(NewCollection(dir, WithIndentedJSON()))) with byte-identical on-disk format - ✓
internal/persis/fileupgradecheck— removed; replaced infile.NewUpgradeCheckStore(cfg)(creates{DataDir}/upgrade/at0o750, then usesstore.NewUpgradeCheckStore(NewCollection(dir, WithIndentedJSON()))); invalid-JSON quirk preserved (returns nil cache, no error) - ✓
internal/persis/file/dagrun— file-backed DAG-run store with exact existing file-layout compatibility - ✓ DAG-run wiring goes through
file.NewDAGRunStoreand service code depends onexec.DAGRunStore - ✓
internal/persis/file/proc— file-backed ProcStore keeps released.procpaths and payloads; no collection JSON is written under the proc directory
⏳ Next — Phase 2
- ✓
Replace distributed stores' file-lock dependency with backend-neutral lock/claim semantics.Lease/active/dispatch now useCompareAndSwap+ a newCollection.Createprimitive;persis/store/no longer importsdirlock. - 5. Keep DAG-run behind
exec.DAGRunStore; add a backend-specific SQL implementation when DBMS support is added. - 6. Continue deleting old
file*/packages only when their file-layout compatibility has a clear replacement. - 7. Unify wiring where it is honest to do so; do not hide file-specific behavior inside
persis/store.