Skip to content

Synthesis Performance Optimization Plan

Target: 100x Performance Improvement (66s → 0.66s for 10K resources)

Current Performance Profile (10K resources)

  • Total synthesis time: 66.2 seconds
  • Hash computation: 11.3s (39.5s cumulative due to recursion)
  • Type checking: 39.6s cumulative (3.9M isinstance calls)
  • JSON serialization: ~5-10s
  • Config building: ~4-5s

Root Cause Analysis

1. Recursive Hash Computation (60% of time)

  • _compute_hash() is called recursively for every child construct
  • 10K resources = 30K+ hash computations (due to nested calls)
  • Each hash computation traverses the entire subtree
  • Problem: O(n²) complexity for n resources

2. Excessive Type Checking (25% of time)

  • 3.9 million isinstance() calls for 10K resources
  • Heavy use of typing module's runtime checking
  • Type checks in hot paths during serialization

3. Inefficient Config Building (10% of time)

  • _to_config_cached() still computes hash for cache validation
  • Deep copying of configs
  • Multiple passes over resource collections

Optimization Strategy for 100x Improvement

Phase 1: Eliminate Recursive Hashing (Target: 20x improvement)

A. Incremental Hash Updates (Highest Impact)

class Construct:
    def __init__(self):
        self._hash_dirty = True
        self._cached_hash = None
        self._parent_hash_version = 0

    def _invalidate_hash(self):
        """Mark hash as dirty and propagate up"""
        self._hash_dirty = True
        if self._parent:
            self._parent._invalidate_hash()

    def _compute_hash_fast(self):
        """Compute hash without recursion"""
        if not self._hash_dirty and self._cached_hash:
            return self._cached_hash

        # Only hash this node's data, not children
        hasher = hashlib.sha256()
        hasher.update(self.__class__.__name__.encode())
        hasher.update(self.nf_id.encode())

        # Hash only direct attributes
        if hasattr(self, "_config"):
            # Use pickle for fast serialization
            hasher.update(pickle.dumps(self._config, protocol=5))

        self._cached_hash = hasher.hexdigest()[:16]
        self._hash_dirty = False
        return self._cached_hash

B. Pre-computed Stack Hash

class Stack:
    def _compute_stack_hash(self):
        """Compute stack hash in O(n) instead of O(n²)"""
        # Single pass to collect all hashes
        all_hashes = []
        for resource in self._resources.values():
            all_hashes.append(resource._compute_hash_fast())

        # Combine in single operation
        combined = "".join(sorted(all_hashes))
        return hashlib.sha256(combined.encode()).hexdigest()[:16]

Phase 2: Eliminate Runtime Type Checking (Target: 5x improvement)

A. Remove isinstance() from Hot Paths

# Instead of:
if isinstance(value, RuntimeValue):
    # handle RuntimeValue
    pass
elif isinstance(value, dict):
    # handle dict
    pass


# Use type flags:
class RuntimeValue:
    __slots__ = ["_is_runtime_value", "value"]

    def __init__(self):
        self._is_runtime_value = True


# Fast check:
if hasattr(value, "_is_runtime_value"):
    # handle RuntimeValue
    pass
elif type(value) is dict:  # Direct type check, not isinstance
    # handle dict
    pass

B. Batch Type Checking

def categorize_values(values):
    """Categorize all values in one pass"""
    runtime_values = []
    dicts = []
    lists = []
    primitives = []

    for v in values:
        if hasattr(v, "_is_runtime_value"):
            runtime_values.append(v)
        elif type(v) is dict:
            dicts.append(v)
        elif type(v) in (list, tuple):
            lists.append(v)
        else:
            primitives.append(v)

    return runtime_values, dicts, lists, primitives

Phase 3: Optimize Serialization (Target: 10x improvement)

A. Pre-serialization Structure

class Stack:
    def _prepare_for_serialization(self):
        """Build optimized structure for JSON serialization"""
        # Pre-allocate the entire structure
        result = {"terraform": {}, "resource": {}, "data": {}, "output": {}}

        # Single pass to populate
        for resource in self._resources.values():
            rtype = resource._resource_type
            if rtype not in result["resource"]:
                result["resource"][rtype] = {}

            # Direct assignment, no intermediate objects
            result["resource"][rtype][resource.nf_id] = resource._config

        return result

B. Direct Memory Serialization

