solana-recover 1.1.3

A comprehensive Solana wallet recovery and account management tool
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
# Deployment Guide

This guide covers deploying Solana Recover to production environments. Solana Recover is a production-ready, high-performance system for scanning Solana wallets and recovering SOL from empty token accounts, with full Turnkey integration and enterprise-grade security.

## Table of Contents

- [Deployment Options]#deployment-options
- [System Requirements]#system-requirements
- [Environment Configuration]#environment-configuration
- [Docker Deployment]#docker-deployment
- [Kubernetes Deployment]#kubernetes-deployment
- [Cloud Platform Deployment]#cloud-platform-deployment
- [Monitoring and Logging]#monitoring-and-logging
- [Security Considerations]#security-considerations
- [Performance Tuning]#performance-tuning
- [Backup and Recovery]#backup-and-recovery
- [Maintenance]#maintenance

## Deployment Options

### Recommended Deployments

1. **Docker Compose** - Small to medium deployments
2. **Kubernetes** - Large-scale, containerized deployments
3. **Cloud Services** - Managed solutions
4. **Bare Metal** - On-premises deployments

### Deployment Architecture

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Load Balancer │    │   Web Frontend  │    │   Mobile Apps   │
└─────────┬───────┘    └─────────┬───────┘    └─────────┬───────┘
          │                      │                      │
          └──────────────────────┼──────────────────────┘
                    ┌─────────────┴─────────────┐
                    │   API Gateway/Proxy       │
                    │  (nginx, traefik, etc.)   │
                    └─────────────┬─────────────┘
                    ┌─────────────┴─────────────┐
                    │   Solana Recover API      │
                    │  (Multiple Instances)     │
                    └─────────────┬─────────────┘
                    ┌─────────────┴─────────────┐
                    │   Database & Cache        │
                    │  (PostgreSQL, Redis)      │
                    └─────────────┬─────────────┘
                    ┌─────────────┴─────────────┐
                    │   Monitoring & Logging    │
                    │ (Prometheus, Grafana)     │
                    └───────────────────────────┘
```

## System Requirements

### Minimum Requirements

- **CPU**: 2 cores
- **Memory**: 4GB RAM
- **Storage**: 50GB SSD
- **Network**: 100 Mbps

### Recommended Requirements

- **CPU**: 4+ cores
- **Memory**: 8GB+ RAM
- **Storage**: 100GB+ SSD
- **Network**: 1 Gbps

### High-Performance Requirements

- **CPU**: 8+ cores
- **Memory**: 16GB+ RAM
- **Storage**: 500GB+ NVMe SSD
- **Network**: 10 Gbps

### Software Dependencies

- **Docker**: 20.10+
- **Docker Compose**: 2.0+
- **Kubernetes**: 1.24+ (if using K8s)
- **PostgreSQL**: 13+ (for production database)
- **Redis**: 6+ (for caching)

## Environment Configuration

### Environment Variables

Create a `.env` file for your deployment:

```bash
# Application Configuration
SOLANA_RECOVER_ENV=production
SOLANA_RECOVER_LOG_LEVEL=info
SOLANA_RECOVER_PORT=8080
SOLANA_RECOVER_HOST=0.0.0.0

# Database Configuration
DATABASE_URL=postgresql://user:password@postgres:5432/solana_recover
DATABASE_POOL_SIZE=20
DATABASE_TIMEOUT_SECONDS=30

# Redis Configuration
REDIS_URL=redis://redis:6379
REDIS_POOL_SIZE=10

# Solana RPC Configuration
SOLANA_RPC_ENDPOINTS=https://api.mainnet-beta.solana.com,https://solana-api.projectserum.com
SOLANA_RPC_POOL_SIZE=50
SOLANA_RPC_TIMEOUT_MS=5000
SOLANA_RPC_RATE_LIMIT_RPS=100

# Turnkey Configuration
TURNKEY_API_URL=https://api.turnkey.com
TURNKEY_ORG_ID=your-org-id
TURNKEY_API_KEY=your-api-key
TURNKEY_PRIVATE_KEY_ID=your-key-id

