Skip to the content.

Recipes

Complete patterns for common jobs. Each one assumes an instance created as in the quick start:

import { createSteady } from "@solustiq/steady"
import { pgAdapter } from "@solustiq/steady/pg"

export const steady = createSteady({ db: pgAdapter(pool), tenant: "acme" })

and a process that calls steady.tick() every minute with every flow defined.

Daily report on a schedule

export const dailyReport = steady.defineFlow("daily-report", async (f, input: { team: string }) => {
  // The day the report is about, recorded once, so a resume after midnight still reports the same day.
  const day = await f.step("pick-day", () => new Date(Date.now() - 86_400_000).toISOString().slice(0, 10))
  const numbers = await f.step("query", () => loadMetrics(input.team, day))
  const html = await f.step("render", () => renderReport(numbers))
  await f.step("send", () => sendMail({ to: `${input.team}@example.com`, subject: `Report ${day}`, html }), {
    retry: { maxAttempts: 5, backoffMs: 60_000 },
  })
})

// On boot (safe to repeat: the next firing time is kept when nothing changed):
await steady.schedule(dailyReport, "0 7 * * 1-5", {
  tz: "Europe/Istanbul",
  key: "daily-report:sales",
  input: { team: "sales" },
})

What you get: one run per weekday at 07:00 Istanbul time, even with several runners or a cron that fires twice. After an outage the missed day fires once on recovery. A crash after render resumes at send without querying again. To report for several teams, call schedule once per team with distinct keys.

Why pick-day is a step: Date.now() between steps would give a different day if the run resumes after midnight. Inside a step, it is recorded once.

Approval wait with a signal from an HTTP handler

A purchase over a threshold needs a manager’s approval. The flow waits up to three days.

export const purchase = steady.defineFlow("purchase", async (f, order: { id: string; amount: number; requester: string }) => {
  if (order.amount >= 1000) {
    await f.step("ask-approval", () => notifyManagers(order))
    const decision = await f.waitForSignal<{ approved: boolean; by: string }>("decision", { timeout: "3d" })
    if (!decision || !decision.approved) {
      await f.step("reject", () => notifyRequester(order, decision ? `rejected by ${decision.by}` : "no decision in 3 days"))
      return { status: "rejected" }
    }
    await f.log(`approved by ${decision.by}`)
  }
  const po = await f.step("create-po", () => createPurchaseOrder(order.id))
  return { status: "ordered", po: po.number }
})

// Where the order is created:
await steady.start(purchase, { id: order.id, amount: order.amount, requester: user.id }, { key: `purchase:${order.id}` })

The approval endpoint. Steady has no HTTP surface: your handler decides who may send the signal, and it must authenticate the caller before calling signal.

// app/api/orders/[id]/decision/route.ts
export async function POST(request: Request, { params }: { params: { id: string } }) {
  const session = await getSession(request) // your auth: cookie session, JWT, ...
  if (!session) return new Response("unauthorized", { status: 401 })

  const order = await db.orders.find(params.id)
  if (!order || !(await canApprove(session.user, order))) return new Response("forbidden", { status: 403 })

  const body = await request.json().catch(() => null)
  if (typeof body?.approved !== "boolean") return new Response("bad request", { status: 400 })

  // Build the payload from verified facts; never forward the request body as is.
  await steady.signal({ flow: purchase, key: `purchase:${order.id}` }, "decision", {
    approved: body.approved,
    by: session.user.email,
  })
  await steady.tick({ maxRuns: 1 }) // optional: continue now instead of on the next cron tick
  return Response.json({ ok: true })
}

For one-click links in an email (no session), sign the link: put the order id, the decision and an expiry in the URL with an HMAC over them (crypto.createHmac("sha256", process.env.LINK_SECRET)), verify the HMAC and the expiry with crypto.timingSafeEqual in the handler, then signal.

Notes:

Retry with backoff

Default policy: 3 attempts, 1 s backoff doubling, capped at 5 minutes. Set a policy per flow or per step:

class NotFound extends Error {}

export const syncCustomer = steady.defineFlow(
  "sync-customer",
  async (f, input: { customerId: string }) => {
    const customer = await f.step("fetch", () => crm.getCustomer(input.customerId))
    await f.step("push", () => billing.upsertCustomer(customer), {
      retry: {
        maxAttempts: 8,
        backoffMs: 60_000,           // waits 1, 2, 4, 8, 16, 32, then 60 minutes
        maxBackoffMs: 3_600_000,     // 1 hour
        nonRetryable: (error) => error instanceof NotFound,
      },
    })
  },
  { retry: { maxAttempts: 4, backoffMs: 30_000 } }, // default for every step of this flow
)

How it behaves:

No-show handling with a re-invite

An intro meeting: create a room, invite, wait 20 minutes for the guest to join. If they do not, mark a no-show, wait two days and invite again.

