Skip to content

DocsGuides

Registering a flow up front

View as Markdown

Optionally, describe a flow once and let Zigbongo route each step. The SDK keeps your definition, so if a call fails it takes the person through the rest of the flow with your default choices.

Step by step or registered

You don't have to register anything. Step by step, your code keeps its own routing and calls decide wherever it has a real choice; a flow exists the first time you ask about it (Sessions and outcomes).

Registering suits a flow with many steps, such as a quiz or an onboarding, when you'd rather describe it once:

  • Zigbongo checks the definition when you register it: a cycle, a missing default or a step that points to a node that doesn't exist is refused.
  • Zigbongo routes each step, including answer-based routing, optional steps and the order of a set of questions, and returns each option's payload with its step.
  • Your current rules for who sees what can be the starting point.
  • The SDK keeps the definition, so a failure mid-flow still takes the person to the end, with your default choices.

Both ways share the same learning, outcomes and reports. Keep the node and option keys the same and what was learned carries over between them.

A definition

// flows.js
export const quizFlow = {
  key: "onboarding-quiz",
  objective: { direction: "maximize", window: "P1D", aggregate: "sum" },
  holdoutPercent: 5,
  start: "q_goal",
  nodes: [
    {
      key: "q_goal",
      type: "variant",
      options: [
        { key: "v1", default: true, payload: { title: "What's your goal?" } },
        { key: "v2", payload: { title: "What brings you here?" } },
      ],
      next: { byAnswer: { lose_weight: "route" }, else: "lifestyle" },
    },
    {
      key: "route",
      type: "branch",
      options: [
        { key: "diet", to: "lifestyle", default: true },
        { key: "fitness", to: "q_injury" },
      ],
    },
    {
      key: "q_injury",
      type: "variant",
      optional: { default: "include" },
      options: [{ key: "short", default: true }, { key: "detailed" }],
      next: "lifestyle",
    },
    {
      key: "lifestyle",
      type: "sequence",
      items: [{ key: "sleep" }, { key: "stress" }, { key: "activity" }],
      defaultOrder: ["sleep", "stress", "activity"],
      next: "pitch",
    },
    {
      key: "pitch",
      type: "variant",
      options: [{ key: "fitness" }, { key: "healthy_eating" }, { key: "general", default: true }],
      defaultRules: [{ when: { goal: "lose_weight", age: [30, 45] }, option: "healthy_eating" }],
      next: null,
    },
  ],
};

The flow:

Field Required Meaning
key yes The flow's key, the same as in the URL
objective.direction yes maximize or minimize
objective.window no The attribution window, an ISO 8601 duration; P1D by default
objective.aggregate no How a session's outcomes add up: sum (default), max or last
holdoutPercent no The flow holdout; 5 by default
explorationFloor no The share of traffic each option keeps until it's confidently beaten; 0.02 by default
start yes The first node's key
nodes yes The nodes, which must not form a cycle

The node types:

type Decides Fields
variant Which version of a step to show options, next
branch Which node comes next options, each with to (a node key, or null to end)
sequence Which item of a set comes next, until all are shown items, defaultOrder, next
  • Every node has a unique key and may have optional: { default: "include" | "skip" } and its own holdoutPercent.
  • Options of a variant or branch node: exactly one has default: true, the option your own flow would show. A payload can be anything; it comes back with the step.
  • next is a node key, null for the end, or answer routing: { byAnswer: { "yes": "q_injury" }, else: "q_goal" }. It's required, so a forgotten field isn't read as the end, and byAnswer needs else. Zigbongo follows answer routing; it never optimizes it.
  • defaultRules on a variant or branch node are your current rules for its default, top to bottom: the first rule whose every test the session's inputs pass gives the default, else the option marked default. A test is an exact string or boolean, or [min, max] for numbers, bounds included, null for an open end. A missing or null input passes nothing, and "30" isn't a number.

A definition that can't be used is refused with 400 invalid_flow, naming every problem and its node. A request body is at most 2 MiB, about 20,000 small nodes.

How each node runs

  • Variant: Zigbongo picks the option, then follows next, by the answer you report where it routes by answer.
  • Branch: Zigbongo picks the option and goes where its to leads.
  • Sequence: one step per item, each chosen among the items not yet shown; the first pick and each later position are learned on their own. When all are shown, next follows, by the last item's answer.
  • Optional node: Zigbongo first decides whether to include it. Skipped, it costs no round trip: the flow carries on as if the node had been shown and not answered (next, or its else; a branch goes where its default option leads). A start can end at once when every node is skipped.
  • Default rules set each decision's default: people in the holdout, or in a paused flow, get the rule's option, and learning starts from it.
  • Answers route as their JSON text: a string as it is, a number or boolean as written in JSON (3, true).

Versions

  • Each distinct definition is a version, numbered 1, 2, 3 in the order first registered. Registering the same content again returns the existing version; registering an earlier one makes it current again.
  • A start that sends a definition Zigbongo already has runs on that version and changes nothing: it doesn't make it current or set the flow's settings again. Only registering, or a start with content Zigbongo hasn't seen, makes a version current. So servers running different definitions during a deploy don't switch the current version back and forth.
  • Registering new content, with register() or at a start, counts once more against the other rate-limit allowance (Retries and rate limits).
  • A session stays on the version it started on.
  • Registering sets the flow's goal, window, aggregate, holdout and exploration floor to the definition's, defaults included, every time. A change made on the dashboard or with PATCH lasts only until the next registration, so the dashboard shows a registered flow's settings without offering to change them. The flow's retention period isn't part of a definition.

