Ignitify.dev
Tutorials

Pass state between runs

A run does not see the run before it. First you send the last result as the next payload, so a counter goes on from 1 to 2 to 3 and a failed run changes nothing. Then you keep a counter in the memory of a warm VM and see when it is lost. Last, you keep it in your own database, with compare-and-set, so two runs at once lose no update.

nodestatepayloadwarm-vmdatabaseabout 45 minStarter tier

What this tutorial proves

  • A run's result can be the next run's input. The platform keeps every result, and you read the newest one that completed.
  • A failed run saves no new state, so the next run goes on from the last good one.
  • This way has limits: two runs at once read the same state, and a deleted run drops out.
  • A task that keeps state in memory can reuse it on a warm VM, but only as a cache, and only for runs one after another.
  • Runs that start at the same time get their own VMs and do not share that memory.
  • State that runs share, or that you cannot lose, belongs in your own database. Each run reads it and writes it back with compare-and-set, so no update is lost.

Which way fits your task? See Pass state between runs. It compares three ways: the last result, a warm VM and your own database. This tutorial builds all three.

Before you start

  • The CLI, installed and signed in with your own (owner) key: ignitify login. See Install.
  • jq, for the one-line reads below.
  • Part 1 runs on any plan. Part 2 needs Starter and up: the Free plan has no warm VMs. Part 3 needs Starter and up: the Free plan has no outbound network. The tasks of parts 1 and 2 have no network.
  • Part 3 needs a database or store with an HTTPS API that you own, and a token for it.
terminal
$ ignitify login

1 · From outside: the last result is the next payload

The task returns its state as its result. Before each run, you read the newest completed result of the task and send it back as the payload. The state is at most 10 KiB.

Create the task

terminal
$ ignitify task:create counter

Replace the two starter files with these:

task.yaml
schema_version: 1
slug: counter
runtime: node
execution:
  duration: short
  network:
    type: none                  # no network: the state comes in as the payload
run:
  payload: {}
  preset: std.micro
  timeout_sec: 60
index.ts
// A counter whose state comes in as the payload. The result IS the next cursor.
// payload.fail: true fails the run on purpose, to show that a failed run saves no new cursor.

const VERSION = 1;

type Cursor = { version: number; count: number };
type Input = { version?: unknown; count?: unknown; fail?: unknown } | null;

/** The count to continue from: the payload's count when it is a cursor of this version, else 0. */
const countOf = (payload: Input): number =>
  payload?.version === VERSION && Number.isInteger(payload.count) ? Number(payload.count) : 0;

export async function run(payload: Input): Promise<Cursor> {
  const count = countOf(payload);
  if (payload?.fail === true) throw new Error(`failed on purpose; the cursor stays at ${count}`);
  console.log(`count ${count} -> ${count + 1}`);
  return { version: VERSION, count: count + 1 };
}

The task adds 1 to the count it gets, and returns the new count with a version. A payload that is not a cursor of this version starts the count at 0. With fail: true in the payload, the run fails on purpose.

terminal
$ ignitify task:validate counter
ignitify task:deploy counter

Run it three times

Read the newest completed result, then send it as the payload. Before the first run there is no result, so jq gives {}.

terminal
$ PREV=$(ignitify run:list --task-name counter --status COMPLETED --limit 1 --json | jq -c '.[0].result // {}')
ignitify task:run counter --payload "$PREV" --wait

Run the two lines three times. The results are {"version":1,"count":1}, then count 2, then count 3.

  • run:list lists the newest run first. --status COMPLETED --limit 1 gives the newest run that completed.
  • Write the status in capitals: COMPLETED. A lowercase status is refused.
  • --json prints a list of runs, and each run has its result.
  • To read one run: ignitify run:get <run-id> --json | jq .result.

A failed run keeps the last good state

