Skip to content

netherframe Performance Optimization Results

Hybrid plan serialization (2026-11-25)

Timed without a profiler, a hybrid plan of 1,000 created resources spent about 85 ms, and an apply replacing 1,000 resources about 300 ms, turning plans and states into JSON. Four changes:

  • An apply given the summary plan returned reused the plan's artifact only after building its JSON again to compare (_coerce_plan_artifact). The session now records an orjson fingerprint of the data plan returned, and reuses the artifact when the data equals it and still has that fingerprint (it may be the same object, changed in place); other data is verified as a saved plan is.
  • Serializing state walks each resource's attributes for values of a dynamic cty type (dynamic_type_metadata). Those values are TypedObjects and TypedLists, and until one is made in the process (their __new__ says so, which unpickling and copying call too) no value holds one, so the walk is skipped.
  • The digest that tells whether a plan's live execution graph can be reused (_execution_digest) is compared only within the process, so it uses orjson. The persisted content_digest keeps stdlib json's bytes.
  • _json_safe tells plain values apart by class and takes scalars out of containers without a call; subclasses take the isinstance walk as before, so its results are unchanged.
1,000 resources, without a profiler Before After
Hybrid plan creating them 313 ms 260 ms
Hybrid apply replacing them (plan included) 1,042 ms 915 ms
Apply: _coerce_plan_artifact 78 ms 5 ms
Apply: dynamic_type_metadata (12,000 calls) 56 ms 2 ms
Apply: _json_safe 137 ms 42 ms

The workload is perf_profile.py's hybrid-plan-create and hybrid-apply-replace with its cProfile section switched off, an in-process mock provider, medians of three runs.

Creation and synthesis regression fix (2026-11-25)

poe bench (10,000 explicit resources) had become 31% slower than its recorded baseline. Bisecting it over the commits since that baseline found two causes:

  • 9d31c72 (installed native Python providers, released in core 0.11.0) made synthesis resolve every resource's provider and look it up among the installed native providers. Each resolution read all of the stack's providers again and parsed two provider addresses. Synthesis now checks each distinct provider once per stack: a resource's provider depends only on its class, its type and its nf_provider.
  • d0cfdb9 (Phase 3 soundness, released on 2026-11-24) validated each nf_id with a generator over the forbidden characters. It now uses a frozenset.

Microseconds per resource for 10,000 explicit resources:

Measurement Recorded baseline Before the fix After the fix
Creation, under cProfile 10.5 12.6 11.2
Synthesis, under cProfile 25.9 35.1 24.3
Total, under cProfile (what poe bench records) 36.2 48.1 35.7
Total, without a profiler 12.0 14.9 12.1

The cProfile rows are medians of 5 interleaved runs of perf_profile.py. The last row is the best of 5 builds in one process. Every commit's netherframe.core was exported with git archive and run with the same harness and environment. The 1,000-resource benchmark went from 78.8 to 62.6 under cProfile.

Creation remains about 0.1 µs per resource slower than the baseline without a profiler. The cost comes from the ContextVar that keeps a stack's provider context local to a build, and from scope handling for nested constructs. Both are kept.

Qualified creation pipeline (2026-11-16)

Final result: retain preparation and deferred-input planning; revert the coordinator. Fresh paired comparisons against c0c80fb6, three samples each:

Workload Before Retained code Result
1,000-resource local gRPC dependency chains 9.568 s 8.330 s 1.238 s / 12.9% faster
AWS 6.66.0 / FakeCloud, 1,000 known-input SSM creates 11.110 s 11.119 s Flat within noise
First unchanged AWS full apply 4.637 s 4.647 s Flat within noise

The dependency-chain pairs were 9.568/8.597, 9.657/8.097 and 9.423/8.330 s. Median process CPU fell 10.563 → 9.001 s. Every sample verified its full state, durable provider receipts, consumed input revisions and zero unresolved operations. The AWS unchanged applies performed zero writes. The deferred optimization requires the existing explicit apply_deferred opt-in; known inputs do not benefit from eliminating speculative plans. The 6–7 s target has not been reached. Incremental trial timings below were collected at different times and must not be added together.