# Security Configuration
JWT_SECRET=your-super-secret-jwt-key
API_KEY_ENCRYPTION_KEY=your-32-character-encryption-key
CORS_ORIGINS=https://yourdomain.com,https://app.yourdomain.com

# Monitoring Configuration
METRICS_ENABLED=true
METRICS_PORT=9090
HEALTH_CHECK_INTERVAL=30

# Performance Configuration
MAX_CONCURRENT_WALLETS=1000
BATCH_SIZE=100
CACHE_TTL_SECONDS=300
```

### Configuration Files

#### Production Config (`config/production.toml`)

```toml
[server]
host = "0.0.0.0"
port = 8080
workers = 8
timeout_seconds = 60

[database]
url = "${DATABASE_URL}"
pool_size = 20
timeout_seconds = 30
migration_auto = true

[redis]
url = "${REDIS_URL}"
pool_size = 10
timeout_seconds = 5

[rpc]
endpoints = ["https://api.mainnet-beta.solana.com", "https://solana-api.projectserum.com"]
pool_size = 50
timeout_ms = 5000
rate_limit_rps = 100
health_check_interval_seconds = 30

[scanner]
batch_size = 100
max_concurrent_wallets = 1000
retry_attempts = 3
retry_delay_ms = 1000

[fees]
default_percentage = 0.15
minimum_lamports = 1000000
waive_below_lamports = 10000000

[security]
jwt_secret = "${JWT_SECRET}"
api_key_encryption_key = "${API_KEY_ENCRYPTION_KEY}"
cors_origins = ["https://yourdomain.com"]

[monitoring]
metrics_enabled = true
metrics_port = 9090
health_check_interval = 30
log_level = "info"

[cache]
ttl_seconds = 300
max_size = 10000
```

## Docker Deployment

### Dockerfile

```dockerfile
# Multi-stage build for production
FROM rust:1.75-slim as builder

WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY src ./src
COPY config ./config

# Build the application
RUN cargo build --release

# Production image
FROM debian:bookworm-slim

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    ca-certificates \
    libssl1.1 \
    && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN useradd -m -u 1000 solana

# Copy application
COPY --from=builder /app/target/release/solana-recover /usr/local/bin/
COPY --from=builder /app/config ./config

# Set permissions
RUN chown -R solana:solana /app
USER solana

# Expose ports
EXPOSE 8080 9090

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

# Start the application
CMD ["solana-recover", "server", "--config", "config/production.toml"]
```

### Docker Compose

Create `docker-compose.yml`:

```yaml
version: '3.8'

services:
  solana-recover:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
      - "9090:9090"
    environment:
      - DATABASE_URL=postgresql://postgres:${POSTGRES_PASSWORD}@postgres:5432/solana_recover
      - REDIS_URL=redis://redis:6379
      - JWT_SECRET=${JWT_SECRET}
      - API_KEY_ENCRYPTION_KEY=${API_KEY_ENCRYPTION_KEY}
    env_file:
      - .env
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    restart: unless-stopped
    networks:
      - solana-network
    volumes:
      - ./config:/app/config:ro
      - ./logs:/app/logs

  postgres:
    image: postgres:15-alpine
    environment:
      - POSTGRES_DB=solana_recover
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./scripts/init.sql:/docker-entrypoint-initdb.d/init.sql
    networks:
      - solana-network
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    command: redis-server --appendonly yes
    volumes:
      - redis_data:/data
    networks:
      - solana-network
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/ssl:/etc/nginx/ssl:ro
    depends_on:
      - solana-recover
    networks:
      - solana-network
    restart: unless-stopped

  prometheus:
    image: prom/prometheus:latest
    ports:
      - "9091:9090"
    volumes:
      - ./monitoring/prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - prometheus_data:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
      - '--web.console.libraries=/etc/prometheus/console_libraries'
      - '--web.console.templates=/etc/prometheus/consoles'
    networks:
      - solana-network
    restart: unless-stopped

  grafana:
    image: grafana/grafana:latest
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
    volumes:
      - grafana_data:/var/lib/grafana
      - ./monitoring/grafana/dashboards:/etc/grafana/provisioning/dashboards:ro
      - ./monitoring/grafana/datasources:/etc/grafana/provisioning/datasources:ro
    networks:
      - solana-network
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:
  prometheus_data:
  grafana_data:

