Picking up Mastra workflow runs after a crash

A glowing ember in grey ash catching a small new flame

At Flash we run 11 Mastra agents behind the agentic marketplace at flash.co, plus a WhatsApp commerce agent. Most of the real work happens in long workflows. Every day the agents run 8 to 10 jobs that take 30 minutes or more, and the WhatsApp agent runs all its async jobs as workflows.

Our Mastra servers run on ECS, as tasks. Tasks come and go all the time: a redeploy replaces them, new ones come up when we scale, and now and then one crashes. Pods on Kubernetes behave the same way. Whenever a task went away in the middle of a run, the run stopped there and stayed in running.

rekindle is the small library I wrote earlier this year to pick those runs back up. All 12 agents run on it, and so far it has resumed 492 runs. Those runs carried on by themselves after a deploy or a crash. A developer didn’t have to restart them, our CD pipeline didn’t have to trigger anything, nobody had to check the data afterwards, and the critical daily jobs finished on time.

It’s on npm as mastra-rekindle, for Mastra 1.46 to 1.83.

If you’re on Mastra 1.84 or later, Mastra now has workflow recovery built in, with run leases, a recovery loop and leader election. Use that. We’re moving to it too.

What Mastra 1.4x gave us

Mastra saves every run to Postgres as it goes, step by step, and a stopped run could be resumed. run.restart() picks a run up from its last active step: the step that was interrupted runs again from its start, and the steps that had finished are skipped. restartAllActiveWorkflowRuns() does that for every active run of a workflow.

Two things were missing around it.

  • The restart wasn’t automatic. It had to be called for each stopped run, and finding those runs was up to us.
  • Mastra 1.4x did not ensure a resume was picked up by only one server. A run whose server died and a run that is still going on another server both say running, and restart-all restarts both. A server that stalls for a while (a long GC pause, a blocked event loop) can also wake up and carry on with a run that another server already picked up.

rekindle adds those two things: it notices which runs have actually been abandoned, and makes sure only one server resumes each of them.

How it works

Everything lives in the Postgres that Mastra already uses, in two tables next to Mastra’s own: rekindle_instances and rekindle_run_owners.

Three servers running Mastra and rekindle, all sharing one Postgres that holds the Mastra tables and the two rekindle tables

Heartbeats

Every server process writes a heartbeat to rekindle_instances every 5 seconds. It’s one row per process with a timestamp.

A heartbeat older than 20 seconds means that process is dead. That’s the only way rekindle decides something is dead. A process that gets kill -9’d or loses its machine can’t say goodbye, so rekindle doesn’t wait for one.

Three servers heartbeating every 5 seconds; server C stops and is counted dead after 20 seconds

Owners

Every run of an opted-in workflow gets one row in rekindle_run_owners saying which process owns it. The row is the lock. Only the process named in it may run that run’s steps.

The guard

Each step starts with one line:

const ownership = rekindleWorkflow('scoutRun')

const validate = createStep({
  id: 'validate',
  inputSchema, outputSchema,
  execute: async ({ inputData, runId }) => {
    await ownership.guard(runId)
    // ... the step's work ...
  },
})

The guard takes the row if nobody owns the run, keeps it if this process already owns it, and takes it over if the owner is dead. If a different process owns it and that process is alive, the guard throws and the step stops.

That last case is the stalled server. Say server A freezes for a minute. Its heartbeat goes stale, B claims the run and resumes it. When A wakes up and reaches its next step, the guard finds B in the row with a fresh heartbeat, and A stops there.

Server A stalls after step 1; server B claims the run and starts step 2; when A wakes up, the guard stops it because B owns the run

A guard can also run a few seconds after the owner died, before its heartbeat has gone stale. So before giving up, the guard retries for a little longer than the stale window. A dead owner goes stale inside that time. A live one doesn’t.

The sweep and the claim

Every 10 minutes or so, each server sweeps. It lists the running and waiting runs of the opted-in workflows and tries to claim each one.

A claim is one SQL statement:

UPDATE rekindle_run_owners
   SET owner_instance_id = $me, claimed_at = now(), restarted_at = now(),
       attempts = attempts + 1
 WHERE workflow_name = $1 AND run_id = $2
   AND done_at IS NULL
   AND attempts < 3
   AND (owner_instance_id IS NULL OR owner_instance_id IN (
         SELECT instance_id FROM rekindle_instances
          WHERE heartbeat_at < now() - interval '20 seconds'))
   AND EXISTS (SELECT 1 FROM rekindle_instances
                WHERE instance_id = $me
                  AND heartbeat_at >= now() - interval '20 seconds')

It only matches if the run’s owner is dead or has let go, the run isn’t done, it hasn’t been restarted 3 times already, and the server making the claim is alive itself. The heartbeat checks run inside the same statement, against Postgres now(). There’s no gap between checking and taking, and the servers’ own clocks don’t matter.