Final validation: 13,440 unit tests passed (89 skipped), 1,937 PostgreSQL / FakeCloud tests passed (one skipped), Ruff, alias generation and docs build passed. The three experiments were committed separately; a subsequent commit removes the coordinator after the broader performance check.

The first follow-up carries an exact per-operation preparation witness through authorization, finishes terminal operations locally, and runs create validation and final planning in a single worker submission. Provider/schema callbacks and database fallbacks stay off the scheduler. The preparation witness contains no live authority: the backend still checks ownership, inputs, object claims and both transaction fences. Changed request bytes or qualification headers require preparation again; process identifiers and serialized size are checked at arm.

Three sequential paired 1,000-resource gRPC/PostgreSQL runs against c0c80fb6: 9.380 s → 8.779 s median (6.4% faster). Individual pairs were 10.213/8.779, 9.380/9.032 and 9.191/8.692 s. Every run retained the same final state hash, 1,000 committed receipts, correct dependency revisions and zero unresolved operations. This removes 1,000 terminal-finish worker submissions and 750 separate validation submissions from this workload. Request preparation and provider work retain their correctness checks.

Validation: 11,116 core unit tests passed (85 skipped), 70 PostgreSQL authorization/creation/completion tests passed (24 real-provider tests skipped without FakeCloud), Ruff and the documentation build passed.

The second experiment coordinated the three creation queues. Authorization and publication share one lane; returned provider results have a separate storage lane so a slow publication cannot hold up their durability. Every transaction keeps its live validation and fences. The existing opportunistic combined receipt/publication gate remains disabled.

Three paired runs against f68dbd39 were 8.529/8.542, 8.692/8.571 and 8.688/8.723 s: 8.688 → 8.571 s median (1.3%). This elapsed improvement is small relative to noise. Median process CPU fell 9.459 → 9.336 s, PostgreSQL CPU 2.353 → 2.104 s, and transaction count 249 → 209. Median receipt p95 stayed approximately 68 → 67 ms. All final-state and receipt checks passed.

A single-worker version was rejected despite a 3.1% median elapsed improvement: receipt p95 rose to about 153 ms behind publication. A trial regression test held publication open and required the independent receipt to become durable before publication was released. Both trial queue implementations exercised cancellation, lost-reply, backpressure and failure cases; the coordinated path ran with worker budgets of one and four.

Validation of the coordinator trial: 13,479 workspace unit tests passed (89 skipped), 95 targeted PostgreSQL/FakeCloud tests passed, including the isolated WAL-observation test that timed out during the earlier full-suite run. Ruff, generated alias checks and the documentation build passed.

The third change defers unknown-input provider planning for qualified fresh creates when apply_deferred explicitly enables it and approval is once or auto. The plan records resource_config_unknown; dependencies must be concrete, provider settings constant and the cloud identity known. Extra plan semantics and unsupported dependency models retain their original paths. Saved and admitted plans retain full deferred plan-round validation. See deferred planning.

Against 1b98621f, paired runs were 8.691/8.160, 8.852/8.125 and 8.954/8.761 s: 8.852 → 8.160 s median (7.8%). Validation and plan RPCs each fell from 1,750 to 1,000, and speculative unknown-input plans from 750 to zero. All three pairs improved and retained the same state hash, receipts and input revisions. The final version also delays qualification until an unknown-input create is encountered, avoiding that work on known configurations and no-op runs.

Broader validation rejected the coordinator. The combined three-change trial improved a fresh comparison against c0c80fb6 from 9.772 to 8.536 s median, but 1,000 known-input AWS 6.66.0 SSM creates on FakeCloud regressed from 11.648 to 11.913 s median (2.3%). First unchanged applies were approximately flat (4.765 to 4.692 s). Two probes disabling only the coordinator completed creation in 11.081 and 11.309 s. The final code therefore retains preparation and deferred-input planning and removes the coordinator experiment.

The deferred-planning validation passed 13,493 workspace unit tests (89 skipped). The full PostgreSQL run passed 1,919 tests with one skip; its only two failures were assertions expecting the speculative RPCs now eliminated. The expanded 78-test initial-refresh file passed with deferred planning on and off, verifying 1,937 unique PostgreSQL cases across the suite and corrected-file rerun.