networks:
  solana-network:
    driver: bridge
```

### Deployment Commands

```bash
# Build and start services
docker-compose up -d --build

# View logs
docker-compose logs -f solana-recover

# Scale the application
docker-compose up -d --scale solana-recover=3

# Update the application
docker-compose pull
docker-compose up -d

# Backup database
docker-compose exec postgres pg_dump -U postgres solana_recover > backup.sql

# Restore database
docker-compose exec -T postgres psql -U postgres solana_recover < backup.sql
```

## Kubernetes Deployment

### Namespace

```yaml
# namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
  name: solana-recover
  labels:
    name: solana-recover
```

### ConfigMap

```yaml
# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: solana-recover-config
  namespace: solana-recover
data:
  production.toml: |
    [server]
    host = "0.0.0.0"
    port = 8080
    workers = 8

    [database]
    url = "${DATABASE_URL}"
    pool_size = 20

    [redis]
    url = "${REDIS_URL}"
    pool_size = 10

    [rpc]
    endpoints = ["https://api.mainnet-beta.solana.com"]
    pool_size = 50
    timeout_ms = 5000
    rate_limit_rps = 100

    [scanner]
    batch_size = 100
    max_concurrent_wallets = 1000
    retry_attempts = 3
    retry_delay_ms = 1000

    [fees]
    default_percentage = 0.15
    minimum_lamports = 1000000
    waive_below_lamports = 10000000
```

### Secret

```yaml
# secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: solana-recover-secrets
  namespace: solana-recover
type: Opaque
data:
  database-url: <base64-encoded-database-url>
  jwt-secret: <base64-encoded-jwt-secret>
  api-key-encryption-key: <base64-encoded-encryption-key>
```

### Deployment

```yaml
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: solana-recover
  namespace: solana-recover
  labels:
    app: solana-recover
spec:
  replicas: 3
  selector:
    matchLabels:
      app: solana-recover
  template:
    metadata:
      labels:
        app: solana-recover
    spec:
      containers:
      - name: solana-recover
        image: solana-recover:latest
        ports:
        - containerPort: 8080
        - containerPort: 9090
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: solana-recover-secrets
              key: database-url
        - name: JWT_SECRET
          valueFrom:
            secretKeyRef:
              name: solana-recover-secrets
              key: jwt-secret
        - name: API_KEY_ENCRYPTION_KEY
          valueFrom:
            secretKeyRef:
              name: solana-recover-secrets
              key: api-key-encryption-key
        volumeMounts:
        - name: config
          mountPath: /app/config
        resources:
          requests:
            memory: "512Mi"
            cpu: "250m"
          limits:
            memory: "1Gi"
            cpu: "500m"
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
      volumes:
      - name: config
        configMap:
          name: solana-recover-config
```

### Service

```yaml
# service.yaml
apiVersion: v1
kind: Service
metadata:
  name: solana-recover-service
  namespace: solana-recover
spec:
  selector:
    app: solana-recover
  ports:
  - name: http
    port: 80
    targetPort: 8080
  - name: metrics
    port: 9090
    targetPort: 9090
  type: ClusterIP
```

### Ingress

```yaml
# ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: solana-recover-ingress
  namespace: solana-recover
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/rate-limit: "100"
spec:
  tls:
  - hosts:
    - api.solana-recover.com
    secretName: solana-recover-tls
  rules:
  - host: api.solana-recover.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: solana-recover-service
            port:
              number: 80