terminal
$ PREV=$(ignitify run:list --task-name counter --status COMPLETED --limit 1 --json | jq -c '(.[0].result // {}) + {fail: true}')
ignitify task:run counter --payload "$PREV" --waitFAILED: failed on purpose; the cursor stays at 3
terminal
$ PREV=$(ignitify run:list --task-name counter --status COMPLETED --limit 1 --json | jq -c '.[0].result // {}')
ignitify task:run counter --payload "$PREV" --wait
CallerAPI server1run with fail: truecount: 3 + fail2run endsFAILEDnothing saved3run:list, newest completed4last resultcount: 3the run before the failure5run again with that payloadcount: 36run endsCOMPLETED: count 4savedthe statecompletedfailedCallerAPI server1run + fail: truecount: 32run endsFAILEDnothing saved3run:list, newest done4last resultcount: 35run again, same payload6run endsCOMPLETED: count 4
A failed run has no completed result, so the next read skips it.

The result is count 4. The failed run has no completed result, so the next read skips it.

  • task:run --wait exits with code 1 when the run fails. In a script with set -e, check the status yourself, or the script stops.
  • If you delete a run (run:delete), the next read goes back to the completed run before it.

The limits of this way

2 · Warm memory: keep it in the process

With state: across-runs, the task process stays alive on a warm VM after a run. The next run of the same task on that VM can read what the last run left in memory. This needs Starter and up.

Create the task

terminal
$ ignitify task:create warm-counter

Replace the two starter files with these:

task.yaml
schema_version: 1
slug: warm-counter
runtime: node
# across-runs keeps the task process on a warm VM between runs; the counter lives in its memory.
execution:
  cardinality: many
  duration: short
  state: across-runs
  network:
    type: none
run:
  payload: {}
  preset: std.micro
  timeout_sec: 60
index.ts
// A counter kept in process memory. With `state: across-runs` the task process stays alive on a
// warm VM, so the next run of this task on that VM sees the count the last run left.
// BOOT_ID is made once per process: a new boot_id means a new process, and with it a new memory.
import { randomUUID } from "node:crypto";

const BOOT_ID = randomUUID();

let count = 0; // module level: kept while the process lives

export function init(): void {
  console.log(`init boot_id=${BOOT_ID}`);
}

export async function run() {
  count += 1;
  console.log(`count ${count} boot_id=${BOOT_ID}`);
  return { count, boot_id: BOOT_ID, pid: process.pid };
}

BOOT_ID is made once per process, so a new boot_id means a new process and a new memory. cardinality: many is needed for across-runs.

terminal
$ ignitify task:validate warm-counter
ignitify task:deploy warm-counter

task:validate warns that snapshots are deferred and the task runs as a booted VM that is warm. It means the state lives only in the running process. Nothing saves it to disk.

The same state in the other runtimes. The rest of the task is the usual run:

Python
count = 0  # module level: kept while the process lives

def run(payload, ctx):
    global count
    count += 1
    return {"count": count, "boot_id": BOOT_ID, "pid": os.getpid()}
Go
var count = 0 // package level: kept while the process lives

func run(payload json.RawMessage, _ *ignitify.Ctx) (any, error) {
	count++
	return map[string]any{"count": count, "boot_id": bootID, "pid": os.Getpid()}, nil
}
Rust
let mut count: u64 = 0; // owned by the run closure: kept while the process lives
ignitify_runtime::start(
    || Ok(()),
    move |_payload: Value, _ctx| {
        count += 1;
        Ok(json!({ "count": count, "boot_id": boot_id, "pid": std::process::id() }))
    },
)

One after another: 1, 2, 3 on one VM

terminal
$ ignitify task:run warm-counter --wait
ignitify task:run warm-counter --wait
ignitify task:run warm-counter --waitcount 1, then count 2, then count 3

Start each run soon after the last one ends. All three results have the same boot_id, and run:get shows the same VM:

terminal
$ ignitify run:get <run-id> --json | jq '{vm_id, result}'

run:timeline <run-id> of the second and third run shows Started on a running VM. run:logs shows the init line in the first run only.

All at once: no sharing

terminal
$ for i in 1 2 3; do ignitify task:run warm-counter; done

Three runs that start together get three VMs, and each result has count 1. One VM runs one run at a time, so runs that start together do not share memory. Later runs can land on any of the three VMs, so each VM counts on its own.