Raw measurements and workload limits are recorded in libs/netherframe.core/tests/performance/results/creation_pipeline_20261116.json.

Planning and execution follow-up (2026-11-16)

Four changes were implemented in order and committed separately. The local 1,000-resource full-apply benchmark improved from 10.791 s to 8.970 s (medians of three runs each, 16.9%). It uses 250 four-resource chains, concurrency 10, 1 KiB payloads, a deterministic local gRPC provider, and durable PostgreSQL with fsync, synchronous commits and full-page writes enabled. Construction, database startup and result verification are excluded.

Change Reference median Changed median Commit
Share decoded ownership claims within each stable validation 10.791 s 10.058 s (6.8% faster) 1244fa71
Enable exact, qualified provider plan reuse 10.058 s 9.561 s (4.9% faster) 3b9985dc
Cache claims derived from exact stored request text 9.278 s 9.130 s (1.6%; noisy) d6efa726
Reuse text parsing and capture-local planning metadata 9.246 s 8.970 s (3.0% faster) 29abdfdd

The last two comparisons rerun their immediate predecessor as a paired control; the different reference timings show run-to-run variation. These percentages are not additive, and three samples do not establish confidence intervals. Real cloud API latency is outside this dummy-provider workload.

Claim reuse does not retain live authority. Every transaction still reads and checks current stages, grants, ownership, footprints and state. The cross-read cache is keyed by exact request text and action and limited to 512 entries, with a 4 MiB UTF-8 budget for retained strings (excluding Python object overhead). It returns independent lease mappings; oversized requests bypass it. In a same-database alternating comparison with 64 pending operations, reading and deriving all claims improved from 6.53 to 3.46 ms; a fenced 64-row state-only commit improved from 65.49 to 61.34 ms. These microbenchmarks use two warm-up rounds and nine measured pairs. A separate experiment removed one authorization SQL round trip without improving elapsed time, so it was reverted.

Provider reuse requires explicit qualification and an exact successful request, configuration, runtime and result proof. Unknown or changed inputs and unqualified runtimes retain ordinary planning. Destroy operations still use their own plans, and provider restarts revalidate configuration where needed. The dummy workload makes 1,750 resource-plan and 1,750 validation calls instead of 2,000 of each; all 1,000 provider mutations still occur. Unchanged plans avoid finalizing a proof that cannot be consumed by an apply.

With the real AWS 6.66.0 provider against FakeCloud, three final 1,000-SSM creation samples have a median of 11.067 s, compared with 11.935 s in the three reference samples (7.3% faster). That reference already includes the scoped-claim change and disables plan reuse. The first unchanged apply is effectively flat (4.481 vs 4.450 s). The intermediate reuse-only build had a 3.4% unchanged-apply slowdown; the final metadata changes offset it, but these samples do not establish a no-op speedup. Verification checks all 1,000 durable provider results, state/service equality, service versions, 750 direct inputs, no unresolved operations, and no extra writes on the unchanged apply.

Planning now shares each decoded ownership request and unresolved-operation guard within its captured snapshot, discovers each provider configuration's static reads once per stack per capture, and caches bounded immutable address parse results. The next capture rebuilds provider reads; construct configuration and live runtime values are not cached. Median intent capture improved from 349 to 261 ms (25.2%). Address parsing still constructs fresh caller/subclass instances and preserves oversized and custom string inputs.

The median final run has the following exclusive main-thread wall breakdown. These phases partition elapsed time; worker CPU, SQL and queue timers overlap and cannot be added to them.

Phase Time Share
Execution 6.936 s 77.3%
Planning 1.423 s 15.9%
Intent capture 0.258 s 2.9%
Other apply work 0.332 s 3.7%
Provider configuration and empty refresh 0.021 s 0.2%

During validation, an existing affected-plan activation bug was reproduced on the unchanged baseline: it required a full execution inventory from a deliberately selected closure. Commit 342365b8 restores the selected-closure validator while keeping full-plan inventory validation strict.

