I Built a Distributed Workflow Engine in Go. Then I Made Its Workers Fail.
How I built FlowForge in Go using DAG scheduling, PostgreSQL leases, fencing tokens, Redis Streams, and a transactional outbox.
Contents7 sections
00 / Who gets to say a task is finished?
How DAG scheduling, leases, fencing tokens, and a transactional outbox help a distributed system recover when execution goes wrong.
Running one background task is easy. Running a hundred tasks in the right order, across workers that can disappear at any moment, is a different problem.
Imagine a data pipeline: extract a dataset, normalize and enrich it in parallel, then generate a report. The report cannot start until both branches finish. Now imagine one worker freezes halfway through its task. Should the system wait forever, retry the task, or trust the original worker if it eventually returns?
Those questions became the foundation of FlowForge, a workflow orchestration engine I built in Go. I wanted to go beyond a pipeline that worked on a good day: I wanted to understand what happens when a worker disappears, a message arrives twice, or an old worker tries to finish a task it no longer owns. The most interesting problem wasn't getting work to run. It was deciding who is allowed to say a task has finished.
01 / Dependencies before execution
A workflow is a directed acyclic graph (DAG): nodes are tasks, and arrows mean one task must finish before another begins.
Before a run starts, FlowForge validates its graph using Kahn's topological sorting algorithm and rejects cycles. At the start of a run, tasks with no dependencies become READY; the others remain BLOCKED.
The scheduler then uses a PostgreSQL common table expression (CTE) with a NOT EXISTS dependency check to unlock a blocked task only when none of its predecessors remains unfinished. In other words, the database helps decide when work is eligible to run, rather than trusting an in-memory queue to remember the whole graph.
02 / Separate the source of truth from the queue
FlowForge has two distinct responsibilities: keeping the correct workflow state and delivering work to available workers.
The Go API accepts workflow definitions and starts runs. PostgreSQL stores definitions, task states, leases, and pending events. A scheduler advances dependencies and checks for abandoned tasks. Redis Streams delivers task.ready notifications to a worker consumer group and events to the live dashboard.
In the local quickstart, the API, scheduler, relay, and three worker loops run inside one Go process; PostgreSQL and Redis run as separate services. This is a useful local demonstration of distributed coordination—not a claim that the default setup is a multi-host production deployment.
A worker receiving a Redis message does not automatically own the task. It must first atomically change that task from READY to LEASED in PostgreSQL. If the task is already leased or finished, the update fails. A duplicate notification cannot grant a second current lease; this does not guarantee that the computation runs only once across retries.
03 / What if a dead worker isn't actually dead?
The failure case that shaped the design was a worker that looked dead—but wasn't.
Worker A claims a task and receives a unique UUID lease token. Then it stalls: perhaps the process hangs, the network slows down, or execution simply takes too long. Its lease expires. The scheduler eventually resets the task to READY, and Worker B acquires it with a different token.
What happens when Worker A wakes up and tries to commit its old result?
FlowForge uses lease fencing. A successful completion is a conditional PostgreSQL update, not an unconditional write:
UPDATE task_runs
SET state = 'SUCCEEDED', output_ref = $1
WHERE id = $2
AND state IN ('LEASED', 'RUNNING')
AND lease_token = $3::uuid;If A presents the old token after B has taken ownership, the update matches zero rows. FlowForge returns ErrStaleLeaseCommit instead of letting A overwrite the newer task state. The completion query checks task state and token equality; it does not check lease_expires_at. Expiry makes a task eligible for scheduler recovery, but the clock passing the deadline does not itself invalidate the token. Until recovery clears it, an otherwise matching completion can still succeed. The repository has a lease-fencing test that simulates a reset to READY, reacquires the task with a new token, and checks that the old token is rejected.
That distinction matters: the task may execute more than once, but stale workers cannot commit their results to FlowForge's task record after reassignment. This does not undo external side effects. If an HTTP task already charged a card or posted a message, SQL fencing cannot reverse that action. Such integrations need idempotency or their own deduplication strategy.
04 / The invisible failure between PostgreSQL and Redis
There was another deceptively simple failure window. Suppose the scheduler marks a task READY in PostgreSQL, then publishes a notification to Redis. If the process crashes between those two operations, the database knows the task is ready but workers might never hear about it.
FlowForge's scheduler writes both the task-state change and an outbox event in one PostgreSQL transaction. A separate relay polls unsent events, publishes them to Redis Streams, and marks them sent afterward.
This shifts the failure boundary. If the process crashes before the database transaction commits, neither change survives. If it commits, the event remains available for the relay to retry.
There is a trade-off: a relay can publish successfully and crash before marking the row sent. On restart it may publish the same event again. That gives the outbox relay an at-least-once publication model, assuming PostgreSQL and Redis become available and the relay continues retrying. It does not establish exactly-once execution or complete end-to-end delivery. Database-side lease acquisition prevents duplicate task.ready notifications from giving multiple workers simultaneous valid ownership.
There is still a delivery gap in this version. Workers read new Redis consumer-group messages with XREADGROUP ... >, without a pending-message reclaim path. If a worker stops after receiving a message but before acquiring its PostgreSQL lease, the message can remain pending while the task stays READY. Expired-lease recovery cannot rescue a task that never acquired a lease. Pending-message recovery or a reconciliation scan would be needed to close that gap.
05 / Recovery is part of scheduling
The scheduler also scans for expired leases and returns abandoned tasks to READY, incrementing their attempt count. Failed adapter executions can enter RETRY_WAIT with exponential backoff capped at ten seconds; exhausted execution retries can move a task into a DLQ state. Expired leases take a separate recovery path, so this is not a claim that repeated lease expiry is bounded by the same retry limit. The React dashboard visualizes task progress, worker status, and simulated failure controls. The hosted website also offers a browser-side simulator; its animations illustrate scenarios rather than prove that a live backend executed them.
I wrote tests for cycle detection, dependency unlocks, expired-lease recovery, lease fencing, and outbox behavior. The repository contains the source and a demo video.
There are deliberate limits. In this version, the local worker fleet runs inside the server process, the Python adapter simulates script execution rather than launching a Python subprocess, and external side effects are not guaranteed exactly once. The backend chaos control sets a Redis flag that pauses future worker pickups and suppresses heartbeats. It does not forcibly stop an adapter already executing, and it is not the same as crashing an independent host.
Those limitations are part of what made the project useful: distributed-system guarantees become clearer when you define precisely what is protected, and what isn't.
06 / What I took away
A workflow engine isn't just a queue with arrows. It's a collection of decisions about dependencies, ownership, retries, and recovery.
The most surprising lesson was that a task can have a perfectly clear state in PostgreSQL while a delayed worker still believes it owns that task. A queue message isn't permission to execute, a timeout isn't proof of death, and a completed computation isn't automatically a valid result. Ownership has to be checked where the durable state lives.
The hard part isn't getting work started. It's making ownership explicit—and checking the stored token before accepting a result.
Thanks for reading.
Back to the notebook