Optimize With Measurement
$fw:optimize is Flywheel's optimization workflow.
Use it when the question is:
- what is actually slow, expensive, noisy, or inefficient?
- which change improves the metric without breaking correctness?
- how do we prove the improvement against real telemetry or a trustworthy local
harness?
This is not a "spray tweaks and hope" skill. It is a measurement-first loop.
Interaction Method
Follow ../references/host-interaction-contract.md.
Call the exact host question tool named in
../references/host-interaction-contract.md when that tool is available. Do
not ask for raw 1/2/3 replies when the host already offers a choice surface.
When the workflow spans multiple material steps, use the host task-tracking
tool named in ../references/host-interaction-contract.md to create and
maintain a short task list.
Ask one question at a time. When multiple measurement paths are viable, present
the recommended label first and rely on the host's native freeform final path
when it exists.
Input
#$ARGUMENTS
Interpret the input as one of:
- a concrete optimization goal
- a known hotspot, service, query path, or component
- a latency, throughput, cost, or saturation problem
- an existing optimization note or spec
If the input is blank, ask what should be optimized and which outcome matters.
Reference Loading Map
Do not preload every reference. Load only what the current phase needs:
- Read
references/provider-selection.md when choosing the measurement source.
- Read
references/measurement-contract.md when building the optimization
contract.
- Read
references/datadog-path.md only when the Datadog path is selected.
- Read
references/lgtm-path.md only when the OTel-native path is selected.
- Read
references/optimization-loop.md only when execution planning begins.
- Read
../commit/references/evidence-bundle.md only when a measured result
should be handed off into $fw:review or $fw:commit.
- Read
../observability/references/service-readiness-matrix.md only when the
optimization target is runtime-risky or blast-radius-sensitive.
Execution Notes
Keep the stable optimization scaffold first, gather repo and telemetry truth
before forming hypotheses, and prefer one measured improvement over a bag of
speculative micro-tweaks.
- keep the measurement source explicit
- state the metric, guardrails, and stop criteria before changing code
- use serial experiments by default
- keep changes small enough that the metric movement can still be attributed
Core Principles
- No optimization without a metric - define what better means before
editing code.
- Use the repo's real observability front door - Datadog, an OTel-native
backend surface, or a local harness. Do not invent a telemetry source when
the project already has one.
- Correctness and reliability are guardrails, not optional follow-ups -
performance wins that raise error rate, break ordering, or widen blast
radius do not count as wins.
- Prefer hybrid proof when available - use local benchmarks, local
profiles, or a local observability stack for fast iteration, then validate
in a shared environment when the change is runtime-facing.
- One experiment, one conclusion - small deltas beat giant rewrites when
the goal is attribution.
Workflow
Phase 0: Classify The Optimization Target
Decide what category of optimization is in scope:
- request or endpoint latency
- job, queue, or batch throughput
- query or storage efficiency
- CPU, memory, or allocation pressure
- cache hit rate or invalidation churn
- build, test, or developer loop performance
- infrastructure spend or saturation
Also classify whether the target is:
- local-only - build, benchmark, or profile work can be proven on the
machine
- runtime-facing - service behavior must be proven against telemetry
- hybrid - local measurement is fast, but a shared environment is needed to
confirm the result matters
Phase 1: Touch Grass
Build an optimization ledger from repo truth:
- read
AGENTS.md and CLAUDE.md when present
- inspect relevant manifests, scripts, CI workflows, benchmark harnesses, load
tests, and profiling configs
- inspect nearby code and tests for the target path
- inspect the active repo's
docs/solutions/ for prior performance or
reliability learnings
- read
.context/flywheel/setup-ledger.md when present
- inspect observability config, instrumentation libraries, dashboards, monitor
references, saved queries, and environment variables
Capture:
- the target code path or service boundary
- the current likely bottleneck and alternative hypotheses
- correctness guardrails and reliability risks
- existing measurement surfaces
- whether the repo already appears Datadog-first, OTel-native-first, or
local-only
- which environments are actually observable: local dev stack, shared
non-production, production, or only a subset
If the optimization target is runtime-risky, read
../observability/references/service-readiness-matrix.md and keep the
applicable dimensions visible while optimizing.
Phase 2: Choose The Measurement Source
Read references/provider-selection.md.
Use repo evidence plus any setup ledger to choose one of these paths:
- Hybrid local + shared (recommended when both a fast local harness and a
trustworthy shared measurement environment exist)
- Datadog-backed measurement
- OTel-native backed measurement
- Local-only benchmark/profile/stack
- Freeform path when the repo needs a different measurement posture
Selection rules:
- choose Datadog-backed when Datadog appears to be the operational system
of record and the user has Datadog MCP or equivalent read access
- choose OTel-native backed when the repo is OTel-first or Grafana,
Prometheus or Mimir, Loki, Tempo, Pyroscope, or collector-backed dashboards
are the real support surfaces
- choose Local-only when remote access is unavailable, the code is not yet
deployed, or the hotspot is purely local
- choose Hybrid when local measurement is useful for rapid iteration and a
shared environment is available to validate the real-world effect
If both Datadog and OTel-native surfaces are plausible, first verify which
backend is the source of truth for this target. Then pin the environment
separately: local dev stack, shared non-production, or production.
Phase 3: Build The Measurement Contract
Read references/measurement-contract.md.
Before making changes, define:
- Primary metric - the number that decides whether the change won
- Guardrails - correctness, error rate, resource caps, saturation, or
reliability constraints that must not regress
- Measurement source - local benchmark, Datadog query, PromQL, TraceQL,
log query, profile, or dashboard
- Workload / sample - the request mix, traffic window, fixture, or batch
- Observation window - enough time to reduce noise and avoid mixed
rollouts
- Version / rollout binding - how you will isolate the experiment from
unrelated traffic or deploys
- Stop criteria - what counts as success, failure, or insufficient signal
If you cannot define a trustworthy baseline, stop and build or identify the
measurement surface first.
Phase 4: Load The Path-Specific Guidance
If the selected path is Datadog, read references/datadog-path.md.
If the selected path is OTel-native backed, read references/lgtm-path.md.
Use that guidance to pin:
- exact tags, labels, services, environments, and versions
- the metrics, traces, logs, and profiles that matter most
- the safest query surfaces for comparing before vs after
Phase 5: Plan The Optimization Loop
Read references/optimization-loop.md.
Prefer serial iteration:
- baseline
- hypothesis
- smallest credible change
- local checks and correctness tests
- measurement
- keep, revert, or revise
Only parallelize experiments when:
- the code paths are isolated
- the measurements are independent
- the user explicitly wants parallel work
Phase 6: Execute And Measure
For each experiment:
- state the hypothesis in one sentence
- make the smallest change that can move the metric
- run correctness checks before treating a metric move as real
- measure against the contract
- compare against baseline and guardrails
- record what changed, what moved, and whether the hypothesis held
Use local worktrees when isolated iteration will reduce confusion or protect
the current checkout.
If the change survives the optimization gate, route through $fw:review and
$fw:commit before calling it complete.
When the measurement result should feed later stages, create or update a shared
evidence bundle under:
.context/flywheel/evidence/<bundle-id>/
Keep the shared summary focused on:
- baseline
- guardrails
- measurement source
- winning change or current best direction
- the exact query, benchmark, dashboard, or profile name to rerun
Keep bulky raw traces, profiles, or benchmark outputs in their native local
location and reference them from the bundle instead of copying them.
Output Contract
Return a concise optimization brief:
- Target - what is being optimized
- Chosen measurement backend - Datadog, OTel-native, local-only, or hybrid
- Chosen environment - local dev stack, shared non-production,
production, or mixed
- Baseline and guardrails
- Top hypotheses
- Experiment posture - serial or parallel, and why
- Winning change or current best direction
- Residual risks or missing signal
- Evidence bundle - shared bundle path when one was created, otherwise
not created
- Next Flywheel handoff -
$fw:work, $fw:review, $fw:commit, or
another optimization iteration
Included References
@./references/provider-selection.md
@./references/measurement-contract.md
@./references/datadog-path.md
@./references/lgtm-path.md
@./references/optimization-loop.md
@../commit/references/evidence-bundle.md
1---2name: optimize3description: Run measured optimization loops. Use for latency, throughput, resource, cost, build, or query improvements that need proof.4---56# Optimize With Measurement78`$fw:optimize` is Flywheel's optimization workflow.910Use it when the question is:1112- what is actually slow, expensive, noisy, or inefficient?13- which change improves the metric without breaking correctness?14- how do we prove the improvement against real telemetry or a trustworthy local15 harness?1617This is not a "spray tweaks and hope" skill. It is a measurement-first loop.1819## Interaction Method2021Follow `../references/host-interaction-contract.md`.2223Call the exact host question tool named in24`../references/host-interaction-contract.md` when that tool is available. Do25not ask for raw `1/2/3` replies when the host already offers a choice surface.2627When the workflow spans multiple material steps, use the host task-tracking28tool named in `../references/host-interaction-contract.md` to create and29maintain a short task list.3031Ask one question at a time. When multiple measurement paths are viable, present32the recommended label first and rely on the host's native freeform final path33when it exists.3435## Input3637<optimization_input> #$ARGUMENTS </optimization_input>3839Interpret the input as one of:4041- a concrete optimization goal42- a known hotspot, service, query path, or component43- a latency, throughput, cost, or saturation problem44- an existing optimization note or spec4546If the input is blank, ask what should be optimized and which outcome matters.4748## Reference Loading Map4950Do not preload every reference. Load only what the current phase needs:5152- Read `references/provider-selection.md` when choosing the measurement source.53- Read `references/measurement-contract.md` when building the optimization54 contract.55- Read `references/datadog-path.md` only when the Datadog path is selected.56- Read `references/lgtm-path.md` only when the OTel-native path is selected.57- Read `references/optimization-loop.md` only when execution planning begins.58- Read `../commit/references/evidence-bundle.md` only when a measured result59 should be handed off into `$fw:review` or `$fw:commit`.60- Read `../observability/references/service-readiness-matrix.md` only when the61 optimization target is runtime-risky or blast-radius-sensitive.6263## Execution Notes6465Keep the stable optimization scaffold first, gather repo and telemetry truth66before forming hypotheses, and prefer one measured improvement over a bag of67speculative micro-tweaks.6869- keep the measurement source explicit70- state the metric, guardrails, and stop criteria before changing code71- use serial experiments by default72- keep changes small enough that the metric movement can still be attributed7374## Core Principles75761. **No optimization without a metric** - define what better means before77 editing code.782. **Use the repo's real observability front door** - Datadog, an OTel-native79 backend surface, or a local harness. Do not invent a telemetry source when80 the project already has one.813. **Correctness and reliability are guardrails, not optional follow-ups** -82 performance wins that raise error rate, break ordering, or widen blast83 radius do not count as wins.844. **Prefer hybrid proof when available** - use local benchmarks, local85 profiles, or a local observability stack for fast iteration, then validate86 in a shared environment when the change is runtime-facing.875. **One experiment, one conclusion** - small deltas beat giant rewrites when88 the goal is attribution.8990## Workflow9192### Phase 0: Classify The Optimization Target9394Decide what category of optimization is in scope:9596- request or endpoint latency97- job, queue, or batch throughput98- query or storage efficiency99- CPU, memory, or allocation pressure100- cache hit rate or invalidation churn101- build, test, or developer loop performance102- infrastructure spend or saturation103104Also classify whether the target is:105106- **local-only** - build, benchmark, or profile work can be proven on the107 machine108- **runtime-facing** - service behavior must be proven against telemetry109- **hybrid** - local measurement is fast, but a shared environment is needed to110 confirm the result matters111112### Phase 1: Touch Grass113114Build an optimization ledger from repo truth:115116- read `AGENTS.md` and `CLAUDE.md` when present117- inspect relevant manifests, scripts, CI workflows, benchmark harnesses, load118 tests, and profiling configs119- inspect nearby code and tests for the target path120- inspect the active repo's `docs/solutions/` for prior performance or121 reliability learnings122- read `.context/flywheel/setup-ledger.md` when present123- inspect observability config, instrumentation libraries, dashboards, monitor124 references, saved queries, and environment variables125126Capture:127128- the target code path or service boundary129- the current likely bottleneck and alternative hypotheses130- correctness guardrails and reliability risks131- existing measurement surfaces132- whether the repo already appears Datadog-first, OTel-native-first, or133 local-only134- which environments are actually observable: local dev stack, shared135 non-production, production, or only a subset136137If the optimization target is runtime-risky, read138`../observability/references/service-readiness-matrix.md` and keep the139applicable dimensions visible while optimizing.140141### Phase 2: Choose The Measurement Source142143Read `references/provider-selection.md`.144145Use repo evidence plus any setup ledger to choose one of these paths:146147- **Hybrid local + shared** (recommended when both a fast local harness and a148 trustworthy shared measurement environment exist)149- **Datadog-backed measurement**150- **OTel-native backed measurement**151- **Local-only benchmark/profile/stack**152- Freeform path when the repo needs a different measurement posture153154Selection rules:155156- choose **Datadog-backed** when Datadog appears to be the operational system157 of record and the user has Datadog MCP or equivalent read access158- choose **OTel-native backed** when the repo is OTel-first or Grafana,159 Prometheus or Mimir, Loki, Tempo, Pyroscope, or collector-backed dashboards160 are the real support surfaces161- choose **Local-only** when remote access is unavailable, the code is not yet162 deployed, or the hotspot is purely local163- choose **Hybrid** when local measurement is useful for rapid iteration and a164 shared environment is available to validate the real-world effect165166If both Datadog and OTel-native surfaces are plausible, first verify which167backend is the source of truth for this target. Then pin the environment168separately: local dev stack, shared non-production, or production.169170### Phase 3: Build The Measurement Contract171172Read `references/measurement-contract.md`.173174Before making changes, define:1751761. **Primary metric** - the number that decides whether the change won1772. **Guardrails** - correctness, error rate, resource caps, saturation, or178 reliability constraints that must not regress1793. **Measurement source** - local benchmark, Datadog query, PromQL, TraceQL,180 log query, profile, or dashboard1814. **Workload / sample** - the request mix, traffic window, fixture, or batch1825. **Observation window** - enough time to reduce noise and avoid mixed183 rollouts1846. **Version / rollout binding** - how you will isolate the experiment from185 unrelated traffic or deploys1867. **Stop criteria** - what counts as success, failure, or insufficient signal187188If you cannot define a trustworthy baseline, stop and build or identify the189measurement surface first.190191### Phase 4: Load The Path-Specific Guidance192193If the selected path is Datadog, read `references/datadog-path.md`.194195If the selected path is OTel-native backed, read `references/lgtm-path.md`.196197Use that guidance to pin:198199- exact tags, labels, services, environments, and versions200- the metrics, traces, logs, and profiles that matter most201- the safest query surfaces for comparing before vs after202203### Phase 5: Plan The Optimization Loop204205Read `references/optimization-loop.md`.206207Prefer serial iteration:2082091. baseline2102. hypothesis2113. smallest credible change2124. local checks and correctness tests2135. measurement2146. keep, revert, or revise215216Only parallelize experiments when:217218- the code paths are isolated219- the measurements are independent220- the user explicitly wants parallel work221222### Phase 6: Execute And Measure223224For each experiment:225226- state the hypothesis in one sentence227- make the smallest change that can move the metric228- run correctness checks before treating a metric move as real229- measure against the contract230- compare against baseline and guardrails231- record what changed, what moved, and whether the hypothesis held232233Use local worktrees when isolated iteration will reduce confusion or protect234the current checkout.235236If the change survives the optimization gate, route through `$fw:review` and237`$fw:commit` before calling it complete.238239When the measurement result should feed later stages, create or update a shared240evidence bundle under:241242```text243.context/flywheel/evidence/<bundle-id>/244```245246Keep the shared summary focused on:247248- baseline249- guardrails250- measurement source251- winning change or current best direction252- the exact query, benchmark, dashboard, or profile name to rerun253254Keep bulky raw traces, profiles, or benchmark outputs in their native local255location and reference them from the bundle instead of copying them.256257## Output Contract258259Return a concise optimization brief:2602611. **Target** - what is being optimized2622. **Chosen measurement backend** - Datadog, OTel-native, local-only, or hybrid2633. **Chosen environment** - local dev stack, shared non-production,264 production, or mixed2654. **Baseline and guardrails**2665. **Top hypotheses**2676. **Experiment posture** - serial or parallel, and why2687. **Winning change or current best direction**2698. **Residual risks or missing signal**2709. **Evidence bundle** - shared bundle path when one was created, otherwise271 `not created`27210. **Next Flywheel handoff** - `$fw:work`, `$fw:review`, `$fw:commit`, or273 another optimization iteration274275---276277## Included References278279@./references/provider-selection.md280@./references/measurement-contract.md281@./references/datadog-path.md282@./references/lgtm-path.md283@./references/optimization-loop.md284@../commit/references/evidence-bundle.md