paladin-ai 0.5.1

Enterprise AI orchestration framework with multi-agent coordination patterns
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# Production Best Practices

Comprehensive checklist and guidelines for deploying Paladin in production environments.

## Table of Contents

- [Pre-Deployment Checklist]#pre-deployment-checklist
- [Security]#security
- [Performance]#performance
- [Reliability]#reliability
- [Monitoring]#monitoring
- [Disaster Recovery]#disaster-recovery
- [Cost Optimization]#cost-optimization
- [Maintenance]#maintenance

## Pre-Deployment Checklist

### Infrastructure

- [ ] **Compute resources** sized appropriately (CPU, memory)
- [ ] **High availability** configured (multiple replicas/zones)
- [ ] **Auto-scaling** enabled with appropriate thresholds
- [ ] **Load balancing** configured with health checks
- [ ] **Network policies** restrict unnecessary traffic
- [ ] **TLS/SSL** certificates configured and valid
- [ ] **DNS** properly configured with failover

### Configuration

- [ ] **Environment variables** properly set (no hardcoded secrets)
- [ ] **Configuration files** validated and tested
- [ ] **API keys** rotated and secured
- [ ] **Log levels** set appropriately (warn/error in prod)
- [ ] **Resource limits** configured (CPU, memory, connections)
- [ ] **Timeouts** set for all external calls
- [ ] **Rate limits** configured to prevent abuse

### Data

- [ ] **Database backups** automated and tested
- [ ] **Volume backups** scheduled and verified
- [ ] **Backup retention** policy defined (7d/30d/365d)
- [ ] **Disaster recovery** plan documented and tested
- [ ] **Data encryption** at rest and in transit
- [ ] **Access controls** properly configured

### Monitoring

- [ ] **Health checks** configured and responding
- [ ] **Metrics collection** enabled (Prometheus/Grafana)
- [ ] **Log aggregation** configured (ELK/Loki)
- [ ] **Alerting** rules defined for critical metrics
- [ ] **On-call rotation** established
- [ ] **Incident response** procedures documented
- [ ] **SLO/SLA** defined and monitored

### Testing

- [ ] **Load testing** performed at expected scale
- [ ] **Integration tests** passing in staging
- [ ] **Rollback procedure** tested
- [ ] **Canary deployment** strategy defined
- [ ] **Blue-green deployment** capability verified
- [ ] **Smoke tests** automated post-deployment

## Security

### Authentication & Authorization

```yaml
# Use strong authentication
auth:
  type: "oauth2"
  provider: "auth0"
  scopes: ["paladin:read", "paladin:write"]

# Implement role-based access control
rbac:
  roles:
    - admin: ["*"]
    - user: ["paladin:execute", "garrison:read"]
    - viewer: ["paladin:read"]
```

### API Key Management

```bash
# Rotate API keys regularly
OPENAI_API_KEY=$(vault kv get -field=api_key secret/openai)
DEEPSEEK_API_KEY=$(vault kv get -field=api_key secret/deepseek)

# Use separate keys for different environments
staging_key="sk-proj-staging-..."
production_key="sk-proj-prod-..."
```

### Network Security

```yaml
# Kubernetes NetworkPolicy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: paladin-network-policy
spec:
  podSelector:
    matchLabels:
      app: paladin
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: ingress-nginx
    ports:
    - protocol: TCP
      port: 8080
  egress:
  - to:
    - namespaceSelector: {}
    ports:
    - protocol: TCP
      port: 443  # HTTPS only
```

### Container Security

```dockerfile
# Use specific versions (not latest)
FROM rust:1.70-slim-bullseye AS builder

# Run as non-root user
USER paladin:paladin

# Read-only filesystem
docker run --read-only --tmpfs /tmp paladin

# Drop capabilities
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE paladin

# Use security scanning
docker scan paladin:latest
snyk container test paladin:latest
```

### Secrets Management

```bash
# Use external secrets managers
# Kubernetes External Secrets
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
  name: paladin-secrets
spec:
  secretStoreRef:
    name: aws-secrets-manager
  target:
    name: paladin-secrets
  data:
  - secretKey: openai-api-key
    remoteRef:
      key: paladin/prod/openai-api-key

# HashiCorp Vault
vault kv put secret/paladin/prod \
  openai_api_key=sk-... \
  deepseek_api_key=...
```

## Performance

### Resource Allocation

```yaml
# Production resource configuration
resources:
  requests:
    cpu: 1000m      # 1 CPU guaranteed
    memory: 2Gi     # 2GB guaranteed
  limits:
    cpu: 4000m      # 4 CPU max
    memory: 8Gi     # 8GB max (OOM if exceeded)

# Horizontal Pod Autoscaler
autoscaling:
  enabled: true
  minReplicas: 5
  maxReplicas: 20
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80
```

### Connection Pooling