Broader native verification also exposed stale test boundaries already failing on the original revision. Commit e17b83dc updates independent evidence readers for full-plan formats 17, 19 and 20, keeps affected format 18 distinct, and rejects unsupported formats. The lost-response test now interrupts both single and batched receipt writes and verifies that its injected outage occurred. Test path setup also supports sibling fixtures under the root runner's importlib mode.

Final validation: the standard workspace unit command passes 13,418 tests (89 skipped), and the complete PostgreSQL suite with containers and FakeCloud enabled passes 1,921 tests (one skipped). Ruff lint and formatting checks pass for all 34 changed Python files, and the documentation builds without issues.

Samples, verification hashes, provider call counts, SQL counters and limitations are retained in libs/netherframe.core/tests/performance/results/planning_execution_20261116.json. Reproduce the dummy full-apply workload with the graph_orchestration.py command in the next section.

Next execution targets: diagnostic probes (2026-11-16)

A second investigation tested whether another two seconds could be removed from the complete 1,000-resource apply. No tested variant reached seven seconds. The repeated baseline was 9.154 s median; a prototype moving known local setup, write preparation and already-committed operation completion out of worker threads reached 8.641 s median (0.512 s, 5.6%). Both have three samples. This is a diagnostic prototype, not a production change: callbacks and fallback paths that can block must remain isolated from the scheduler.

Exploratory change Full apply Finding
Concurrency 1 / 32 / 64 9.122 / 8.828 / 8.690 s No multi-second gain
Existing opportunistic receipt/publication path 10.397 s Regresses; 524 transactions and 78 publications
Authorization collection 20 ms 9.099 s Essentially baseline
Creation window 512 10.210 s Regresses despite fewer transactions
Publication collection 100 ms 9.560 s Longer waits outweigh fewer publications
Extra exact lease-set validation cache 9.294 s No demonstrated improvement
Return target 32, maximum collection 50 ms 9.276 s Fewer transactions, no wall-time gain
Local preparation + concurrency 64 + return target 32 8.453 s Still above target despite only 164 transactions

These table entries are single samples. Every run verifies the same final state, 1,000 durable provider receipts, dependency inputs, fencing and zero unresolved operations. The existing combined receipt/publication feature remains disabled. The probes are not qualified against arbitrary providers, callbacks or all failure paths and were not installed in production.

The remaining work should target the complete qualified-create pipeline:

  1. Prepare one stable mutation envelope per change and carry its pure derived data through authorization and publication. Separate local preparation from blocking fallbacks, and remove redundant worker handoffs. The baseline made about 6,000 worker submissions, including 1,000 terminal operation finishes.
  2. Coordinate the authorization, receipt and publication stages instead of independently fragmenting their batches. Preserve prompt durable receipts, current-state checks and both fences. Judge this by wall time and CPU, not transaction count alone: the probes show that fewer transactions can be slower.
  3. Investigate explicit deferred planning of unknown-input creates. This fixture makes 750 speculative provider plans with unknown inputs and plans those resources again during execution. Planning once inputs are available could avoid that work, but must retain deferred approval and saved-plan semantics; the calls cannot simply be omitted for arbitrary plans.

A 6–7 s complete apply is the next prototype target, not a demonstrated result or a prediction of production cloud latency. Measurements, verification hashes, worker counts and discarded-probe limitations are retained in libs/netherframe.core/tests/performance/results/execution_pipeline_probes_20261116.json.

Runtime and provider hot paths (2026-11-15)

Six optimizations reduce graph traversal, task creation, configuration rebuilding, provider serialization and database traffic. These measurements use Python 3.15.2 on one host with local mock or gRPC dummy providers. They measure netherframe overhead; production cloud API latency is outside this comparison.

Area Before After
Deferred closure, 10,000-node chain Repeated scans; 7.600 s median Queue traversal in O(V + E); 0.00786 s median
Explicit ordering between two 2,000-resource stacks 4,000,000 edges; 125.8 MiB in dependency sets 4,000 scheduling edges through a shared barrier; 1.71 MiB
Ready-node scheduling and refresh A task for every resource A bounded ready queue and fixed refresh workers; yielded continuations retain their context
Deferred planning, 200 namespaces and an output 202 full desired-state builds; 3.628 s apply One full build, then selected configurations; 0.840 s apply
Provider encoding, 1,000 gRPC creates 11,001 encodings 9,001 encodings, with the same provider RPC counts
Receipt batching, 1,000 gRPC creates on PostgreSQL Median 3,843 SQL requests / 297 transactions Median 3,537 requests / 267 transactions