When five servers sweep at the same moment, all five send this. Postgres gives the row to one of them, and the other four update 0 rows and move on. The one that got the row calls restart().

Servers B, C and D all claim run 42 at once; B wins and calls restart(), C and D get 0 rows and skip

A few details around the sweep:

  • The first sweep waits 30 seconds after boot, plus some jitter. In a deploy the old servers go down first, and their heartbeats need to go stale before anyone can take their runs.
  • Sweeps are jittered, so servers don’t all sweep in the same second.
  • A sweep restarts at most 25 runs. After a big outage the backlog goes out over a few sweeps instead of all at once.
  • A run with no owner row at all is only claimed once Mastra itself hasn’t updated it for 20 seconds. That covers a run whose first step hadn’t reached its guard yet.

Finishing and shutting down

The last step calls ownership.clear(runId), which marks the run done. It’s a mark, not a delete. Mastra saves the run’s final status a moment after the last step returns, and until then the run still shows as running. The mark stops a sweep from picking it up in that gap.

On SIGTERM a server stops claiming new runs but keeps heartbeating. The runs it’s still finishing don’t get taken over while it shuts down.

What resuming actually reruns

A resumed run starts the interrupted step again from the top. Steps that finished before the crash don’t run again. So every step has to be safe to run twice: read its inputs again, and write in a way that doesn’t duplicate.

Server A finishes step 1 and crashes halfway through step 2; server B skips step 1, starts step 2 over from the beginning, then finishes step 3

Try it

The repo has a demo that does the whole thing on your machine. Two servers share one Postgres. Server A starts a three-step run and gets kill -9’d in the middle of the slow step. Server B finishes it.

git clone https://github.com/onkarhoysala/mastra-rekindle
cd mastra-rekindle
npm install
npm run db:start
DATABASE_URL=postgres://postgres@localhost:54329/postgres npx tsx examples/basic/demo.ts

db:start starts a throwaway Postgres on port 54329 from a local install. You can point DATABASE_URL at any Postgres instead.

Trimmed output:

  0.7s  [A] RUN_STARTED 4e5497a1
  0.7s  [A] step gather start
  2.7s  [A] step gather end
  2.7s  [A] step slow start
  5.7s  [A]   slow ... 3/10
  5.9s  --- kill -9 A (mid step "slow")
  5.9s  --- starting instance B
 11.5s  [rekindle] resuming abandoned run { workflow: 'demoRun', instanceId: 'B-fe9d48' }
 11.5s  [B] step slow start
 21.6s  [B] step slow end
 21.6s  [B] step publish start
 22.6s  [B] step publish end

step log for run 4e5497a1
  gather   start  on A
  gather   end    on A
  slow     start  on A
  slow     start  on B
  slow     end    on B
  publish  start  on B
  publish  end    on B

PASS: resumed on B at the interrupted step, gather not re-run

A runs gather, starts slow and gets killed 3 seconds in. B boots, and its sweep claims the run once A’s heartbeat is stale. The demo uses short timings (a 4 second stale window and a 3 second sweep) so it finishes in about 20 seconds. B runs slow again from its start, then publish. gather doesn’t run again.

Adding it to your app

In each workflow, register it once, guard every step, and clear in the last one:

import { rekindleWorkflow } from 'mastra-rekindle'

const ownership = rekindleWorkflow('myWorkflow')  // same key as in new Mastra({ workflows })

// first line of every step
await ownership.guard(runId)

// in the last step
await ownership.clear(runId)

Use the runId that Mastra passes to execute. Don’t guard on a field from your input, even one called runId. If you start runs with your own ids, the two can differ, and then the guard protects a run the sweep never looks at.

When the server boots:

import { createRekindle } from 'mastra-rekindle'

const rekindle = createRekindle({ mastra })  // uses Mastra's Postgres pool, schema and logger
await rekindle.migrate()
await rekindle.start()

process.on('SIGTERM', async () => {
  rekindle.drain()
  await yourShutdown()
  process.exit(0)
})

On Mastra versions that have the recovery option (eg 1.78), also set recovery: { workflows: 'off' }. Otherwise Mastra restarts every active run on every boot, alongside rekindle.

Limits

  • It’s Postgres only.
  • Resume is per step. A step interrupted halfway reruns from its start, so steps have to be safe to run twice.
  • The guard only checks at the start of a step. If a live server can’t heartbeat for 20 seconds (pool exhausted, a long database failover), another server takes its runs and the step it was in the middle of runs twice. Giving rekindle a small pool of its own helps.
  • A step without a guard isn’t covered while it runs. An agent passed straight to createStep, a .map or a nested workflow needs wrapping in a step that guards.
  • A hung step on a live server isn’t detected.
  • On the first rollout, runs that were already in flight have no owner row yet. If Mastra hasn’t updated one for 20 seconds, it can be restarted.

npm install mastra-rekindle. The code, tests and docs are on GitHub. It’s for Mastra 1.46 to 1.83. On 1.84 or later, use Mastra’s own recovery.