Skip to content

๐Ÿงฌ Flow DNA โ€” Genetic Optimization โ€‹

Every flow execution leaves a "DNA fingerprint." Over hundreds of runs, the library evolves optimal retry, timeout, and caching configs using a micro genetic algorithm.
Flow DNA Evolution
Generation: 0
Timeout
5000ms
Max Retries
3
Stale Time
10.0s
Fitness Score (Latency Optimized)
42.0%

The Concept โ€‹

Traditional async libraries require manual tuning of timeouts, retry counts, and cache durations. Flow DNA eliminates this by learning from production traffic.

After N executions, the engine:

  • Analyzes P95 latency to suggest optimal timeouts
  • Tracks success rates to evolve retry counts
  • Monitors cache hit rates to tune stale times
  • Adjusts debounce based on call frequency

Quick Start โ€‹

ts
import { useFlow } from "@asyncflowstate/react";

const { data, execute } = useFlow(fetchUser, {
  evolution: {
    enabled: true,
    generations: 50, // Begin optimizing after 50 executions
    mutationRate: 0.1, // How aggressively to tweak params
    fitness: "latency", // Optimize for: 'latency' | 'reliability' | 'bandwidth'
  },
});

How It Works โ€‹

mermaid
graph TD
    A["Execute Flow"] --> B["Record Genome"]
    B --> C{"N Executions?"}
    C -->|No| A
    C -->|Yes| D["Run Genetic Algorithm"]
    D --> E["Evolve Config"]
    E --> F["Apply Mutations"]
    F --> G["Track Fitness Score"]
    G --> A

Execution Genome โ€‹

Each execution captures a performance fingerprint:

FieldDescription
latencyTotal execution time in ms
retriesNumber of retry attempts used
cacheHitWhether the result came from cache
successWhether execution succeeded
payloadSizeResponse payload size in bytes

Fitness Functions โ€‹

ModeOptimizes ForBest When
latencyFastest response timesUser-facing API calls
reliabilityHighest success rateCritical mutations
bandwidthSmallest payloadsMobile-first apps

Evolved Configuration โ€‹

After enough generations, the engine suggests:

ts
// The flow automatically adjusts:
// - timeout: 5000 โ†’ 3200ms (learned from P95 latency)
// - retry.maxAttempts: 3 โ†’ 2 (server recovers fast)
// - staleTime: 30000 โ†’ 45000ms (data rarely changes)
// - debounce: undefined โ†’ 150ms (rapid-fire calls detected)

API Reference โ€‹

FlowDNA โ€‹

ts
import { FlowDNA } from "@asyncflowstate/core";

const dna = new FlowDNA("user-fetch", { enabled: true });

// Record execution telemetry
dna.record({
  latency: 230,
  retries: 0,
  cacheHit: false,
  success: true,
  payloadSize: 1024,
});

// Get evolved suggestions
const evolved = dna.getEvolved();
// { suggestedTimeout: 350, suggestedMaxRetries: 2, fitnessScore: 0.92, ... }

Persistence โ€‹

DNA telemetry is stored in localStorage with the key prefix af_dna_. It persists across sessions so flows continue evolving even after page refreshes.

Built with by AsyncFlowState Contributors
Open Source ยท MIT License