The closure measurements use three baseline and five final samples. Deferred apply times are single samples, so the configuration-build counts are stronger evidence than their timing ratio. Selected deferred planning still captures graph evidence and performs provider planning against current state; it does not remove every whole-state operation.

Encoding reuse lasts for one request and applies only when fields reference the same input object. It cannot reuse stale bytes across requests. Development saved-plan format 20 introduced support for explicit stack ordering. Release format 1 retains the ordering, and earlier readers reject the new format. Resource dependency references remain separate from scheduling barriers.

Receipt batching uses three trials per configuration. It retains the initial 2 ms collection window and extends it only for an incomplete active cohort, up to 10 ms from the first queued response. It flushes when that cohort is ready and does not require missing peers to return. Median apply time was essentially unchanged (10.951 s versus 10.936 s); the improvement is 8% fewer SQL requests and 10% fewer transactions. Median per-run p95 receipt latency was 83.9 ms versus 85.5 ms. Row and byte limits, fencing, cancellation draining and acknowledgement after durable storage remain in force.

Raw samples and measurement limits are retained in libs/netherframe.core/tests/performance/results/runtime_provider_algorithms_20261115.json. The PostgreSQL workload can be run with:

PYTHONPATH=tests/helpers uv run python tests/performance/graph_orchestration.py \
  --count 1000 --transport grpc --timeout 90 --output /tmp/graph-runtime.json

Deferred execution and operation reads: follow-up (2026-11-15)

Four further changes were implemented and committed in order. Each comparison isolates its change against the preceding implementation. Deferred apply measurements use three runs per configuration and 200 namespaces whose provider settings depend on a newly created cluster. Algorithm measurements use three samples per size.

Change Before After
Stable state snapshots with lazy row copies 0.904 s median apply; 20,439 resource copies 0.716 s; 402 copies (21% faster)
Indexed propagation of unresolved roots, 300-node chain 3.274 s median 0.265 ms; scopes indexed once, new roots propagated through a queue
Reuse deferred planning loop and resource index 0.699 s median apply; 406 loop setups and 204 lookups 0.423 s; 3 loop setups and 4 lookups (40% faster)
PostgreSQL operation exclusion reads, 64 pending returned operations 5.67 ms per read; 388,016 bytes of text columns 3.30 ms; 308,666 bytes (42% faster, 20% less text)

The state snapshot also fixes a reproduced concurrent-write failure during deferred refresh. It captures membership under the engine mutex and copies a row when a reader first accesses it. Replacement of live rows preserves the snapshot's previous values, using the existing ResourceState.copy semantics. With both deferred optimizations, an 800-namespace scaling check completed in 1.608 s with 1,602 resource copies; the original state-read path failed this workload while siblings recorded results.

Unresolved-root propagation preserves all root provenance, including cycles and app/stack scopes. A 10,000-node, single-root chain now takes 11.14 ms median. Multiple roots can still produce large provenance sets; the queue eliminates repeated scans rather than discarding roots.

Deferred workers rejoin their owning AnyIO loop, and one resource index serves the deferred scheduling context. Empty refresh and adoption work returns early. Regression tests cover a one-thread worker budget, nested provider work and context-variable isolation.

PostgreSQL permission checks retain complete requests, move footprints and recovery ownership. Their narrower query omits response payloads and unused status metadata. State-only publication reuses the permission check's operation snapshot inside the same app-frontier lock, reducing a fixed 64-row batch from 19 to 18 body SQL requests. Initial and tail fences still run separately against the database clock, and full operation records remain available to recovery and status readers.

