← Engineering & Writing

State architecture / Design study

Reactive consistency in navigation state

How I built ownership and derivation patterns for navigation state in the intermediary portal, using Signals for synchronous relationships and RxJS for async workflows.

The intermediary portal uses Signals for navigation state (breadcrumbs, tabs, side nav) and RxJS for async workflows. The challenge: keep navigation consistent when route changes, permission updates, and async data loads happen simultaneously.

01 / Ownership

One owner per piece of state

Each navigation element has a single owner. The route owns the selected section ID. The application repository owns reusable data records. Child components receive values as inputs and emit user actions as outputs — they don't maintain independent selection state.

Problem I solved: two subscribers copying each other through effects created ordering questions. When navigation and data refresh happened together, it was unclear which update won. Solution: clear ownership boundaries. The route owns selection; the repository owns data; components are pure projections.

02 / Derivation

Compute, don't copy

Editability, visibility, and permissions are computed from current account and permission data using Angular computed signals. These are lazy and memoized — they only recompute when their dependencies change. A computed signal answers a question; it doesn't trigger operations.

Mistake I avoided: storing editability as a boolean that gets copied around. If permissions change, the copied boolean becomes stale. Instead, compute editability from the live account and permission data. The trade-off: missing inputs must be represented explicitly. A null permission means "unknown," not "false."

03 / Async boundaries

Guard result commits

When a user selects account A, then account B before A finishes loading, the response for A must not replace B's data. Each request carries the selected ID and a generation counter. When the response arrives, check both match the current owner before committing.

RxJS switchMap cancels the previous stream, but cancellation doesn't guarantee the server stopped work. An adapter might ignore cancellation; a write might already be accepted. Solution: keep an identity guard at the commit point. Old errors can't replace new success; old success can't overwrite new selection.

04 / Race conditions

Handle concurrent state changes

Navigation state changes can overlap: route transitions, permission updates, and data refreshes all modify shared state. Without explicit ordering, the final state depends on which async operation completes last — a race condition that's difficult to reproduce in testing.

Solution: serialize state mutations through a single source of truth. The route guard completes before data loads; data loads complete before UI updates. Each step waits for the previous one, eliminating timing-dependent bugs. The trade-off: slightly slower navigation, but predictable behavior.

05 / Memory management

Prevent subscription leaks

Angular components subscribe to observables for navigation state, data streams, and user actions. Without proper cleanup, these subscriptions persist after the component is destroyed, causing memory leaks and unexpected behavior.

Solution: use Angular's DestroyRef to automatically unsubscribe when the component is destroyed. For signals, computed values are automatically cleaned up when their dependencies are destroyed. The key: never store subscriptions in variables that outlive the component.

06 / Testing strategy

Verify reactive behavior

Testing reactive state requires verifying not just the final state, but the sequence of intermediate states and the timing of updates. Traditional unit tests check the end result; reactive tests must check the journey.

Solution: use marble diagrams to test observable sequences. For signals, test the dependency graph: change an input signal, verify the computed signal updates. Use fakeAsync() to control timing and verify that async operations complete in the expected order.

07 / Performance

Optimize reactive updates

Reactive systems can trigger excessive updates if not designed carefully. A single state change might cascade through multiple computed values, causing the UI to re-render multiple times for a single user action.

Solution: use computed signals for derived state — they only recompute when their dependencies change. Use distinctUntilChanged() on observables to prevent duplicate emissions. Profile with Angular DevTools to identify unnecessary change detection cycles.

08 / Migration strategy

Transition from RxJS to Signals

The intermediary portal had existing RxJS-based state management. Migrating to Signals required a phased approach: keep RxJS for async workflows, use Signals for synchronous UI state, gradually convert as confidence grows.

Solution: use toSignal() to convert observables to signals, and toObservable() to convert signals to observables. This allows gradual migration without rewriting the entire state management layer. The key: identify which state is synchronous (signals) vs async (observables) before converting.

09 / Error handling

Manage failures in reactive flows

Reactive systems must handle errors at multiple levels: network failures, validation errors, permission denials, and race conditions. Each error type requires a different recovery strategy.

Solution: use catchError() for observable errors, and signal error states for synchronous failures. Display user-friendly error messages, but log detailed errors for debugging. For race conditions, use the identity guard pattern from the async section.

System flow

Navigation state flow

  1. 01

    Route change

    User navigates to new section, route guard validates permissions

  2. 02

    Signal update

    Route-owned signal updates selected ID, triggers computed values

  3. 03

    Derivation

    Computed signals for breadcrumbs, tabs, and side nav recalculate

  4. 04

    Async fetch

    RxJS observable fetches data for selected section

  5. 05

    Identity guard

    Response validated against current selection before commit

Decision record

Design decisions and tradeoffs

↔ Scroll horizontally to compare approaches and tradeoffs.

Approaches and their tradeoffs
DecisionApproachTradeoff
Single source of truthRoute owns the selected section ID, not a shared serviceComponents must receive state via inputs, but navigation has one authoritative owner
Computed derivationUse computed signals for derived state instead of storing copiesMissing inputs must be explicit (null vs undefined), but no stale copies
Identity guardsTag each async request with the selection that triggered itExtra metadata in requests, but prevents stale responses from overwriting current state

Failure cases & validation

Failure scenarios to validate

Proposed validation scenarios and expected behavior. These are design checks, not reported production test results.

  1. User switches accounts before the first request completes

    First response is discarded, second response is committed

  2. Permissions change while viewing an account

    Computed editability signal updates immediately, UI reflects new permissions

  3. Network request fails after user navigates away

    Error is not displayed, no stale state remains in the UI

  4. Component is destroyed while async operation is pending

    DestroyRef cancels subscription, no memory leak or state mutation

  5. A resolves after B has been selected

    Response from A is rejected by identity guard, only B data is shown

Evidence & further reading

Technical references