# Performance Optimization Guide

Optimize infrastructure for latency, throughput, and cost efficiency.

## Performance Profiling

### 1. Identify Bottlenecks

```nushell
def profile-infrastructure [] {
    print "Profiling infrastructure performance..."

    let metrics = (
        provisioning metrics collect \
            --duration 24h \
            --granularity 1m \
            --include-all
    )

    let slowest = (
        $metrics
        | group-by component
        | each { | group |
            {
                component: $group.0.component,
                avg_latency_ms: ($group | map .latency_ms | math avg),
                p99_latency_ms: ($group | map .latency_ms | math percentile 0.99),
                error_rate: ($group | map .errors | length) / ($group | length)
            }
        }
        | sort-by p99_latency_ms --reverse
    )

    print "Slowest Components (by P99 latency):"
    $slowest | table
}
```

### 2. Database Query Optimization

```bash
# Enable query logging for long queries
provisioning database config set \
    --database production \
    --setting log_min_duration_statement \
    --value 100

# Identify slow queries
provisioning database queries --sort duration --limit 10
```

## Optimization Techniques

### Caching Strategy

```nickel
{
  caching = {
    layers = [
      {
        name = "application_memory",
        ttl_seconds = 300,
        max_size_mb = 512,
        eviction_policy = "lru"
      },
      {
        name = "redis_cluster",
        ttl_seconds = 3600,
        max_size_mb = 16000,
        replication = true,
        cluster_mode = true
      },
      {
        name = "cdn_edge",
        ttl_seconds = 86400,
        geo_distributed = true,
        compression = "gzip"
      }
    ]
  }
}
```

### Database Indexing

```sql
CREATE INDEX idx_orders_user_id ON orders(user_id)
WHERE status = 'completed';

CREATE INDEX idx_metrics_timestamp_service
ON metrics(timestamp DESC, service_id)
INCLUDE (value, error_rate);

SELECT schemaname, tablename, indexname, idx_scan
FROM pg_stat_user_indexes
ORDER BY idx_scan DESC;
```

### Connection Pooling

```rust
use deadpool_postgres::Pool;

let config = deadpool_postgres::Config {
    dbname: Some("production".to_string()),
    user: Some("app".to_string()),
    host: Some("db.example.com".to_string()),
    port: Some(5432),
    pool: Some(deadpool_postgres::PoolConfig {
        max_size: 100,
        min_idle: Some(10),
        timeout: Some(Duration::from_secs(30)),
        ..Default::default()
    }),
    ..Default::default()
};

let pool = config.create_pool(NoTls, deadpool_postgres::Runtime::Tokio1)?;
```

## Application Performance

### Request Batching

```nushell
def fetch-user-data-batched [user_ids: list] {
    let placeholders = (
        $user_ids
        | enumerate
        | map { | ite| m $"($item.index + 1)" }
        | str join ", "
    )

    let query = $"SELECT * FROM users WHERE id IN ($placeholders)"
    provisioning database query --sql $query
}
```

### Async Operations

```rust
#[tokio::main]
async fn main() {
    let handles: Vec<_> = (0..100)
        .map| ( i| d {
            tokio::spawn(async move {
                fetch_user(id).await
            })
        })
        .collect();

    for handle in handles {
        handle.await.unwrap();
    }
}
```

## Infrastructure-Level Optimizations

### CPU Optimization

```nickel
{
  compute_optimization = {
    cpu_scaling = {
      enabled = true,
      policy = "performance",
      turbo_boost = true,
      idle_state = "c1"
    }
  }
}
```

### Memory Optimization

```bash
provisioning memory optimize --aggressive
echo 10 > /proc/sys/vm/swappiness
```

### Network Optimization

```bash
provisioning network tune --optimize latency
```

## Cost Optimization

### Resource Right-Sizing

```nushell
def rightsize-resources [] {
    print "Analyzing resource utilization..."

    let usage = (
        provisioning metrics get \
            --metric cpu_utilization \
            --dimension instance_type \
            --period 30d
    )

    $usage | each { | instance |
        if $instance.avg_utilization < 20 {
            print $"⚠️  Over-provisioned: ($instance.type)"
            print $"   Recommendation: Downsize to smaller type"
        }
    }
}
```

### Spot Instance Strategy

```nickel
{
  cost_optimization = {
    spot_instances = {
      enabled = true,
      percentage = 60,
      target_savings = 0.70,
      interruption_tolerance = true
    }
  }
}
```

## Performance SLOs

| Metric | Target | Measurement |
| -------| - -------| - ------------- |
| API Latency (P99) | <200ms | Response time percentile |
| Database Query (P99) | <100ms | Query execution time |
| Cache Hit Rate | >90% | Successful cache hits |
| Error Rate | <0.1% | Errors per total requests |
| Throughput | >1,000 req/s | Requests per second |

## Benchmarking

```nushell
def benchmark-deployment [] {
    print "Running performance benchmark..."

    let results = (
        provisioning test benchmark \
            --concurrent-users 100 \
            --duration 5m \
            --ramp-up 1m
    )

    print "Benchmark Results:"
    print $"Response Time (Avg): ($results.avg_latency_ms)ms"
    print $"Response Time (P95): ($results.p95_latency_ms)ms"
    print $"Response Time (P99): ($results.p99_latency_ms)ms"
    print $"Throughput: ($results.throughput) req/s"
    print $"Error Rate: ($results.error_rate)%"
}
```

## See Also

- [Monitoring Guide](./monitoring.md)
- [Capacity Planning](./capacity-planning.md)
- [Cost Optimization Examples](../examples/cost-optimization-examples.md)