```rust,ignore
// Configure connection pools
let redis_config = RedisConfig {
    url: "redis://redis:6379".into(),
    pool_size: 20,
    connection_timeout: Duration::from_secs(5),
    idle_timeout: Some(Duration::from_secs(60)),
};

let minio_config = MinioConfig {
    endpoint: "minio:9000".into(),
    max_connections: 100,
    connection_timeout: Duration::from_secs(10),
};
```

### Caching Strategy

```yaml
# Redis caching configuration
cache:
  enabled: true
  ttl: 3600  # 1 hour
  max_size: 10000
  eviction_policy: "lru"

# Application-level caching
garrison:
  cache_embeddings: true
  cache_ttl: 86400  # 24 hours
```

### LLM Optimization

```yaml
# Optimize LLM calls
llm:
  timeout: 30s
  max_retries: 3
  retry_delay: 1s
  connection_pooling: true

  # Use faster models for simple tasks
  model_routing:
    simple_tasks: "gpt-3.5-turbo"
    complex_tasks: "gpt-4"

  # Batch similar requests
  batching:
    enabled: true
    max_batch_size: 10
    max_wait_time: 100ms
```

## Reliability

### Health Checks

```yaml
# Liveness probe (restart if fails)
livenessProbe:
  httpGet:
    path: /health/live
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10
  timeoutSeconds: 5
  failureThreshold: 3

# Readiness probe (remove from load balancer if fails)
readinessProbe:
  httpGet:
    path: /health/ready
    port: 8080
  initialDelaySeconds: 10
  periodSeconds: 5
  timeoutSeconds: 3
  failureThreshold: 3
  successThreshold: 1
```

### Graceful Shutdown

```rust,ignore
// Implement graceful shutdown
use tokio::signal;

async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }

    tracing::info!("Shutdown signal received, starting graceful shutdown");
}

// In main
let server = axum::Server::bind(&addr)
    .serve(app.into_make_service())
    .with_graceful_shutdown(shutdown_signal());
```

```yaml
# Kubernetes graceful termination
spec:
  terminationGracePeriodSeconds: 30
  containers:
  - lifecycle:
      preStop:
        exec:
          command: ["/bin/sh", "-c", "sleep 15"]
```

### Circuit Breakers

```rust,ignore
// Implement circuit breakers for external services
use circuit_breaker::{CircuitBreaker, Config};

let llm_breaker = CircuitBreaker::new(Config {
    failure_threshold: 5,
    success_threshold: 2,
    timeout: Duration::from_secs(60),
});

async fn call_llm_with_breaker(prompt: &str) -> Result<Response> {
    llm_breaker.call(async {
        llm_client.generate(prompt).await
    }).await
}
```

### Retry Logic

```rust,ignore
// Implement exponential backoff
use backoff::{ExponentialBackoff, Error as BackoffError};
use backoff::future::retry;

async fn call_with_retry<F, T>(f: F) -> Result<T>
where
    F: Fn() -> Result<T>,
{
    let backoff = ExponentialBackoff {
        max_elapsed_time: Some(Duration::from_secs(60)),
        max_interval: Duration::from_secs(30),
        ..Default::default()
    };

    retry(backoff, || async {
        f().map_err(|e| {
            if e.is_retryable() {
                BackoffError::Transient(e)
            } else {
                BackoffError::Permanent(e)
            }
        })
    }).await
}
```

## Monitoring

### Key Metrics

```yaml
# Application metrics
metrics:
  - paladin_requests_total          # Total requests
  - paladin_request_duration_seconds  # Request latency
  - paladin_errors_total            # Error count
  - paladin_active_paladins         # Active Paladins
  - garrison_entries_total          # Memory entries
  - arsenal_tool_calls_total        # Tool invocations

# System metrics
  - process_cpu_seconds_total       # CPU usage
  - process_resident_memory_bytes   # Memory usage
  - go_goroutines                   # Goroutines (if applicable)

# External dependencies
  - llm_api_calls_total             # LLM API calls
  - llm_api_duration_seconds        # LLM latency
  - redis_operations_total          # Redis ops
  - minio_operations_total          # MinIO ops
```

### Alerting Rules

```yaml
# Prometheus alerting rules
groups:
- name: paladin
  interval: 30s
  rules:
  - alert: HighErrorRate
    expr: rate(paladin_errors_total[5m]) > 0.05
    for: 5m
    labels:
      severity: critical
    annotations:
      summary: "High error rate detected"

  - alert: HighLatency
    expr: histogram_quantile(0.95, paladin_request_duration_seconds) > 2
    for: 10m
    labels:
      severity: warning
    annotations:
      summary: "High P95 latency (>2s)"

  - alert: PodCrashLooping
    expr: rate(kube_pod_container_status_restarts_total[15m]) > 0
    for: 15m
    labels:
      severity: critical
    annotations:
      summary: "Pod is crash looping"
```