export const intro = steady.defineFlow("intro-meeting", async (f, input: { email: string; slot: string }) => {
  const room = await f.step("create-room", () => meetings.createRoom(input.slot))
  await f.step("invite", () => mail.invite(input.email, room.url))
  const joined = await f.waitForSignal("joined", { timeout: "20m" })
  if (joined) return { outcome: "joined" }

  await f.step("mark-no-show", () => crm.markNoShow(input.email))
  await f.sleep("2d")
  const room2 = await f.step("create-room-2", () => meetings.createRoom("next-free-slot"))
  await f.step("reinvite", () => mail.invite(input.email, room2.url))
  const joinedLater = await f.waitForSignal("joined", { timeout: "20m" })
  return { outcome: joinedLater ? "joined-second" : "no-show-twice" }
})

await steady.start(intro, { email, slot }, { key: `intro:${email}:${slot}` })

// In the video provider's webhook (verify its signature first):
await steady.signal({ flow: intro, key: `intro:${email}:${slot}` }, "joined", { at: new Date().toISOString() })

The second wait uses the same signal name. The late-signal rule makes that safe: if the guest joins the first room 25 minutes after the invite, that joined arrives after the first deadline, is flagged late and kept in the history, and does not answer the wait two days later. A joined sent while the second wait is armed does. If you do want a late signal to count, pass acceptLate: true to the second wait.

Timeouts are measured against the signal’s creation time, not the tick: a guest who joined at minute 19 counts even if the next tick runs at minute 21.

Migrating from cron jobs

A typical cron job loops over work and keeps progress in ad hoc columns:

// before: runs every 10 minutes
for (const invoice of await db.invoices.where({ status: "due", reminded: false })) {
  await mail.reminder(invoice)
  await db.invoices.update(invoice.id, { reminded: true }) // lost if the process dies right before this
}

With Steady, the cron keeps finding work but only starts runs; the runs do the work:

export const dunning = steady.defineFlow("dunning", async (f, input: { invoiceId: string }) => {
  await f.step("reminder-1", () => mail.reminder(input.invoiceId, 1))
  await f.sleep("7d")
  if (await f.step("paid?", () => billing.isPaid(input.invoiceId))) return
  await f.step("reminder-2", () => mail.reminder(input.invoiceId, 2))
  await f.sleep("7d")
  if (await f.step("paid-again?", () => billing.isPaid(input.invoiceId))) return
  await f.step("escalate", () => collections.open(input.invoiceId))
})

// the old cron route, now every minute:
export async function GET() {
  for (const invoice of await db.invoices.where({ status: "due" })) {
    await steady.start(dunning, { invoiceId: invoice.id }, { key: `dunning:${invoice.id}` }) // no-op when started
  }
  return Response.json(await steady.tick())
}

Step by step:

  1. Keep the existing cron trigger; make its handler call tick().
  2. Turn the body of each job into a flow. Every side effect becomes a step with a stable name.
  3. Replace “did we already do this?” columns with idempotency keys on start (one run per business object and period, such as report:2026-12-01).
  4. Replace “check again later” logic with sleep, and polling for a human with waitForSignal.
  5. For jobs that only need “run at 07:00”, use schedule instead of finding work in the handler.
  6. Run old and new side by side for one cycle behind a flag, compare, then delete the old columns.

If finding work is itself expensive, put the selection in a scheduled flow that starts child runs with keys inside a step.

Sensitive step results

By default, step results are redacted before they are stored, and the flow receives the redacted value. A step that returns { accessToken } therefore gives the flow { accessToken: "[redacted]" } (the name matches token). That is deliberate: secrets should not sit in your job tables.

When a flow genuinely needs a secret from one step in a later one (an OAuth token for the next call, a signed download link to email), mark that step sensitive and configure encryption:

export const steady = createSteady({
  db: pgAdapter(pool),
  tenant: "acme",
  encryption: { key: process.env.STEADY_ENCRYPTION_KEY! }, // openssl rand -base64 32
})

export const exportData = steady.defineFlow("export", async (f, input: { userId: string }) => {
  const file = await f.step("build-archive", () => storage.buildArchive(input.userId))
  const link = await f.step("sign-link", () => storage.signedUrl(file.path, { expiresIn: "7d" }), { sensitive: true })
  await f.step("email-link", () => mail.send(input.userId, `Your export: ${link.url}`))
  return { path: file.path } // do not return the secret: outputs are redacted and stored as usual
})

What sensitive: true does:

Alternatives, in order of preference: pass a reference instead of the secret (a vault path, a record id) and resolve it inside the step that uses it; or narrow the redaction patterns (redact: { patterns: [/password|secret|authorization/i] }) if the default catches names that are not secrets in your domain, such as idempotencyKey.