The fixed database comparison uses two warm-up rounds followed by nine alternating samples. Each ledger-read sample averages 20 queries. A second run reproduced the read improvement (6.35 to 3.38 ms). State-batch median timings improved only 1–3%; the saved query is the firmer batch result. Text-column byte counts exclude native binary fields and protocol framing, and body SQL counts exclude BEGIN, protocol SET and COMMIT.

Three complete 1,000-resource gRPC/PostgreSQL applies per configuration showed no demonstrated end-to-end gain from the database change: median 11.293 s before and 11.445 s after, with overlapping observed ranges and varying batch sizes. The measured gain is in operation reads and redundant-query removal; cloud API latency remains outside these local workloads.

The follow_up section of libs/netherframe.core/tests/performance/results/runtime_provider_algorithms_20261115.json retains samples, counters, commit IDs and measurement limits. Reproduce the fixed database comparison with:

PYTHONPATH=tests/helpers uv run python tests/performance/graph_operation_reads.py \
  --output /tmp/operation-reads.json

Data structures: measured follow-up (2026-11-15)

Six changes were implemented in order, with a separate commit for each. These comparisons measure the affected operations on Python 3.15.2, using the preceding implementation as the control. They are local scaling and allocation measurements, not estimates of cloud deployment speed.

Change Workload Before After Commit
Cached manifest projections and digest Five reads of a fresh 10,000-entry manifest 332 ms 72.0 ms 2013b602
Slotted immutable input records 100,000 records with shared strings, including their containing list 11.20 MB 7.20 MB d79e1ec4
Stack scope revision index 100 scopes across 10,000 rows, including index construction 974 ms 23.3 ms ef1d195b
Unresolved operations indexed by address 2,000 rows, 2,000 concrete inputs, two scopes and 200 operations 115 ms 15.9 ms 82da3afb
Shared immutable graph partitions 1,000 edge updates on 10,000 edges, including conversion and final materialization 307 ms 25.9 ms 217c02a7
Provider configurations indexed by source, alias and scope Register 1,000 configurations and perform 1,000 source-address lookups 77.3 ms 8.61 ms 73ab6480

Times are medians of five samples, except provider lookup, which uses seven. Scope, operation, edge and provider measurements alternate the control and changed implementations. Manifest measurements use five separate trials per implementation. Record allocation uses three tracemalloc samples per implementation; its 36% reduction applies to these allocations, not whole-process memory.

Manifest caches retain immutable static evidence. Callers still receive a mutable copy of planning contexts so runtime qualification cannot contaminate another evaluation. Copying, pickling, replacement and wire round trips preserve the manifest digest. Scope indexes belong to one captured version view and retain the canonical hashes, owner exclusion, tombstones and semantic revision counters; engine commits and reloads invalidate them. The unresolved-operation comparison produced the same 800 diagnostics, including quarantine and recovery checks.

Graph storage promotes containers lazily at 1,024 entries. Large containers use 64 immutable partitions, sharing untouched buckets between captured roots. This reduces copying for local updates; it is not a logarithmic persistent tree. Generation-only changes and remove/re-add cycles still invalidate prior evidence. Serialization reconstructs partitions so another process's randomized hash seed cannot invalidate lookups. Edge deltas and persisted wire formats remain unchanged; the in-memory edge collection now exposes a read-only set interface.

The graph change adds about 0.3–0.6 microseconds per update in the smaller flat container benchmarks. Three complete 1,000-resource gRPC/PostgreSQL applies per configuration measured 11.396 s median before and 11.480 s after, with overlapping ranges. This demonstrates no full-apply speedup. All six runs verified provider results, resource state, private data, identities, dependency revisions, durable operation receipts and commit fences. In the earlier instrumented workload, edge updates occupied only 1.1 ms, so this is chiefly a large-graph scaling improvement.

The provider index is built on the first source-address lookup and invalidated by registration or shutdown. It preserves the first matching configuration, scope preference, aliases and replacement ordering. Source lookup alone, including the first index build, fell from 70.3 ms to 1.73 ms; 20,000 direct name lookups remained about 3.7 ms. The representative apply used direct names exclusively, so this change benefits workloads that use source-address fallback.

