# Design Patterns

Common patterns and best practices in Provisioning infrastructure.

## Stateless Service Pattern

Design services that can be scaled horizontally:

```nickel
{
  patterns = {
    stateless = {
      description = "Services with no local state",
      principles = [
        "Store state in external databases",
        "Sessions stored in Redis/DynamoDB",
        "No local file storage",
        "Horizontally scalable"
      ],

      example = {
        servers = [
          { name = "api-01", stateless = true },
          { name = "api-02", stateless = true },
          { name = "api-03", stateless = true }
        ],

        state_storage = {
          sessions = "redis-cluster",
          data = "postgres-database"
        }
      }
    }
  }
}
```

## Circuit Breaker Pattern

Prevent cascading failures:

```nickel
{
  patterns = {
    circuit_breaker = {
      description = "Fail fast to prevent downstream impact",

      states = {
        closed = "Normal operation, requests pass through",
        open = "Failure threshold reached, requests rejected",
        half_open = "Test if service recovered"
      },

      configuration = {
        failure_threshold = 5,
        success_threshold = 3,
        timeout = 60
      }
    }
  }
}
```

## Retry with Exponential Backoff

Gracefully handle transient failures:

```nushell
def retry-with-backoff [operation max-retries] {
  let mut attempt = 0

  loop {
    try {
      return ($operation)
    } catch { | err |
      $attempt += 1
      if $attempt >= $max_retries {
        error "Max retries exceeded"
      }

      let delay = (2 | math pow $attempt)  # 2^n exponential
      sleep ($delay | into duration --unit s)
    }
  }
}
```

## CQRS Pattern

Separate read and write models:

```nickel
{
  cqrs = {
    # Write model
    write = {
      database = "postgres-primary",
      transactions = "required",
      consistency = "strong"
    },

    # Read model
    read = {
      database = "elasticsearch",
      updates = "eventual",
      consistency = "eventual"
    },

    # Sync between models
    event_stream = "kafka-topic-changes"
  }
}
```

## Bulkhead Pattern

Isolate critical resources:

```nickel
{
  bulkheads = [
    {
      name = "critical-services",
      services = ["auth", "payment"],
      resources = { cpu: "4", memory: "8Gi" },
      separate_network = true
    },
    {
      name = "batch-processing",
      services = ["reports", "data-processing"],
      resources = { cpu: "8", memory: "16Gi" },
      separate_network = true
    }
  ]
}
```

## Related Documentation

- [Architecture Overview](./system-overview.md)
- [Integration Patterns](./integration-patterns.md)
- [Feature System](../features/cli-architecture.md)