def serialize_fast(config):
    """Ultra-fast JSON serialization"""
    # Use msgpack for binary serialization (10x faster than JSON)
    import msgpack

    # Or use optimized JSON with pre-allocated buffer
    import rapidjson

    return rapidjson.dumps(config, ensure_ascii=False, number_mode=rapidjson.NM_NATIVE)

Phase 4: Parallel Processing (Target: 4x improvement)

A. Parallel Resource Processing

from concurrent.futures import ThreadPoolExecutor
import multiprocessing


class Stack:
    def _build_configs_parallel(self):
        """Build resource configs in parallel"""
        # Use process pool for CPU-bound work
        with multiprocessing.Pool() as pool:
            # Batch resources for processing
            batches = [self._resources[i : i + 100] for i in range(0, len(self._resources), 100)]

            # Process batches in parallel
            results = pool.map(self._process_resource_batch, batches)

            # Merge results
            return self._merge_configs(results)

B. Async I/O for File Writing

import aiofiles
import anyio


async def write_json_async(path, data):
    """Write JSON asynchronously"""
    async with aiofiles.open(path, "wb") as f:
        # Serialize in thread pool
        json_bytes = await anyio.to_thread.run_sync(orjson.dumps, data, option=orjson.OPT_INDENT_2)
        await f.write(json_bytes)

Phase 5: Memory Optimization (Supporting improvement)

A. Object Pooling

class ConfigPool:
    """Reuse config dictionaries"""

    def __init__(self):
        self.pool = []

    def get(self):
        if self.pool:
            return self.pool.pop()
        return {}

    def release(self, config):
        config.clear()
        self.pool.append(config)


# Global pool
_config_pool = ConfigPool()

B. Lazy Attribute Loading

class Resource:
    __slots__ = ["_id", "_type", "_config_loader"]

    def __init__(self):
        self._config_loader = None  # Lazy load config

    @property
    def config(self):
        if self._config_loader:
            return self._config_loader()
        return {}

Implementation Priority

Quick Wins (1-2 days, 10-20x improvement)

  1. Eliminate recursive hashing - Replace with incremental hashing
  2. Remove isinstance() checks - Use type flags
  3. Switch to orjson - Already partially done

Medium Effort (3-5 days, 5-10x improvement)

  1. Batch operations - Process resources in batches
  2. Pre-serialization structure - Build optimal structure for JSON
  3. Parallel resource processing - Use multiprocessing

Larger Changes (1 week, 2-5x improvement)

  1. Memory pooling - Reuse objects
  2. Async I/O - Non-blocking file operations
  3. Custom serialization - Binary formats or custom JSON encoder

Proof of Concept Code

# Quick test to validate approach
import time
import hashlib
import orjson


class OptimizedStack:
    def __init__(self):
        self._resources = {}
        self._hash_cache = {}

    def add_resource(self, resource):
        self._resources[resource.id] = resource
        # Invalidate only stack hash, not all children
        self._stack_hash = None

    def synthesize_optimized(self):
        # 1. Build config in single pass (no recursion)
        config = self._build_flat_config()

        # 2. Serialize with orjson (already fast)
        json_bytes = orjson.dumps(config)

        return json_bytes

    def _build_flat_config(self):
        """Build config without recursion or type checking"""
        result = {"resource": {}}

        # Single pass, no type checking
        for rid, resource in self._resources.items():
            rtype = resource.type
            if rtype not in result["resource"]:
                result["resource"][rtype] = {}
            result["resource"][rtype][rid] = resource.config

        return result


# Benchmark
def benchmark_optimized(count):
    stack = OptimizedStack()

    # Add resources
    for i in range(count):
        stack.add_resource(SimpleResource(f"r_{i}", "test", {"index": i}))

    # Time synthesis
    start = time.perf_counter()
    result = stack.synthesize_optimized()
    elapsed = time.perf_counter() - start

    print(f"Optimized synthesis for {count} resources: {elapsed:.3f}s")
    return elapsed

Expected Results

With all optimizations implemented: - 10K resources: 66s → 0.5-1.0s (66-132x improvement) - 1K resources: 6.7s → 0.05-0.1s (67-134x improvement) - 100 resources: 0.3s → 0.005s (60x improvement)

Next Steps

  1. Implement incremental hashing (biggest win)
  2. Remove isinstance() from hot paths
  3. Benchmark each optimization in isolation
  4. Combine optimizations and measure cumulative effect
  5. Profile to identify any remaining bottlenecks