# AWS IoT Core for Amazon Sidewalk Device Bulk Management Solution

**Version 1.0.0**

A customer-deployed AWS CDK solution for efficient bulk provisioning and configuration of Amazon Sidewalk devices.

## Overview

This solution implements distributed, parallel processing entirely within your AWS account, eliminating external permission requirements while providing enhanced visibility and control over device operations. Unlike CSV-based workflows, this CDK-based approach enables:

- **Direct system integration** - Connect with Aurora databases, ERP systems, and manufacturing workflows through programmatic JSON APIs
- **Complex device configurations** - Support nested positioning settings, custom tags, and conditional logic
- **Enterprise scalability** - Process 100,000+ devices with optimized concurrency and batching
- **Real-time integration** - Trigger operations from CI/CD pipelines, manufacturing systems, or inventory platforms
- **High performance** - Concurrent processing with automatic batch optimization and S3-based result storage

### Key Capabilities

- **Intelligent Batching** - Automatically maximizes concurrency utilization while respecting timeout constraints
- **S3-Based Architecture** - Eliminates Step Functions payload limits for unlimited scalability
- **Aurora PostgreSQL 16.1** - Modern database with RDS Data API for serverless access
- **Dual Processing Flows** - Separate optimized paths for Create and Update operations
- **Comprehensive Monitoring** - CloudWatch dashboards, metrics, and detailed logging
- **Automatic Cleanup** - Intelligent cleanup of temporary files with S3 lifecycle policies

## IAM Requirements

** For detailed IAM permission requirements, see [IAM_PERMISSIONS.md](IAM_PERMISSIONS.md)**

### Quick Summary

**Deployment Permissions** (for CDK deployment):
- CloudFormation, S3, Lambda, IAM, Step Functions, RDS, EC2, Secrets Manager, CloudWatch, EventBridge
- Optional: SQS, SNS (if using notifications)

**Runtime Permissions** (automatically granted by CDK):
- IoT Wireless API, S3, RDS Data API, CloudWatch Metrics, Secrets Manager

**User Permissions**:
- **File Upload**: S3 write access to input bucket, read access to reports bucket
- **Monitoring**: CloudWatch Logs, Step Functions, CloudWatch Metrics (read-only)

**Simplified Option**: Use AWS managed policy `PowerUserAccess` for deployment (not recommended for production)

For complete IAM policies and detailed permissions, see **[IAM_PERMISSIONS.md](IAM_PERMISSIONS.md)**.

---

## Quick Start

### 1. Prerequisites