```

### Horizontal Pod Autoscaler

```yaml
# hpa.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: solana-recover-hpa
  namespace: solana-recover
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: solana-recover
  minReplicas: 3
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80
```

### Deployment Commands

```bash
# Apply all configurations
kubectl apply -f namespace.yaml
kubectl apply -f configmap.yaml
kubectl apply -f secret.yaml
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
kubectl apply -f ingress.yaml
kubectl apply -f hpa.yaml

# Check deployment status
kubectl get pods -n solana-recover
kubectl get services -n solana-recover
kubectl get ingress -n solana-recover

# View logs
kubectl logs -f deployment/solana-recover -n solana-recover

# Scale deployment
kubectl scale deployment solana-recover --replicas=5 -n solana-recover

# Update deployment
kubectl set image deployment/solana-recover solana-recover=solana-recover:v1.2.0 -n solana-recover
```

## Cloud Platform Deployment

### AWS Deployment

#### Using ECS (Elastic Container Service)

```json
{
  "family": "solana-recover",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "512",
  "memory": "1024",
  "executionRoleArn": "arn:aws:iam::account:role/ecsTaskExecutionRole",
  "taskRoleArn": "arn:aws:iam::account:role/ecsTaskRole",
  "containerDefinitions": [
    {
      "name": "solana-recover",
      "image": "your-account.dkr.ecr.region.amazonaws.com/solana-recover:latest",
      "portMappings": [
        {
          "containerPort": 8080,
          "protocol": "tcp"
        }
      ],
      "environment": [
        {
          "name": "DATABASE_URL",
          "value": "postgresql://user:pass@rds-endpoint:5432/db"
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "/ecs/solana-recover",
          "awslogs-region": "us-west-2",
          "awslogs-stream-prefix": "ecs"
        }
      },
      "healthCheck": {
        "command": ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"],
        "interval": 30,
        "timeout": 5,
        "retries": 3
      }
    }
  ]
}
```

#### Infrastructure as Code (Terraform)

```hcl
# main.tf
provider "aws" {
  region = var.aws_region
}

# VPC
resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name = "solana-recover-vpc"
  }
}

# ECS Cluster
resource "aws_ecs_cluster" "main" {
  name = "solana-recover"

  setting {
    name  = "containerInsights"
    value = "enabled"
  }
}

# RDS Database
resource "aws_db_instance" "postgres" {
  identifier     = "solana-recover-db"
  engine         = "postgres"
  engine_version = "15.3"
  instance_class = "db.t3.micro"
  
  allocated_storage     = 20
  max_allocated_storage  = 100
  storage_encrypted      = true
  storage_type          = "gp2"
  
  db_name  = "solana_recover"
  username = var.db_username
  password = var.db_password
  
  vpc_security_group_ids = [aws_security_group.rds.id]
  db_subnet_group_name   = aws_db_subnet_group.main.name
  
  backup_retention_period = 7
  backup_window          = "03:00-04:00"
  maintenance_window     = "sun:04:00-sun:05:00"
  
  skip_final_snapshot = true
  
  tags = {
    Name = "solana-recover-db"
  }
}

# ElastiCache Redis
resource "aws_elasticache_subnet_group" "main" {
  name       = "solana-recover-cache-subnet"
  subnet_ids = aws_subnet.private[*].id
}

resource "aws_elasticache_cluster" "redis" {
  cluster_id           = "solana-recover-redis"
  engine               = "redis"
  node_type            = "cache.t3.micro"
  num_cache_nodes      = 1
  parameter_group_name = "default.redis7"
  port                 = 6379
  subnet_group_name    = aws_elasticache_subnet_group.main.name
  security_group_ids   = [aws_security_group.redis.id]
  
  tags = {
    Name = "solana-recover-redis"
  }
}

# Application Load Balancer
resource "aws_lb" "main" {
  name               = "solana-recover-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb.id]
  subnets            = aws_subnet.public[*].id

  enable_deletion_protection = false

  tags = {
    Name = "solana-recover-alb"
  }
}