Register, start and next in Node.js

import { Zigbongo } from "@zigbongo/sdk";
import { quizFlow } from "./flows.js";

const zb = new Zigbongo({ apiKey: process.env.ZIGBONGO_KEY, baseUrl: "https://zigbongo.com" });
const quiz = zb.flow(quizFlow); // once, at module scope; sends nothing

// At deploy or startup: throws a ZigbongoError with code "invalid_flow" for a bad definition.
const { version, created } = await quiz.register();

// In a request handler:
const run = await quiz.start(user.id, { inputs: { platform: "ios", age: 34 } });
render(run.step); // { node, option, payload, arm, fallback, decisionId }; null once done
req.session.quiz = run.state; // plain JSON

// In the next request:
const again = quiz.resume(req.session.quiz);
const step = await again.next({ result: { answer: "lose_weight" }, inputs: { goal: "lose_weight" } });
if (step === null) showResults();
else render(step);
req.session.quiz = again.state;

// Later, by session (or by subject if the start fell back):
await again.outcome(49.0, order.id);
  • zb.flow(definition) keeps a copy of the definition. Create it once per process, so it remembers the version.
  • register() registers the definition (PUT /v1/flows/{flowKey}) and returns { version, hash, created, createdAt, registeredAt }; created is false when the same content was registered before. It isn't retried and throws on failure, which is what you want at deploy.
  • start(subjectId, { inputs, segment }) sends the definition with it until the client knows its version, from register() or an earlier start, then the version only. Without register(), the first start of each process registers a changed definition within its 150 ms budget, and can fall back. segment is a shorthand for the input segment; send one or the other.
  • next({ result, shown, inputs }) reports the step and gives the next one, or null at the end. result.answer drives byAnswer. Pass shown: false when you didn't show the step: it isn't learned from, though the route still follows Zigbongo's choice. inputs add to the session's.
  • run.state and resume(state) carry a run across requests as plain JSON. run.done is true once step is null.
  • abandon() ends the run when the person leaves, and never throws. A registered session with no call for 30 minutes counts as abandoned at its last step; a step after that is refused, and the SDK carries on with your default choices.

The same in PHP

Under PHP-FPM a client lives for one request, so register at deploy and pass the version register() returned to flow(). Starts then send only the version. Without it, each start sends the whole definition: that works too, since a start with a definition Zigbongo already has runs on its version and changes nothing, but every request carries the definition, and only register() makes it the current version.

use Zigbongo\Zigbongo;

$zb = new Zigbongo(apiKey: getenv('ZIGBONGO_KEY'), baseUrl: 'https://zigbongo.com');
$definition = require __DIR__ . '/flows/quiz.php'; // arrays, or JSON text

// At deploy: throws a ZigbongoException (errorCode "invalid_flow") for a bad definition.
$version = $zb->flow($definition)->register()->version;

// In a request:
$quiz = $zb->flow($definition, version: $config['quiz_version']);
$run = $quiz->start($user->id, inputs: ['platform' => 'ios', 'age' => 34]);
render($run->step()); // node, option, payload, arm, fallback, decisionId; null once done
$_SESSION['quiz'] = $run->state();

// In the next request:
$run = $quiz->resume($_SESSION['quiz']);
$step = $run->next(result: ['answer' => $_POST['answer']], inputs: ['goal' => $_POST['answer']]);
$step === null ? showResults() : render($step);
$_SESSION['quiz'] = $run->state();
  • Give flow() only the version register() returned for exactly this definition. A version Zigbongo doesn't have falls back, and the next start sends the definition.
  • Write the definition as ordinary arrays: where Zigbongo reads an object (byAnswer, a rule's when), the SDK sends one. A payload is sent as you give it, so [] stays an array; use new \stdClass() or JSON text for {}.
  • A float answer routes as PHP sends it: 3.0 routes as "3.0", 3 as "3".

When a call fails: the rest of the flow with your default choices

start() and next() never throw. On a timeout (150 ms), when Zigbongo can't be reached, or on an error answer, the SDK reports the fallback, so Zigbongo forgets every decision that call made, and from there follows your definition's defaults to the end without calling Zigbongo again:

  • optional nodes at their optional.default;
  • defaultRules on the inputs so far, else the option marked default;
  • a sequence's items in defaultOrder;
  • next by the answer you report, and a branch where its default option leads.

These steps have fallback: true, arm: "fallback" and no decisionId, and run.fallback is true. They're the same steps your customers see while a flow is paused. So keep the definition in your code: the SDK needs it to fall back.

After a deploy that changes the definition, a run you resume carries on with the version Zigbongo started it on, but a fallback would follow the new definition, so change a live definition with care. More on fallbacks: Fallbacks and timeouts.

Over HTTP

Call Body Answer
PUT /v1/flows/{flowKey} The definition 201 for a new version, 200 for one registered before
POST /v1/flows/{flowKey}/sessions { subjectId, version or flow, inputs, segment } 201 { sessionId, version, arm, step, done }
POST /v1/sessions/{sessionId}/steps { decisionId, shown, result, inputs, state } { step, done }
POST /v1/sessions/{sessionId}/events { "type": "abandoned", state } { sessionId, status, node, endedAt }

version is a number, or "latest" for the version registered last, which is the default. Send an Idempotency-Key header with each start and step so a fallback can be reported against it. state is the run as you keep it, at the step reported. The API reference has the details.

For AI assistants and agents: every docs page is plain Markdown at its address with .md (this one is /docs/registered-flows.md), and llms.txt lists them all.