### Logging Best Practices

```rust,ignore
// Structured logging with tracing
use tracing::{info, warn, error, instrument};

#[instrument(skip(paladin), fields(paladin_id = %paladin.id))]
async fn execute_paladin(paladin: &Paladin, input: &str) -> Result<PaladinResult> {
    info!("Starting paladin execution");

    match paladin.execute(input).await {
        Ok(result) => {
            info!(
                loops_used = result.loops_used,
                output_length = result.content.len(),
                "Paladin execution completed successfully"
            );
            Ok(result)
        }
        Err(e) => {
            error!(error = %e, "Paladin execution failed");
            Err(e)
        }
    }
}
```

```yaml
# Log aggregation configuration
logging:
  level: warn  # info in staging, warn in production
  format: json
  outputs:
    - type: stdout
    - type: file
      path: /app/logs/paladin.log
      rotation:
        max_size: 100MB
        max_age: 7d
        max_backups: 10
```

## Disaster Recovery

### Backup Strategy

```bash
# Automated backups
# 1. Database backups
0 2 * * * /scripts/backup-garrison-db.sh

# 2. Volume snapshots
kubectl exec -n paladin deployment/backup -- \
  /scripts/snapshot-volumes.sh

# 3. Configuration backups
kubectl get all,cm,secrets -n paladin -o yaml > backup-$(date +%Y%m%d).yaml
```

### Recovery Testing

```bash
# Quarterly disaster recovery drill
1. Simulate complete cluster failure
2. Restore from backups
3. Verify data integrity
4. Measure RTO (Recovery Time Objective)
5. Measure RPO (Recovery Point Objective)
6. Document lessons learned
```

### Multi-Region Deployment

```yaml
# Deploy to multiple regions
regions:
  - name: us-east-1
    primary: true
    replicas: 5
  - name: eu-west-1
    primary: false
    replicas: 3
  - name: ap-southeast-1
    primary: false
    replicas: 3

# Cross-region replication
replication:
  garrison: async  # Eventual consistency
  citadel: sync    # Strong consistency for checkpoints
```

## Cost Optimization

### Resource Right-Sizing

```bash
# Analyze actual usage
kubectl top pods -n paladin
kubectl describe hpa paladin -n paladin

# Adjust based on metrics
resources:
  requests:
    cpu: 800m    # Reduced from 1000m
    memory: 1.5Gi  # Reduced from 2Gi
```

### Auto-Scaling Policies

```yaml
# Aggressive scale-down for cost savings
autoscaling:
  scaleDown:
    stabilizationWindowSeconds: 600  # 10 minutes
    policies:
    - type: Percent
      value: 50
      periodSeconds: 300
```

### Spot Instances

```yaml
# Use spot instances for non-critical workloads
nodeSelector:
  kubernetes.io/lifecycle: spot

tolerations:
- key: spot
  operator: Equal
  value: "true"
  effect: NoSchedule
```

## Maintenance

### Update Strategy

```yaml
# Rolling update configuration
strategy:
  type: RollingUpdate
  rollingUpdate:
    maxSurge: 1        # One extra pod during update
    maxUnavailable: 0  # Zero downtime
```

### Maintenance Windows

```bash
# Schedule maintenance during low-traffic periods
# Example: Sundays 2-4 AM UTC
0 2 * * 0 /scripts/maintenance.sh
```

### Dependency Updates

```bash
# Regular dependency updates
dependabot.yml:
  version: 2
  updates:
    - package-ecosystem: "cargo"
      directory: "/"
      schedule:
        interval: "weekly"
      open-pull-requests-limit: 10
```

## Checklist Summary

Use this checklist before each production deployment:

```markdown
## Pre-Deployment
- [ ] All tests passing (unit, integration, e2e)
- [ ] Code review completed and approved
- [ ] Security scan passed (no high/critical vulnerabilities)
- [ ] Performance benchmarks within acceptable range
- [ ] Documentation updated
- [ ] Changelog updated

## Deployment
- [ ] Backup current state
- [ ] Deploy to staging first
- [ ] Run smoke tests in staging
- [ ] Deploy to production using rolling update
- [ ] Monitor metrics during rollout
- [ ] Verify health checks passing

## Post-Deployment
- [ ] Run smoke tests in production
- [ ] Check error rates and latency
- [ ] Verify auto-scaling working
- [ ] Confirm backups running
- [ ] Update runbook if needed
- [ ] Notify stakeholders of successful deployment
```

## Next Steps

- **[Monitoring](../operations/monitoring.md)** - Detailed monitoring setup
- **[Troubleshooting](../operations/troubleshooting.md)** - Common issues and solutions
- **[Performance Tuning](../operations/performance-tuning.md)** - Optimization guide