Skip to content

🪞 Speculative Execution

Like CPU branch prediction, but for UI. Execute both the optimistic and real paths simultaneously. If the server disagrees, perform a smooth animated correction.
IDLE
Projected Revenue
$12,000

The Concept

Traditional optimistic updates show instant results, then jarringly rollback if the server disagrees. Speculative Execution runs both paths in parallel and applies a smooth morphing animation when corrections are needed.

Quick Start

ts
const { data, execute } = useFlow(updateProfile, {
  speculative: {
    enabled: true,
    optimisticBranch: (args) => ({
      ...currentProfile,
      ...args[0],
    }),
    correctionAnimation: "morph",
    correctionDuration: 300,
  },
});

How It Works

mermaid
graph LR
    A["User Action"] --> B["Fork State"]
    B --> C["Speculative Branch (instant)"]
    B --> D["Canonical Branch (server)"]
    C --> E{"Match?"}
    D --> E
    E -->|Yes| F["Silent Merge ✓"]
    E -->|No| G["Animated Correction"]
  1. Fork: On execution, state splits into speculative (instant) and canonical (server) branches
  2. Render: The speculative branch renders immediately
  3. Compare: When the server responds, a deep-diff is performed
  4. Resolve: If identical → silent merge. If different → smooth CSS animation from speculative → canonical

Animation Modes

ModeEffect
morphCSS transform-based smooth morphing
fadeFade out old → fade in new
slideSlide old content out, new content in
noneInstant replacement (same as traditional rollback)

Accuracy Tracking

The engine tracks speculation accuracy over time. If a flow consistently speculates correctly (>95%), the correction animation overhead is automatically removed.

Configuration

OptionTypeDefaultDescription
enabledbooleanfalseEnable speculative execution
optimisticBranch(...args) => TDataCompute the speculative result
correctionAnimationstring'morph'Animation type for corrections
correctionDurationnumber300Animation duration in ms

Built with by AsyncFlowState Contributors
Open Source · MIT License