# ECS Service
resource "aws_ecs_service" "main" {
  name            = "solana-recover"
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.main.arn
  desired_count   = 2
  launch_type     = "FARGATE"

  network_configuration {
    subnets          = aws_subnet.private[*].id
    security_groups  = [aws_security_group.ecs.id]
    assign_public_ip = false
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.main.arn
    container_name   = "solana-recover"
    container_port   = 8080
  }

  depends_on = [aws_lb_listener.main]
}
```

### Google Cloud Platform

#### Cloud Run Deployment

```bash
# Build and push image
gcloud builds submit --tag gcr.io/PROJECT-ID/solana-recover

# Deploy to Cloud Run
gcloud run deploy solana-recover \
  --image gcr.io/PROJECT-ID/solana-recover \
  --platform managed \
  --region us-central1 \
  --allow-unauthenticated \
  --memory 1Gi \
  --cpu 1 \
  --max-instances 100 \
  --min-instances 0 \
  --set-env-vars DATABASE_URL=postgresql://...,REDIS_URL=redis://...
```

### Azure Container Instances

```yaml
# azure-deployment.yaml
apiVersion: 2019-12-01
location: eastus
name: solana-recover-group
properties:
  containers:
  - name: solana-recover
    properties:
      image: solana-recover:latest
      ports:
      - port: 8080
      resources:
        requests:
          cpu: 1.0
          memoryInGb: 2.0
      environmentVariables:
      - name: DATABASE_URL
        secureValue: your-connection-string
  osType: Linux
  restartPolicy: Always
  ipAddress:
    type: Public
    ports:
    - port: 8080
      protocol: TCP
tags: {}
type: Microsoft.ContainerInstance/containerGroups
```

## Monitoring and Logging

### Prometheus Configuration

```yaml
# prometheus.yml
global:
  scrape_interval: 15s
  evaluation_interval: 15s

rule_files:
  - "solana_recover_rules.yml"

scrape_configs:
  - job_name: 'solana-recover'
    static_configs:
      - targets: ['solana-recover:9090']
    metrics_path: /metrics
    scrape_interval: 10s

  - job_name: 'postgres'
    static_configs:
      - targets: ['postgres-exporter:9187']

  - job_name: 'redis'
    static_configs:
      - targets: ['redis-exporter:9121']

alerting:
  alertmanagers:
    - static_configs:
        - targets:
          - alertmanager:9093
```

### Grafana Dashboard

```json
{
  "dashboard": {
    "title": "Solana Recover Dashboard",
    "panels": [
      {
        "title": "Request Rate",
        "type": "graph",
        "targets": [
          {
            "expr": "rate(solana_recover_requests_total[5m])",
            "legendFormat": "{{method}} {{status}}"
          }
        ]
      },
      {
        "title": "Response Time",
        "type": "graph",
        "targets": [
          {
            "expr": "histogram_quantile(0.95, rate(solana_recover_request_duration_seconds_bucket[5m]))",
            "legendFormat": "95th percentile"
          }
        ]
      },
      {
        "title": "Active Scans",
        "type": "singlestat",
        "targets": [
          {
            "expr": "solana_recover_active_scans",
            "legendFormat": "Active Scans"
          }
        ]
      }
    ]
  }
}
```

### Logging Configuration

```yaml
# docker-compose.logging.yml
version: '3.8'

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.5.0
    environment:
      - discovery.type=single-node
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    volumes:
      - elasticsearch_data:/usr/share/elasticsearch/data
    networks:
      - logging

  logstash:
    image: docker.elastic.co/logstash/logstash:8.5.0
    volumes:
      - ./logstash/pipeline:/usr/share/logstash/pipeline:ro
    networks:
      - logging
    depends_on:
      - elasticsearch

  kibana:
    image: docker.elastic.co/kibana/kibana:8.5.0
    ports:
      - "5601:5601"
    environment:
      - ELASTICSEARCH_HOSTS=http://elasticsearch:9200
    networks:
      - logging
    depends_on:
      - elasticsearch

volumes:
  elasticsearch_data:

networks:
  logging:
    driver: bridge
```

## Security Considerations

### Network Security

```yaml
# nginx.conf
server {
    listen 443 ssl http2;
    server_name api.solana-recover.com;

    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;

    # Security headers
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req zone=api burst=20 nodelay;

    location / {
        proxy_pass http://solana-recover:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
```

### Secrets Management

```bash
# Using Kubernetes Secrets
kubectl create secret generic solana-recover-secrets \
  --from-literal=database-url="postgresql://..." \
  --from-literal=jwt-secret="your-jwt-secret" \
  --from-literal=api-key-encryption-key="your-encryption-key"

# Using AWS Secrets Manager
aws secretsmanager create-secret \
  --name solana-recover/production \
  --secret-string '{"database_url":"...","jwt_secret":"..."}'
```

## Performance Tuning

### Database Optimization

```sql
-- PostgreSQL optimization
-- Create indexes for common queries
CREATE INDEX CONCURRENTLY idx_wallet_scans_address ON wallet_scans(wallet_address);
CREATE INDEX CONCURRENTLY idx_wallet_scans_created_at ON wallet_scans(created_at);

-- Partition large tables
CREATE TABLE wallet_scans_partitioned (
    LIKE wallet_scans INCLUDING ALL
) PARTITION BY RANGE (created_at);

-- Connection pooling configuration
ALTER SYSTEM SET max_connections = 200;
ALTER SYSTEM SET shared_buffers = '256MB';
ALTER SYSTEM SET effective_cache_size = '1GB';
```

### Application Tuning

```toml
# Performance configuration
[server]
workers = 8
timeout_seconds = 60

[database]
pool_size = 20
timeout_seconds = 30
statement_timeout_seconds = 30

[scanner]
batch_size = 200
max_concurrent_wallets = 2000
queue_size = 10000

[cache]
ttl_seconds = 600
max_size = 50000
```

## Backup and Recovery

### Database Backups

```bash
# Automated backup script
#!/bin/bash
BACKUP_DIR="/backups/solana-recover"
DATE=$(date +%Y%m%d_%H%M%S)

# Create backup
docker-compose exec -T postgres pg_dump -U postgres solana_recover | gzip > "$BACKUP_DIR/backup_$DATE.sql.gz"

# Retention policy (keep 30 days)
find "$BACKUP_DIR" -name "backup_*.sql.gz" -mtime +30 -delete

# Upload to cloud storage (optional)
aws s3 cp "$BACKUP_DIR/backup_$DATE.sql.gz" s3://your-backup-bucket/
```

### Disaster Recovery

```yaml
# disaster-recovery.yaml
apiVersion: v1
kind: Pod
metadata:
  name: disaster-recovery
spec:
  containers:
  - name: recovery
    image: postgres:15-alpine
    command: ["/bin/bash"]
    args: ["-c", "while true; do sleep 30; done"]
    volumeMounts:
    - name: backup-storage
      mountPath: /backups
  volumes:
  - name: backup-storage
    persistentVolumeClaim:
      claimName: backup-pvc
```

## Maintenance

### Health Checks

```bash
# Health check script
#!/bin/bash

# Check API health
curl -f http://localhost:8080/health || exit 1

# Check database connectivity
docker-compose exec postgres pg_isready -U postgres || exit 1

# Check Redis connectivity
docker-compose exec redis redis-cli ping || exit 1

# Check metrics endpoint
curl -f http://localhost:9090/metrics || exit 1

echo "All health checks passed"
```

### Rolling Updates

```bash
# Zero-downtime deployment
#!/bin/bash

# Pull new image
docker-compose pull solana-recover

# Update service one container at a time
docker-compose up -d --no-deps solana-recover

# Wait for health check
sleep 30

# Verify deployment
curl -f http://localhost:8080/health

echo "Deployment completed successfully"
```

---

This deployment guide provides comprehensive instructions for deploying Solana Recover in various environments. For additional support, contact our team at deployment@solana-recover.com.