Validation passed 13,279 workspace unit tests and 650 tests across the PostgreSQL suites, including the FakeCloud topology and recovery cases. Ruff and the docs build passed. A separate 2,000-resource gRPC/PostgreSQL apply verified 2,000 durable receipts and exercised both partitioned containers, reaching 1,500 edges and generation counters. The outage fixture was updated separately to interrupt batched receipts as well as single-result storage; its previous hook missed the existing app-create batching path.

Samples, workload definitions, commit IDs and verification results are retained in libs/netherframe.core/tests/performance/results/data_structures_20261115.json. The complete apply workload remains reproducible with tests/performance/graph_orchestration.py, using the command above.

The remaining sections describe earlier synthesis measurements.

Executive Summary

Successfully implemented 6 performance optimizations that achieved: - 29.0% improvement for 100 resources (24.7ms → 17.5ms) - 22.3% improvement for 1000 resources (208.1ms → 161.8ms) - 20.5% improvement for 5000 resources (1021.3ms → 811.5ms)

The optimizations maintain excellent near-linear scaling (O(n^1.00)) while significantly reducing per-resource synthesis time.

Optimization Details

1. Threading Optimization

  • Implementation: Skip thread pool for apps with ≤3 stacks
  • Impact: 10.2% improvement for small apps, minimal for large apps
  • File: libs/netherframe.core/netherframe/core/constructs/app_stack.py (App.synth method)

2. Fast JSON Serialization (orjson)

  • Implementation: Use orjson library for 3x faster JSON writing
  • Impact: 13-14% improvement across all resource counts
  • File: libs/netherframe.core/netherframe/core/constructs/app_stack.py (Stack._synthesize method)

3. Logging Control

  • Implementation: tighter logging controls on hot paths
  • Impact: 4-8% improvement in earlier experiments
  • Files: logging and construct hot paths

4. Cached Auto-detection

  • Implementation: Cache frame inspection results for scope/name detection
  • Impact: 2-3% improvement by reducing repeated stack analysis
  • File: libs/netherframe.core/netherframe/core/constructs/base_construct.py (Construct._detect_scope, _extract_variable_name)

5. Lazy Path Construction

  • Implementation: Convert path to cached property
  • Impact: Slight regression (-1%), kept for API consistency
  • File: libs/netherframe.core/netherframe/core/constructs/base_construct.py (Construct.path property)

6. Memoized Token Resolution

  • Implementation: Cache resolved token values by context ID
  • Impact: 0.5-3% improvement in token-heavy workloads
  • File: libs/netherframe.core/netherframe/core/tokens.py (Token.resolve method)

Performance Characteristics

Scaling Analysis

  • 100 to 1000 resources: O(n^0.97) - Sub-linear scaling!
  • 1000 to 5000 resources: O(n^1.00) - Perfect linear scaling
  • Per-resource time: Reduced from 0.21ms to 0.16ms (24% improvement)

Breakdown by Resource Count

Resources Baseline Optimized Improvement Time Saved
100 24.7ms 17.5ms 29.0% 7.2ms
1000 208.1ms 161.8ms 22.3% 46.4ms
5000 1021.3ms 811.5ms 20.5% 209.7ms

Usage Example

To leverage the remaining optimizations:

from nf.core import App, Stack, Resource

app = App(deferred_validation=True)
stack = Stack(app, "my-stack")

for i in range(1000):
    Resource(scope=stack, nf_id=f"bucket_{i}", type="aws_s3_bucket", bucket=f"my-bucket-{i}", tags={"Environment": "prod"})

app.synth()  # Now 22% faster!

Testing

Run performance tests with:

uv run python libs/netherframe.core/tests/performance/perf_profile.py \
  --mode explicit \
  --count 10000 \
  --no-results

Future Optimization Opportunities

  1. Parallel Resource Processing: Process resources in parallel during synthesis
  2. Incremental Synthesis: Only re-synthesize changed resources
  3. Native Extensions: Implement critical paths in Cython/Rust
  4. Resource Batching: Group similar resources for batch processing

Conclusion

The optimization efforts successfully reduced synthesis time by 20-29% while maintaining code quality and backward compatibility. The improvements are most significant for small to medium infrastructure definitions, which represent the most common use case.