One Engine for Branching KYB

I built a typed flow engine as luca Operator's fixed three-step onboarding evolved into a branching KYB journey with more than a dozen possible steps. Steps define screens and transitions, supplying request data and review views where needed; the engine rebuilds the active path when an earlier answer changes and preserves cached form values.

  • React Native
  • TypeScript
  • Zod

At a glance

The starting point

The original self-onboarding had three named stages: personal information, business information, and password. Its screen selected forms through a numeric OnboardingStep; its context repeated that knowledge in onNext and onBack branches and read the forms directly to construct the API request. Adding a screen meant considering rendering, validation, ordering, request mapping, and error handling in several places. The new KYB requirements called for more than a dozen possible steps branching on business type, optional details, and sign-in mode; a user’s route would include the steps selected by their answers.

KYB made that structure particularly fragile. A sole proprietor follows a different path from a partnership or an organization. A business may or may not have another public name or operating address. SSO registration may finish at review while another route needs a password screen. These are transitions determined by answers, not positions in a fixed list.

Step contract and graph

A step is a typed object with a screen factory and nextStep(blackboard) at its core: the current step receives the decision state and returns the next step, or ends the flow. Optional functions say how validated screen data updates that state, which partial fields it contributes to the final request, and how to render a compact reviewSummary from that step’s own cached data. A step can also handle a returned validation error. It carries an analytics name and may provide a progress estimate.

The contract is ConditionalFormStep<TBlackboard, TBuildData, TStepData>. Its three type parameters define the decision state, the output model, and the screen’s own form data. The KYB flow supplies its own types through aliases. The contract itself contains no KYB field names and does not force all screens into one form type.

The KYB definition is a graph of small step objects in one file, rather than a literal ordered array. Most steps point to a single successor. The few conditional transitions express the actual product rules: organization type selects a business path; answers about another name or address include or skip those screens; SSO status determines whether the password step is needed. Changing a branch means changing the transition where that decision belongs. The runtime does not need a central switch over every KYB screen.

This shortened example shows two distinct forms on the sole proprietor path: personal details followed by business details. FlowState and RequestBody stand for types supplied by the flow; they are not built into the engine:

type Step<Data> =
  ConditionalFormStep<FlowState, RequestBody, Data>;

const personalDataStep: Step<PersonalFormValues> = {
  screen: props => <PersonalDataForm {...props} />,
  nextStep: () => businessDataStep as Step<unknown>,
  reviewSummary: data => <PersonalSummary data={data} />,
  buildUnifiedData: data => ({ email: data.email }),
  trackingEventName: 'personal_data',
};

const businessDataStep: Step<BusinessFormValues> = {
  screen: props => <BusinessDataForm {...props} />,
  nextStep: () => reviewStep as Step<unknown>,
  reviewSummary: data => <BusinessSummary data={data} />,
  buildUnifiedData: data => ({
    businessName: data.companyName,
  }),
  trackingEventName: 'business_data',
};

The two steps own different screens, request mappings, and small review views. The preceding organization-type step decides whether this path is taken; these forms do not repeat that branch decision. A terminal step returns undefined from nextStep. The casts at graph edges reflect the different form types of its screens; each step’s own data remains typed within its definition.

How the domain step and the engine exchange data
flowchart TB
  Step[Domain step: screen, nextStep, review, request]
  Screen[Encapsulated screen]
  Blackboard[Blackboard: facts that decide the route]
  Cache[Engine form cache: step identity to untyped values]
  History[Visited step stack: active path]
  Builder[Request builder: run each active step's projection]
  Request[Validated API request]
  Step -->|opens| Screen
  Screen -->|validated form values| Cache
  Step -->|selected decision facts| Blackboard
  Blackboard -->|read by nextStep| Step
  Step -->|visited| History
  History -->|select steps| Builder
  Cache -->|restore values for those steps| Builder
  Step -->|buildUnifiedData function| Builder
  Builder -->|merge and validate| Request

The cache has no knowledge of a screen’s form type. The step that owns that screen knows how to read its cached values and project them into request fields; the builder coordinates those projections for the active path.

How the engine runs the flow

The blackboard contains facts needed to choose a route, such as organization type, optional name or address answers, and SSO status. It is intentionally separate from the full form values. After a screen validates its input, the step may add selected facts to the blackboard. Only then does the runtime ask nextStep for the successor.

The full form values are cached by step identity, while a stack records the visited steps. The cache itself does not need to understand each form’s value type. The engine uses the same step-owned interface in both directions: it supplies cachedData when opening a screen and later passes the stored values to that step’s reviewSummary and buildUnifiedData functions. Other steps do not read or interpret one another’s form data.

Review, edit, and rewind

The review near the end is itself a step. Its screen takes the visited-step stack, selects the entries that provide reviewSummary, and calls each summary with that step’s cached data. Those small, step-owned views compose the review page. The review does not contain a separate switch over form types or a second hand-written list of fields. Each summary has an edit action that finds its step’s index in the visited history and opens that step, regardless of its position. For SSO the review can be the last step; other paths continue to the password step.

After the edited screen validates, the engine updates its cache and blackboard, then walks nextStep(blackboard) again to project the remaining route. If the projected sequence of step identities still matches the visited stack, the user returns directly to the end of the completed path, normally the review step. The condition is route equality, not literal equality of every blackboard value.

If the projected route differs, the engine truncates the visited stack after the edited step and resumes at its newly resolved successor. The user then moves through the remaining screens in the new route. The cache is not truncated: a screen encountered again receives its previous values through the same cachedData interface, so it can prepopulate its form. The engine cannot safely jump straight to review when the future sequence has changed. Only steps in the rebuilt active path contribute to the final request.

For example, changing the business type from sole proprietor to organization selects a different business path. The earlier path leaves the active history; shared screens can reuse cached answers when encountered again, while the final request draws data from the new path.

Editing a step from the review
flowchart TB
  Review[Review: summaries of visited steps]
  Edit[Open any visited step by history index]
  Update[Validate and update blackboard and cache]
  Project[Project nextStep chain again]
  Same{Same step sequence?}
  Return[Return directly to review]
  Trim[Truncate history after edited step]
  Walk[Walk the new route through forms]
  Kept[Cache retained: revisit with saved values]
  Review --> Edit --> Update --> Project --> Same
  Same -->|yes| Return
  Same -->|no| Trim
  Trim -->|keep cached values| Kept
  Kept -->|prefill revisited screens| Walk

Building the request

Each relevant step has a small buildUnifiedData function that maps its validated, cached values to a partial output object. At submission, the runtime applies those functions to the steps on the active path, deep merges their contributions, and validates the resulting object against the onboarding schema. A separate submission hook sends the validated request to the app’s API, including the appropriate route for SSO registration.

This separation matters: the blackboard answers which screen comes next; the request builder answers what the visited screens collected. The request does not have to be assembled by reaching into every form from one large submission function. The step definitions also support review summaries, analytics, and routing applicable backend validation errors back to an editable screen.

Engineering result and trade-offs

The delivered design gives the KYB flow one readable definition of its branches and a shared mechanism for navigation, restoration, review edits, and request construction. Its typed contract and core algorithms operate on step objects, so the engine is substantially decoupled from KYB. The current React provider still wires in the KYB starting step, blackboard alias, schema, submission hook, and error mapping. Making the engine fully application agnostic would require extracting those inputs.

Step identity is used for caching and history comparisons, so step objects must remain stable. A changed branch needs careful handling of history and cached values. Deep merging partial request objects requires deliberate ownership when two steps can write the same field.