To make runs that start together run in turn on one VM, use a bidirectional task: it runs one run at a time, and with on_busy: queue (the default) the extra runs wait and then run on the same VM. Their memory is then shared, and your task can serve it over HTTP between runs. Like all warm memory, it is best-effort. Runs that must share state you cannot lose need your own database (part 3).

Files follow the process

  • With across-runs, files that a run writes in its home folder stay while the process lives, and go with it.
  • With state: independent (the default), each run starts in a new process with an empty home folder, also on a warm VM.
  • Keep files in the home folder. The task cannot write anywhere else, for example in /run.

When the state is lost

CauseState after it
The next run starts after a short idle time (about 30 seconds today; do not depend on it)Lost: a new VM
A run fails because it throws an errorKept: the process lives on
The process ends (it exits or crashes)Lost: the VM ends with it
A run hits its time limit, or you cancel a running runLost: the VM is stopped
A new deployment (a code change, or a change of execution)Lost: a new VM

Start runs from your own code

A run that you start with POST /runs uses the settings of the deployed task.yaml, the same as task:run. A field you send in the call (execution, preset, timeout_sec) wins for that run. So a call with only the payload lands on the warm VM, like the runs above.

3 · Own database: state that runs share

State larger than 10 KiB, state you cannot lose, or state that runs started together must share belongs in your own database. Each run reads it, changes it, and writes it back with compare-and-set: the write succeeds only if nobody wrote since the read. If somebody did, read again and try again.

This example keeps a counter in a key-value store with an HTTPS API. GET /kv/<key> answers {value, version}. PUT /kv/<key> with {value, if_version} writes only when the stored version is still if_version, and answers 409 if not. Use the same steps with your database's HTTPS API.

Create the task

terminal
$ ignitify task:create shared-counter
printf 'https://db.example.com' | ignitify secret:set KV_URL --stdin
ignitify secret:set KV_TOKEN --stdin < my-token.txt

Replace db.example.com with the host of your own store, here and in egress_allow. Replace the two starter files with these:

task.yaml
schema_version: 1
slug: shared-counter
runtime: node
secrets: [KV_URL, KV_TOKEN]     # the store's address and token, never in the code
execution:
  cardinality: many
  duration: short
  network:
    type: egress
    egress_allow: [db.example.com]   # HTTPS only, port 443
run:
  payload: { key: my-counter }
  preset: std.small
  timeout_sec: 120
index.ts
// A counter in your own store, over its HTTPS API, with compare-and-set.
// Secrets: KV_URL (https://<host>), KV_TOKEN. Payload: key (required), sleep_ms (optional, 0-30000):
// a hold between the read and the first write, to see two runs collide.
interface Ctx { secrets?: Readonly<Record<string, string>> }
type Input = { key?: unknown; sleep_ms?: unknown } | null;
type Entry = { value: number; version: number };
type Reply = { status: number; body: unknown; busyRetries: number };

const MAX_CONFLICTS = 10;
const MAX_BUSY_RETRIES = 5;
const DEFAULT_RETRY_AFTER_SEC = 1;
const MAX_RETRY_AFTER_SEC = 5;
const MAX_SLEEP_MS = 30_000;
const REQUEST_TIMEOUT_MS = 10_000;
const MS_PER_SECOND = 1000;
const KEY_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
const BUSY_STATUSES = new Set([429, 503]);
const HTTP = { ok: 200, notFound: 404, conflict: 409 };
const ABSENT: Entry = { value: 0, version: 0 };

const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms));

const secretOf = (ctx: Ctx, name: string): string => {
  const value = ctx.secrets?.[name];
  if (!value) throw new Error(`secret ${name} is not set (ignitify secret:set ${name} --stdin)`);
  return value;
};

const keyOf = (payload: Input): string => {
  const key = payload?.key;
  if (typeof key !== "string" || !KEY_PATTERN.test(key)) throw new Error(`payload.key must match ${KEY_PATTERN}`);
  return key;
};

const sleepMsOf = (payload: Input): number => {
  const value = payload?.sleep_ms ?? 0;
  if (!Number.isInteger(value) || Number(value) < 0 || Number(value) > MAX_SLEEP_MS) {
    throw new Error(`sleep_ms must be an integer in 0-${MAX_SLEEP_MS}`);
  }
  return Number(value);
};

