OrbitsDocs
esc
    Open Orbits
    In your appWorkflows

    Workflows

    Durable workflows in your own code with `@useorbits/workflows`. Steps that save their results, retry on failure, survive crashes and deploys, sleep for days or wait for an event, with every run on the project's Workflows tab.

    What a workflow is

    A workflow is a function in your app made of steps. Orbits keeps each run and calls your app for one step at a time. When a step finishes, its result is saved; when the run carries on, finished steps answer from their saved results, so the run picks up where it left off, after a crash, a deploy or a week's sleep. You don't run a queue or a server of your own for it.

    Each run shows on the project's Workflows tab, with every step's time, result and error, and Run now, Retry and Cancel.

    1. Install

    Terminal
    $ npm install @useorbits/workflows

    2. Write a workflow

    workflows/sync-stock.ts
    import { workflow } from "@useorbits/workflows";
    
    export const syncStock = workflow(
      "sync-stock",
      { schedule: "*/15 * * * *", description: "Pulls the supplier feed into inventory" },
      async ({ input, step, sleep }) => {
        const rows = await step("fetch-supplier-feed", () => fetchFeed());
        const valid = await step("parse-csv", () => parse(rows));
        await step("update-inventory", () => updateStock(valid));
        if (valid.skipped.length) {
          await step("notify-slack", () => notify(valid.skipped));
        }
        await sleep("1 hour");
        await step("write-report", () => writeReport(valid));
      },
    );

    Each step() runs its function once. Its return value is saved, and from then on the step returns that.

    OptionDefault
    descriptionA line on the Workflows tab
    scheduleA five-field cron, in UTC
    eventThe event that starts it. Use this or schedule, not both
    retries2Attempts after the first, for each step, up to 10

    When a step fails

    A step that throws is tried again with backoff: after 10 seconds, then a minute, then 5 minutes, up to retries times. While it waits, the step shows Running with its last error and when the next attempt is due. After the last attempt the run fails. Retry failed step on the run's page starts it again from that step.

    3. Serve it

    Orbits runs your workflows through one endpoint in your app, /.well-known/orbits/workflows. In Next.js:

    app/.well-known/orbits/workflows/route.ts
    import { serve } from "@useorbits/workflows";
    import { syncStock } from "@/workflows/sync-stock";
    import { sendOrderEmails } from "@/workflows/send-order-emails";
    
    export const { GET, POST } = serve([syncStock, sendOrderEmails]);

    serve() returns standard Request to Response handlers, so mount them at the same path in any framework that takes those, such as Elysia, Hono or SvelteKit:

    TypeScript
    const { GET, POST } = serve([syncStock]);
    app.get("/.well-known/orbits/workflows", ({ request }) => GET(request));
    app.post("/.well-known/orbits/workflows", ({ request }) => POST(request));

    Only Orbits reaches this endpoint. Orbits' edge keeps the path off the internet on every address, and each call carries your deployment's ORBITS_WORKFLOWS key, which Orbits sets for you and the package checks.

    Deploy to production. Once the deployment is live, Orbits reads its list of workflows from this endpoint, and they appear on the Workflows tab. A project's workflows are always those of its latest production deployment.

    Start a run

    HowSet it withIts input
    A scheduleschedule: "0 2 * * *", a five-field cron in UTC{}
    An eventevent: "order.paid", then trigger("order.paid", data) from your codedata
    By handRun now on the Workflows tabThe JSON you type
    TypeScript
    import { trigger } from "@useorbits/workflows";
    
    await trigger("order.paid", { order: order.id, email: order.email });

    A schedule starts at most one run of a workflow a minute. Runs belong to production: an event sent from a preview or from your machine is accepted and does nothing.

    Sleep and wait for events

    TypeScript
    const sendOrderEmails = workflow("send-order-emails", { event: "order.paid" }, async ({ input, step, sleep, waitFor }) => {
      await step("send-receipt", () => sendReceipt(input.order));
      const shipped = await waitFor<{ tracking: string }>("order.shipped", { timeout: "3 days" });
      if (shipped) await step("send-tracking", () => sendTracking(input.order, shipped.tracking));
      await sleep("7 days");
      await step("ask-for-review", () => askForReview(input.order));
    });
    • sleep() takes "30s", "15 minutes", "2 hours", "1 day" or milliseconds.
    • waitFor(event) resumes when trigger(event, data) is sent, and returns data. If its timeout passes first, it returns null.

    Neither holds a server open: the run is simply called again when it's time.

    The one rule: same steps, same order

    A run resumes by running your function again from the top, with finished steps answering from their saved results. So the code outside steps must reach the same steps in the same order every time. Put anything that can change inside a step: the clock, randomness, reading a database or an API.

    TypeScript
    // Don't: a different answer on each replay
    if (Math.random() < 0.5) await step("a", doA);
    
    // Do: decided once, inside a step
    const pick = await step("pick", () => Math.random() < 0.5);
    if (pick) await step("a", doA);

    If a run's steps come back in another order, for example because you deployed code that changed under a running workflow, the run fails with an error that says so, rather than guessing. A run uses whichever deployment is production when it's called, so keep that in mind when you change a workflow that has long sleeps.

    Runs: the Workflows tab

    The tab lists each workflow with its trigger ("Every 15 minutes", "When order.paid happens"), its last run and its success rate over the last 7 days, then Recent runs, the 50 newest.

    A run is Running, Succeeded, Failed or Canceled. Open one to see its trigger, who started it, the deployment it ran on, its input and output, and each step:

    Step state
    RunningUnderway, or waiting for its next attempt after an error
    SucceededDone; its result is saved
    FailedOut of attempts
    WaitingA sleep or a waitFor not over yet, or a step this run hasn't reached
    SkippedA step the run never reached because it failed or was canceled
    CanceledStopped by Cancel run

    Steps the run hasn't reached yet are shown from the workflow's last successful run, so you can see what's still to come.

    • Run now starts a run on production with the input you give (any JSON, up to 256 KB). It's picked up within seconds. It needs a production deployment that lists the workflow.
    • Cancel run stops a running run. Your app isn't called for it again; a step already running finishes, and its result is dropped.
    • Retry failed step carries a failed run on from the step that failed, with a fresh set of attempts. Earlier steps keep their results.

    Owners, admins and members can run, cancel and retry. Viewers can look.

    Try it locally

    runLocally() runs a workflow to the end in your own process: steps run once each, sleeps are skipped, and waitFor() gets the events you pass. It's handy in tests.

    TypeScript
    import { runLocally } from "@useorbits/workflows";
    
    const result = await runLocally(sendOrderEmails, { order: "ord_1" }, { events: { "order.shipped": { tracking: "GIG-1" } } });
    // { state: "succeeded", output: …, steps: [...] }

    Limits

    A step's result256 KB at most, as JSON
    A run's input, an event's data256 KB at most
    A step's time5 minutes to finish
    Retries per stepUp to 10 (2 by default)
    Event namesLetters, digits and . _ : -, starting with a letter or digit, up to 100 characters

    What the package calls

    trigger(name, data) sends POST /v1/workflows/events with the deployment's key as Authorization: Bearer owf_… (from ORBITS_WORKFLOWS, not an API token):

    JSON
    { "name": "order.paid", "data": { "order": "ord_1", "email": "ada@example.com" } }

    It starts every workflow the production deployment lists with that event, with data as the input, and wakes runs waiting for it in waitFor. The answer is 202, with what it started and woke. A wrong key is 401. This call doesn't count against the API's rate limits.

    From the CLI and the API

    Terminal
    $ orbits workflows ls$ orbits workflows run send-digest --input '{"week":45}'$ orbits workflows runs$ orbits workflows retry <run id>

    The web app's calls are GET /v1/teams/{team}/projects/{project}/workflows, POST .../workflows/{workflow}/runs, GET .../workflows/runs/{run}, and POST .../runs/{run}/cancel and .../retry. See API › Workflows.

    Was this page helpful?

    Updated