- **Node.js 20+** - [Installation guide](https://nodejs.org/)
- **AWS CLI** - [Installation guide](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
- **AWS CDK** - Will be installed automatically by deploy script
- **AWS Account** - With appropriate IAM permissions (see [IAM_PERMISSIONS.md](IAM_PERMISSIONS.md))

### 2. Configuration

Create or modify `config.json` with your preferred settings.

**Important**: The TPS (Transactions Per Second) values should match your AWS IoT Core service quotas. The solution automatically calculates optimal batch sizes and concurrency based on these values.

**For SQS Notifications:**
```json
{
  "notificationType": "SQS",
  "sqsProperties": {
    "queueName": "sidewalk-bulk-notifications",
    "visibilityTimeout": 300
  },
  "createWirelessDeviceApiTps": 10,
  "updateWirelessDeviceApiTps": 10,
  "getWirelessDeviceApiTps": 10
}
```

**For SNS Notifications:**
```json
{
  "notificationType": "SNS",
  "snsProperties": {
    "topicName": "sidewalk-bulk-notifications"
  },
  "createWirelessDeviceApiTps": 10,
  "updateWirelessDeviceApiTps": 10,
  "getWirelessDeviceApiTps": 10
}
```

**For No Notifications (S3 Reports Only):**
```json
{
  "notificationType": "NONE",
  "createWirelessDeviceApiTps": 10,
  "updateWirelessDeviceApiTps": 10,
  "getWirelessDeviceApiTps": 10
}
```

**Configuration Options:**

- `notificationType`: 
  - `"SQS"` - Creates SQS queue for notifications
  - `"SNS"` - Creates SNS topic for notifications  
  - `"NONE"` - No notifications (S3 reports only)
- `createWirelessDeviceApiTps`: Your AWS IoT Core concurrent API call limit for device creation (default: 10)
- `updateWirelessDeviceApiTps`: Your AWS IoT Core concurrent API call limit for device updates (default: 10)
- `getWirelessDeviceApiTps`: Your AWS IoT Core concurrent API call limit for device queries (default: 10)

**How TPS Configuration Works:**

The solution automatically calculates optimal processing parameters:

1. **Max Concurrency**: `min(10, max(1, TPS))` - Number of parallel Lambda executions
2. **TPS per Lambda**: `TPS ÷ Max Concurrency` - Rate limit for each Lambda
3. **Batch Size**: `TPS per Lambda × 300 seconds` - Maximum devices per batch (respects 5-min Lambda timeout)

**Example for 10 TPS:**
- Max Concurrency: 10 parallel Lambdas
- TPS per Lambda: 1 device/second
- Batch Size: 300 devices per batch
- Processing Time: ~5 minutes per batch

**Example for 100 devices with 10 TPS:**
- Creates 10 batches of 10 devices each
- All 10 batches run concurrently
- Total processing time: ~10 seconds

**Notification Configuration:**
- **SQS**: Creates SQS queue with dead letter queue for failed message handling
- **SNS**: Creates SNS topic supporting email, SMS, Lambda, and other subscriber types
- **NONE**: Only S3 reports generated, no notification resources created

**Important Notes:**
- Configuration values are loaded from `config.json` during deployment
- **To change TPS or notification settings**: Update `config.json` and redeploy using `./deploy.sh`
- Redeployment is fast (~2-3 minutes) as it only updates Lambda configurations, not infrastructure
- New TPS values take effect immediately after redeployment

### 3. Important: Device Profile ID Format

**Critical Requirement**: The `deviceProfileId` field must be a valid UUID in the format:
```
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```

**Example**: `12345678-1234-1234-1234-123456789012`

**Invalid formats** like `sidewalk_profile` or `profile-id-001` will cause validation errors.

To get valid device profile IDs:
```bash
aws iotwireless list-device-profiles --region us-east-1
```

### 4. Deploy

```bash
# Make deploy script executable (on Unix systems)
chmod +x deploy.sh

# Deploy the solution
./deploy.sh
```

The deployment creates:
- **Input S3 bucket** - For uploading device JSON files with EventBridge triggers
- **Report S3 bucket** - For batch files, detailed results, and final reports with 7-day lifecycle cleanup
- **Processing Lambda functions** - With retry logic, increased timeouts (10-15 min), memory (512MB-2GB), and concurrent S3 operations
- **Aurora Serverless v2 database** - PostgreSQL 16.1 with RDS Data API for device state management
- **Step Functions state machine** - Dual-flow orchestration (AWSIoTWirelessDeviceBulkManagementStateMachine)
- **CloudWatch dashboards** - Comprehensive monitoring with custom metrics
- **Notification services** - SQS/SNS based on configuration
- **VPC infrastructure** - Isolated network for Aurora database
- **Secrets Manager** - Secure storage for database credentials

**Lambda Memory Configuration:**
- Input Processor: 1 GB (for large JSON files and batch creation)
- API Processor: 512 MB (for device processing and result storage)
- Report/Notify: 2 GB (for loading many batch results and generating reports)
- DB Init: 256 MB (for database schema initialization)

### 5. Updating Configuration After Deployment

To change TPS limits or notification settings after initial deployment:

1. **Update `config.json`** with new values:
   ```json
   {
     "notificationType": "SQS",
     "createWirelessDeviceApiTps": 20,
     "updateWirelessDeviceApiTps": 20,
     "getWirelessDeviceApiTps": 20
   }
   ```

2. **Redeploy the stack**:
   ```bash
   ./deploy.sh
   ```

3. **Redeployment is fast** (~2-3 minutes):
   - Only updates Lambda environment variables
   - No infrastructure changes required
   - No downtime for existing resources

## Usage

### Device Provisioning

Create a JSON file with your device configurations:

**JSON Format:**
- `operation` (optional): "create" or "update" - auto-detected if not specified
- `batchName` (optional): Custom batch identifier for database tracking - uses S3 filename if not provided
- `devices` (required): Array of device configurations

```json
{
  "operation": "create",
  "batchName": "manufacturing-batch-20250917",
  "devices": [
    {
      "smsn": "SIDEWALK-DEVICE-001",
      "deviceName": "tag-001",
      "deviceProfileId": "profile-id-001",
      "uplinkDestinationName": "uplink-destination-name",
      "positioning": {
        "enabled": true,
        "positioningDestinationName": "positioning-destination-name"
      },
      "tags": [
        {
          "key": "Environment",
          "value": "Production"
        }
      ]
    }
  ]
}
```

### Device Configuration Updates

Update existing device configurations:

```json
{
  "operation": "update",
  "batchName": "update-batch-20250917",
  "devices": [
    {
      "smsn": "SIDEWALK-DEVICE-001",
      "positioning": {
        "enabled": false
      }
    },
    {
      "awsWirelessDeviceId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
      "positioning": {
        "enabled": true,
        "positioningDestinationName": "new-positioning-destination"
      }
    }
  ]
}
```

**Note:** For updates, you can reference devices by either `smsn` or `awsWirelessDeviceId`.

### Processing Workflow

1. **Upload** your JSON file to the input S3 bucket
2. **Automatic validation** occurs immediately (Input Processor Lambda)
3. **Intelligent batching** creates optimal batch sizes to maximize concurrency
4. **Batch files stored in S3** to avoid Step Functions payload limits
5. **Parallel processing** via Step Functions Map state with operation-specific concurrency
6. **Detailed results stored in S3** by each API processor Lambda
7. **Real-time monitoring** via CloudWatch dashboards and metrics
8. **Report generation** aggregates results from all batches
9. **Completion notification** sent via your configured channel (SQS/SNS)
10. **Automatic cleanup** removes temporary batch and result files
11. **Final reports** available in the reports S3 bucket

### Processing Architecture

```
S3 Upload → EventBridge → Step Functions
                              ↓
                    Input Processor Lambda
                    (Validation + Batching)
                              ↓
                    ┌─────────┴─────────┐
                    ↓                   ↓
            Create Operation      Update Operation
         (Max Concurrency: 10)  (Max Concurrency: 10)
                    ↓                   ↓
            CreateDevicesMap      UpdateDevicesMap
         (Parallel Processing)  (Parallel Processing)
                    ↓                   ↓
            API Processor         API Processor
         (Stores results in S3) (Stores results in S3)
                    ↓                   ↓
                    └─────────┬─────────┘
                              ↓
                    Report & Notify Lambda
                (Loads results from S3)
                              ↓
                    Final Reports + Cleanup
```

## Database Integration

### Aurora PostgreSQL Database

The solution includes an Aurora Serverless v2 PostgreSQL 16.1 database for persistent device tracking:

**Database Details:**
- **Name**: `iot_devices`
- **Engine**: Aurora PostgreSQL 16.1 (Serverless v2)
- **Capacity**: 0.5 - 4 ACUs (auto-scaling)
- **Access**: RDS Data API (HTTPS, no VPC required for Lambda functions)
- **Credentials**: Stored in AWS Secrets Manager
- **Features**: Automatic schema creation, triggers, indexes

**Database Schema:**
```sql
-- Devices table
CREATE TABLE devices (
    smsn VARCHAR(100) PRIMARY KEY,
    aws_wireless_device_id VARCHAR(36) UNIQUE NOT NULL,
    device_name VARCHAR(255) UNIQUE NOT NULL,
    device_profile_id VARCHAR(36) NOT NULL,
    uplink_destination_name VARCHAR(255),
    batch_id VARCHAR(100),
    created_at TIMESTAMP NOT NULL,
    updated_at TIMESTAMP NOT NULL,
    status VARCHAR(50) NOT NULL,
    status_details TEXT,
    positioning_enabled BOOLEAN DEFAULT FALSE,
    positioning_destination_name VARCHAR(255)
);

-- Batches table
CREATE TABLE batches (
    batch_id VARCHAR(100) PRIMARY KEY,
    operation VARCHAR(20) NOT NULL,
    total_devices INTEGER NOT NULL,
    processed_devices INTEGER NOT NULL,
    successful_devices INTEGER NOT NULL,
    failed_devices INTEGER NOT NULL,
    status VARCHAR(50) NOT NULL,
    s3_key VARCHAR(500),
    created_at TIMESTAMP NOT NULL,
    updated_at TIMESTAMP NOT NULL,
    completed_at TIMESTAMP
);
```

**Features:**
- **Automatic schema creation** during deployment via custom resource
- **RDS Data API** for serverless access (no VPC connection required)
- **VPC isolation** for security (database in private subnets)
- **Automatic scaling** with Aurora Serverless v2 (0.5-4 ACUs)
- **Backup and monitoring** included (1-day retention)
- **Triggers** for automatic timestamp updates
- **Indexes** on commonly queried columns (status, batch_id, created_at)

**Device Status Tracking:**
- `PENDING` - Device waiting to be processed
- `PROCESSING` - Device is being processed
- `PROVISIONED` - Device successfully created
- `UPDATED` - Device successfully updated  
- `FAILED` - Device processing failed

**Sample Queries:**
See `SAMPLE_QUERIES.md` for 50+ SQL query examples including:
- Device status queries
- Batch statistics
- Error analysis
- Performance monitoring
- Time-based analytics

## Monitoring & Reports

### CloudWatch Dashboards

The solution automatically deploys comprehensive CloudWatch dashboards for real-time monitoring:

#### Operational Dashboard
- **Step Functions Metrics**: Execution success/failure rates, execution duration
- **Lambda Performance**: Invocation counts, error rates, duration metrics
- **Validation Metrics**: Successful vs failed validations, devices validated
- **API Call Monitoring**: Success/failure rates with breakdown by error type

#### Device Status Dashboard  
- **Device Processing Results**: Created/updated device counts, processing failures
- **IoT Wireless API Calls**: Success/failure rates for CreateWirelessDevice and UpdateWirelessDevice
- **Batch Processing**: Batch completion rates, success percentages
- **Error Analysis**: Detailed breakdown by error type (ValidationException, ThrottlingException, etc.)

### Custom Metrics

All Lambda functions emit detailed CloudWatch metrics under the `IoTWireless/BulkManagement` namespace:

**Validation Metrics:**
- `ValidationSuccess` / `ValidationFailure` - Validation results
- `DevicesValidated` - Total devices processed through validation
- `ValidationErrors` - Count of validation errors per batch

**Processing Metrics:**
- `DeviceCreated` / `DeviceUpdated` - Successful device operations
- `DeviceProcessingFailure` - Failed device operations with error code dimensions
- `APICallSuccess` / `APICallFailure` - IoT Wireless API call results
- `BatchSuccessRate` - Percentage of successful devices per batch

**Operational Metrics:**
- `BatchProcessingStarted` / `BatchProcessingCompleted` - Batch lifecycle
- `ReportGenerated` / `NotificationSent` - Reporting and notification status

### Accessing Dashboards

After deployment, dashboard URLs are provided in the CDK outputs:
- **Operational Dashboard**: Monitor system health and performance
- **Device Status Dashboard**: Track device processing results and errors

### Alerting

Set up CloudWatch alarms on key metrics:
- High failure rates (`DeviceProcessingFailure` > threshold)
- API throttling (`APICallFailure` with `ThrottlingException`)
- Validation failures (`ValidationFailure` > threshold)
- Step Function failures

### CloudWatch Dashboards

The solution provides comprehensive dashboards showing:
- Success/failure rates with error type breakdown
- API call rates and throttling events
- Database performance metrics
- Device status distribution
- Batch operation history

### Report Types

**Validation Error Report** (when JSON validation fails):
```json
{
  "operation": "create",
  "result": "validation failed",
  "startedAt": "2025-09-17T09:30:00Z",
  "completedAt": "2025-09-17T09:31:00Z",
  "S3ObjectKey": "devices-batch-20250917.json",
  "summary": {
    "totalDevices": 1000,
    "validDevices": 995,
    "invalidDevices": 5
  },
  "validationErrors": [
    {
      "smsn": "SIDEWALK-DEVICE-123",
      "errorType": "MissingRequiredField",
      "errorMessages": ["Required field 'deviceProfileId' is missing"]
    }
  ]
}
```

**Processing Completion Report**:
```json
{
  "operation": "create",
  "result": "completed with partial success",
  "startedAt": "2025-09-17T09:30:00Z",
  "completedAt": "2025-09-17T09:38:05Z",
  "fileName": "manufacturing-batch-20250917.json",
  "batchName": "manufacturing-batch-20250917",
  "summary": {
    "totalDevices": 1000,
    "successfulDevices": 990,
    "failedDevices": 10,
    "processingTimeSeconds": 485
  },
  "successfulDevices": [
    {
      "smsn": "SIDEWALK-DEVICE-001",
      "awsWirelessDeviceId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
  ],
  "failedDevices": [
    {
      "smsn": "SIDEWALK-DEVICE-991",
      "errorCode": "ResourceNotFoundException",
      "errorMessage": "Device profile 'invalid-profile-id' not found",
      "retryable": false
    }
  ]
}
```

## Architecture

### Components

1. **Input Processing** - S3 event-triggered Lambda (10-min timeout) for JSON validation and intelligent batching
2. **Batch Storage** - S3-based storage for batch data to avoid Step Functions payload limits
3. **Job Distribution** - Step Functions (AWSIoTWirelessDeviceBulkManagementStateMachine) with dual processing flows
4. **Database** - Aurora PostgreSQL 16.1 Serverless v2 for device state management
5. **API Processing** - Lambda functions (15-min timeout) with retry logic and S3 result storage
6. **Result Aggregation** - Report/Notify Lambda (10-min timeout) with concurrent S3 loading
7. **Monitoring & Notification** - CloudWatch dashboards, custom metrics, and SQS/SNS notifications

### Scalability Features

**100K+ Device Support:**
- **S3-Based Architecture**: Batch data and results stored in S3, not in Step Functions payload
- **Increased Timeouts**: 10-15 minute Lambda timeouts for large-scale processing
- **Intelligent Batching**: Maximizes concurrency utilization automatically
- **Wave Processing**: Large jobs processed in multiple waves

**Example: 10,000 Devices with 10 TPS:**
- Batch Size: 300 devices (5-min timeout safety)
- Number of Batches: 34 batches
- Max Concurrency: 10 parallel Lambdas
- Processing Waves: 4 waves (10+10+10+4)
- Total Time: ~20 minutes (4 waves × 5 minutes)

**Example: 100,000 Devices with 10 TPS:**
- Batch Size: 300 devices
- Number of Batches: 334 batches
- Max Concurrency: 10 parallel Lambdas
- Processing Waves: 34 waves
- Total Time: ~170 minutes (~3 hours)

### Concurrency Management

The solution automatically calculates optimal batch sizes and concurrency based on your TPS configuration:

- **Concurrency Optimization**: Creates batches equal to max_concurrency when possible
- **Timeout Safety**: Batch size limited by Lambda 5-minute execution window
- **Adaptive Processing**: Exponential backoff with jitter for retries
- **Operation-Specific**: Separate concurrency limits for Create and Update operations

**Batch Size Calculation:**
```
Max Safe Batch Size = TPS per Lambda × 300 seconds
Optimal Batch Size = min(Total Devices ÷ Max Concurrency, Max Safe Batch Size)
```

**Example for 100 devices with 10 TPS:**
- Max Concurrency: 10
- TPS per Lambda: 1
- Max Safe Batch Size: 300 devices
- Optimal Batch Size: 100 ÷ 10 = 10 devices per batch
- Result: 10 batches running concurrently
- Processing Time: ~10 seconds

## Error Handling

### Retry Strategy

- **Exponential backoff** with jitter (100ms to 60s)
- **Maximum 3 retry attempts** per device
- **Error classification** (transient vs. permanent)
- **Individual device failures** don't stop batch processing

### Error Types

**Retryable Errors:**
- `ThrottlingException`
- `ServiceUnavailableException`
- `InternalServerErrorException`
- Network/connection errors

**Non-Retryable Errors:**
- `ValidationException`
- `ResourceNotFoundException`
- `ConflictException`
- `AccessDeniedException`

## Troubleshooting

### Common Issues

**Validation Errors:**
- Check JSON format and required fields
- Verify device profile and destination names exist
- Ensure SMSN format is correct

**API Throttling:**
- Reduce TPS configuration in `config.json`
- Check AWS IoT Core service quotas
- Monitor CloudWatch metrics for throttling events

### Verifying TPS Configuration

To ensure Lambda functions are receiving the correct TPS values:

1. **Check CloudWatch Logs** for the API processor Lambda:
   ```
   TPS Environment Variables:
     CREATE_DEVICE_TPS: 10
     UPDATE_DEVICE_TPS: 10
     GET_DEVICE_TPS: 10
   ```

2. **Look for TPS validation messages**:
   ```
   Create operation - Expected TPS per lambda: 2, Actual: 2
   Update operation - Expected TPS per lambda: 2, Actual: 2
   ```

3. **Monitor TPS validation metrics** in CloudWatch:
   - Metric: `IoTWireless/BulkManagement/TPSValidation`
   - Dimensions: `Operation`, `ExpectedTPS`

4. **Verify operation-specific behavior**:
   - **Create operations**: Use `createDeviceApiTps` directly
   - **Update operations**: Use `min(updateDeviceApiTps, getDeviceApiTps)`

**TPS Calculation Formula:**
- `TPS per Lambda = Total TPS ÷ Max Concurrency`
- Create: `CREATE_TPS_PER_LAMBDA = createDeviceApiTps ÷ CREATE_MAX_CONCURRENCY`
- Update: `UPDATE_TPS_PER_LAMBDA = min(updateDeviceApiTps, getDeviceApiTps) ÷ UPDATE_MAX_CONCURRENCY`

### Logs and Monitoring

- **CloudWatch Logs**: Detailed execution logs for all Lambda functions
- **Step Functions**: Visual workflow execution history
- **CloudWatch Metrics**: Custom metrics for success rates and processing times
- **Database Logs**: Aurora query logs for troubleshooting

## Performance & Scalability

### Performance Metrics

**10,000 Devices:**
- Processing Time: ~20 minutes
- Concurrent Lambdas: 10
- Batches: 34
- Waves: 4

**100,000 Devices:**
- Processing Time: ~3 hours
- Concurrent Lambdas: 10
- Batches: 334
- Waves: 34

**Scalability Limits:**
- **Step Functions**: 4-hour execution limit (supports up to ~240K devices at 10 TPS)
- **Lambda**: 15-minute timeout (300 devices per batch at 1 TPS)
- **S3**: Unlimited storage for batch files and results
- **Aurora**: Auto-scales from 0.5 to 4 ACUs based on load

### Optimization Features

- **Concurrent S3 Operations**: Parallel uploads/downloads for faster processing
- **Intelligent Batching**: Maximizes parallelism while respecting constraints
- **S3-Based Results**: Eliminates Step Functions payload limits
- **Automatic Cleanup**: S3 lifecycle rules (7-day retention) + Lambda cleanup
- **Database Indexing**: Optimized queries with indexes on key columns

## Cost Optimization

### Recommendations

1. **Right-size TPS limits** based on actual processing needs
2. **Use Aurora Serverless v2** for automatic scaling (scales to zero when idle)
3. **S3 lifecycle policies** automatically clean up temporary files (7-day retention)
4. **CloudWatch log retention** set to 2 weeks to control costs
5. **Monitor usage** via CloudWatch dashboards and adjust as needed

### Estimated Costs

**For 10,000 devices processed monthly:**
- **Lambda**: ~$5-10 (execution time and requests)
- **Step Functions**: ~$2-5 (state transitions)
- **Aurora Serverless v2**: ~$20-50 (based on usage, scales down when idle)
- **S3**: ~$1-3 (storage and requests)
- **CloudWatch**: ~$5-15 (logs and metrics)
- **Total**: ~$35-85/month

**For 100,000 devices processed monthly:**
- **Lambda**: ~$30-50 (longer execution times)
- **Step Functions**: ~$15-25 (more state transitions)
- **Aurora Serverless v2**: ~$50-100 (higher load)
- **S3**: ~$5-10 (more storage and requests)
- **CloudWatch**: ~$15-30 (more logs and metrics)
- **Total**: ~$115-215/month

**Cost Optimization Tips:**
- Process devices in larger batches less frequently
- Use NONE notification type if notifications aren't needed
- Adjust CloudWatch log retention based on requirements
- Monitor Aurora scaling and adjust min/max ACUs if needed

## Security

### Best Practices Implemented

- **IAM least privilege** - Functions have minimal required permissions
- **VPC isolation** - Database and Lambda functions in private subnets
- **Encryption at rest** - S3 buckets and Aurora cluster encrypted
- **Secrets management** - Database credentials in AWS Secrets Manager
- **Network security** - Security groups restrict database access

### Additional Recommendations

- **Enable CloudTrail** for API call auditing
- **Use AWS Config** for compliance monitoring
- **Implement resource tagging** for cost allocation
- **Regular security reviews** of IAM policies

## Support

For issues or questions:

1. **Check CloudWatch Logs** for detailed error information
2. **Review Step Functions execution history** for workflow issues
3. **Monitor CloudWatch dashboards** for system health
4. **Examine database logs** for data-related issues

## Cleanup

To remove the solution and all resources:

```bash
cdk destroy
```

**Warning:** This will delete all data including device records and reports. Ensure you have backups if needed.

---

## Sample Files

This package includes sample JSON files:
- `sample-create-devices.json` - Device provisioning example
- `sample-update-devices.json` - Device configuration update example

Use these as templates for your own device operations.