/** Seconds to wait from a Retry-After header: its integer value, bounded; else the default. */
const retryAfterSec = (header: string | null): number => {
  const n = Number(header);
  return Number.isInteger(n) && n >= 0 ? Math.min(n, MAX_RETRY_AFTER_SEC) : DEFAULT_RETRY_AFTER_SEC;
};

/** The stored entry from a GET reply: 404 = not written yet. */
const entryOf = (reply: Reply): Entry => {
  if (reply.status === HTTP.notFound) return ABSENT;
  const body = reply.body as Partial<Entry> | null;
  if (reply.status !== HTTP.ok || !Number.isInteger(body?.value) || !Number.isInteger(body?.version)) {
    throw new Error(`store read answered ${reply.status}: ${JSON.stringify(reply.body)}`);
  }
  return { value: Number(body!.value), version: Number(body!.version) };
};

/** One HTTP call; a 429 or 503 is retried after its Retry-After, up to MAX_BUSY_RETRIES times. */
async function call(url: string, token: string, init: RequestInit, busyRetries = 0): Promise<Reply> {
  let res: Response;
  try {
    res = await fetch(url, {
      ...init,
      headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
      signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
    });
  } catch (e) {
    const cause = (e as { cause?: { code?: string; message?: string } }).cause;
    const why = cause?.code ?? cause?.message ?? (e as Error).message;
    throw new Error(
      `cannot reach the store at ${new URL(url).host}: ${why}. Is the host in execution.network.egress_allow?`,
      { cause: e },
    );
  }
  if (BUSY_STATUSES.has(res.status) && busyRetries < MAX_BUSY_RETRIES) {
    await sleep(retryAfterSec(res.headers.get("retry-after")) * MS_PER_SECOND);
    return call(url, token, init, busyRetries + 1);
  }
  const text = await res.text();
  return { status: res.status, body: text ? JSON.parse(text) : null, busyRetries };
}

export async function run(payload: Input, ctx: Ctx) {
  const base = secretOf(ctx, "KV_URL").replace(/\/+$/, "");
  const token = secretOf(ctx, "KV_TOKEN");
  const key = keyOf(payload);
  const sleepMs = sleepMsOf(payload);
  const url = `${base}/kv/${encodeURIComponent(key)}`;
  let busyRetries = 0;

  for (let conflicts = 0; conflicts < MAX_CONFLICTS; conflicts += 1) {
    const read = await call(url, token, { method: "GET" });
    busyRetries += read.busyRetries;
    const seen = entryOf(read);
    if (conflicts === 0) await sleep(sleepMs);
    const write = await call(url, token, {
      method: "PUT",
      body: JSON.stringify({ value: seen.value + 1, if_version: seen.version }),
    });
    busyRetries += write.busyRetries;
    if (write.status === HTTP.ok) {
      const stored = write.body as Entry;
      console.log(`${key}: ${seen.value} -> ${stored.value} (conflicts ${conflicts}, busy retries ${busyRetries})`);
      return { key, count: stored.value, version: stored.version, conflicts, busy_retries: busyRetries };
    }
    if (write.status !== HTTP.conflict) {
      throw new Error(`store write answered ${write.status}: ${JSON.stringify(write.body)}`);
    }
    console.log(`${key}: version ${seen.version} is stale, read again`);
  }
  throw new Error(`${key}: gave up after ${MAX_CONFLICTS} conflicts`);
}
terminal
$ ignitify task:validate shared-counter
ignitify task:deploy shared-counter

Two runs at once

terminal
$ for i in 1 2; do ignitify task:run shared-counter --payload '{"key":"my-counter","sleep_ms":15000}'; done

Both runs read the same version. One write wins (conflicts: 0). The other gets 409, reads again and wins the next round (conflicts: 1). The counter goes up by 2: no update is lost.

Clean up

terminal
$ ignitify task:delete counter --yes
ignitify task:delete warm-counter --yes
ignitify task:delete shared-counter --yes

Next steps