> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tensorone.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Stop Cluster

> Stop running GPU clusters gracefully or forcefully with data preservation options

## Overview

The Stop Cluster endpoint allows you to stop running GPU clusters either gracefully (allowing running processes to complete) or forcefully (immediate termination). This is essential for cost management, maintenance, and resource optimization.

## Endpoint

```bash curl
POST https://api.tensorone.ai/v1/clusters/{cluster_id}/stop
```

## Path Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `cluster_id` | string | Yes | Unique cluster identifier |

## Request Body

| Parameter | Type | Required | Description |
| - | - | - | - |
| `force` | boolean | No | Force immediate stop without graceful shutdown (default: false) |
| `grace_period_minutes` | integer | No | Grace period for graceful shutdown (default: 5, max: 30) |
| `save_state` | boolean | No | Create snapshot before stopping (default: false) |
| `snapshot_name` | string | No | Custom name for the snapshot |
| `preserve_data` | boolean | No | Preserve data volumes (default: true) |
| `wait_for_completion` | boolean | No | Wait for stop operation to complete (default: false) |
| `timeout_minutes` | integer | No | Maximum wait time for completion (default: 10, max: 60) |
| `stop_reason` | string | No | Reason for stopping (for audit logs) |
| `notify_users` | array | No | User IDs to notify about the stop operation |

## Request Examples

```bash curl
# Basic graceful stop
curl -X POST "https://api.tensorone.ai/v1/clusters/cluster_abc123/stop" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "grace_period_minutes": 10,
    "stop_reason": "Scheduled maintenance"
  }'

# Force stop with snapshot
curl -X POST "https://api.tensorone.ai/v1/clusters/cluster_abc123/stop" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "force": true,
    "save_state": true,
    "snapshot_name": "emergency_stop_2024_01_15",
    "wait_for_completion": true,
    "stop_reason": "Emergency maintenance"
  }'

# Graceful stop with user notification
curl -X POST "https://api.tensorone.ai/v1/clusters/cluster_abc123/stop" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "grace_period_minutes": 15,
    "save_state": true,
    "preserve_data": true,
    "notify_users": ["user_123", "user_456"],
    "stop_reason": "Cost optimization - end of business day"
  }'
```

```python Python
import requests
import time

def stop_cluster_graceful(cluster_id, grace_minutes=5, reason=None):
    """Stop cluster gracefully with optional reason"""
    
    payload = {
        "force": False,
        "grace_period_minutes": grace_minutes,
        "save_state": False,
        "preserve_data": True,
        "wait_for_completion": True,
        "timeout_minutes": 15
    }
    
    if reason:
        payload["stop_reason"] = reason
    
    response = requests.post(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/stop",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=payload
    )
    
    result = response.json()
    
    if result["success"]:
        print(f"Cluster {cluster_id} stopped successfully")
        if "data" in result and "cost_saved" in result["data"]:
            print(f"Estimated cost savings: ${result['data']['cost_saved']['hourly_rate']:.2f}/hour")
    
    return result

def emergency_stop_with_backup(cluster_id, snapshot_name=None):
    """Emergency stop with automatic snapshot creation"""
    
    if not snapshot_name:
        from datetime import datetime
        snapshot_name = f"emergency_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    
    payload = {
        "force": True,
        "save_state": True,
        "snapshot_name": snapshot_name,
        "preserve_data": True,
        "wait_for_completion": True,
        "timeout_minutes": 30,
        "stop_reason": "Emergency stop with backup"
    }
    
    response = requests.post(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/stop",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=payload
    )
    
    result = response.json()
    
    if result["success"]:
        print(f"Emergency stop completed for cluster {cluster_id}")
        if "snapshot_id" in result["data"]:
            print(f"Backup snapshot created: {result['data']['snapshot_id']}")
    
    return result

def stop_training_cluster_safely(cluster_id, checkpoint_interval_minutes=30):
    """Stop training cluster after ensuring checkpoints are saved"""
    
    # First, check if training is running and when last checkpoint was saved
    cluster_info = requests.get(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}",
        headers={"Authorization": "Bearer YOUR_API_KEY"}
    ).json()
    
    if not cluster_info["success"]:
        return cluster_info
    
    # Calculate appropriate grace period based on checkpoint interval
    grace_period = max(checkpoint_interval_minutes + 5, 10)  # At least 10 minutes
    
    payload = {
        "force": False,
        "grace_period_minutes": grace_period,
        "save_state": True,
        "snapshot_name": f"training_checkpoint_{int(time.time())}",
        "preserve_data": True,
        "stop_reason": "Training session completed",
        "wait_for_completion": True
    }
    
    response = requests.post(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/stop",
        headers={
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "application/json"
        },
        json=payload
    )
    
    return response.json()
```

```javascript JavaScript
// Graceful cluster stop with monitoring
async function stopClusterGracefully(clusterId, options = {}) {
  const stopConfig = {
    force: false,
    grace_period_minutes: options.gracePeriod || 10,
    save_state: options.createSnapshot || false,
    preserve_data: options.preserveData !== false, // default true
    wait_for_completion: options.waitForCompletion || false,
    stop_reason: options.reason || 'Manual stop request'
  };
  
  if (options.snapshotName) {
    stopConfig.snapshot_name = options.snapshotName;
  }
  
  if (options.notifyUsers) {
    stopConfig.notify_users = options.notifyUsers;
  }
  
  const response = await fetch(`https://api.tensorone.ai/v1/clusters/${clusterId}/stop`, {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(stopConfig)
  });
  
  const result = await response.json();
  
  if (result.success) {
    console.log(`Cluster ${clusterId} stop initiated`);
    
    if (stopConfig.wait_for_completion) {
      console.log('Cluster stopped successfully');
      return result.data;
    } else {
      // Poll for completion if not waiting
      return await pollStopCompletion(clusterId);
    }
  }
  
  throw new Error(`Failed to stop cluster: ${result.error.message}`);
}

// Stop multiple clusters with different strategies
async function stopMultipleClusters(clusterConfigs) {
  const stopPromises = clusterConfigs.map(async (config) => {
    try {
      const result = await stopClusterGracefully(config.clusterId, {
        gracePeriod: config.gracePeriod || 5,
        createSnapshot: config.createSnapshot || false,
        reason: config.reason || 'Batch stop operation',
        waitForCompletion: false
      });
      
      return {
        clusterId: config.clusterId,
        success: true,
        data: result
      };
    } catch (error) {
      return {
        clusterId: config.clusterId,
        success: false,
        error: error.message
      };
    }
  });
  
  const results = await Promise.allSettled(stopPromises);
  
  return results.map(result => result.value);
}

// Emergency stop with comprehensive backup
async function emergencyStopWithBackup(clusterId, reason = 'Emergency stop') {
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  
  const stopConfig = {
    force: true,
    save_state: true,
    snapshot_name: `emergency_${clusterId}_${timestamp}`,
    preserve_data: true,
    wait_for_completion: true,
    timeout_minutes: 30,
    stop_reason: reason
  };
  
  try {
    const response = await fetch(`https://api.tensorone.ai/v1/clusters/${clusterId}/stop`, {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(stopConfig)
    });
    
    const result = await response.json();
    
    if (!result.success) {
      throw new Error(result.error.message);
    }
    
    return {
      clusterId: clusterId,
      stopped: true,
      snapshotId: result.data.snapshot_id,
      costSaved: result.data.cost_saved,
      stopTime: result.data.stopped_at
    };
  } catch (error) {
    console.error(`Emergency stop failed for cluster ${clusterId}:`, error);
    throw error;
  }
}

// Utility function to poll stop completion
async function pollStopCompletion(clusterId, maxAttempts = 30) {
  let attempts = 0;
  
  while (attempts < maxAttempts) {
    try {
      const response = await fetch(`https://api.tensorone.ai/v1/clusters/${clusterId}`, {
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        }
      });
      
      const cluster = await response.json();
      
      if (cluster.success) {
        const status = cluster.data.status;
        
        if (status === 'stopped') {
          console.log(`Cluster ${clusterId} is now stopped`);
          return cluster.data;
        } else if (status === 'error') {
          throw new Error(`Cluster ${clusterId} entered error state during stop`);
        }
        
        console.log(`Cluster ${clusterId} status: ${status}, waiting...`);
      }
      
      await new Promise(resolve => setTimeout(resolve, 10000)); // Wait 10 seconds
      attempts++;
    } catch (error) {
      console.error(`Error polling cluster ${clusterId}:`, error);
      attempts++;
    }
  }
  
  throw new Error(`Timeout waiting for cluster ${clusterId} to stop`);
}
```

## Response Schema

```json Success Response (Immediate)
{
  "success": true,
  "data": {
    "id": "cluster_abc123",
    "name": "ml-training-cluster",
    "status": "stopping",
    "stop_initiated_at": "2024-01-15T16:30:00Z",
    "estimated_stop_time": "2024-01-15T16:40:00Z",
    "stop_type": "graceful",
    "grace_period_minutes": 10,
    "stop_progress": {
      "phase": "notifying_processes",
      "percentage": 20,
      "current_step": "Sending SIGTERM to running processes",
      "steps_completed": 2,
      "total_steps": 6
    },
    "snapshot_creation": {
      "enabled": false,
      "snapshot_id": null
    },
    "cost_impact": {
      "hourly_rate_saved": 12.50,
      "session_cost_final": 45.75,
      "billing_stopped_at": "2024-01-15T16:30:00Z"
    },
    "data_preservation": {
      "volumes_preserved": ["root", "data"],
      "snapshots_created": 0
    }
  },
  "meta": {
    "request_id": "req_stop_456",
    "wait_for_completion": false
  }
}
```

```json Success Response (Wait for Completion)
{
  "success": true,
  "data": {
    "id": "cluster_abc123",
    "name": "ml-training-cluster",
    "status": "stopped",
    "stop_initiated_at": "2024-01-15T16:30:00Z",
    "stopped_at": "2024-01-15T16:38:42Z",
    "stop_duration_seconds": 522,
    "stop_type": "graceful",
    "grace_period_used_minutes": 8.7,
    "processes_terminated": {
      "graceful_shutdowns": 12,
      "forced_kills": 0,
      "total_processes": 12
    },
    "snapshot_creation": {
      "enabled": true,
      "snapshot_id": "snap_xyz789",
      "snapshot_name": "training_checkpoint_1642259922",
      "snapshot_size_gb": 156.8,
      "creation_time_seconds": 45
    },
    "cost_summary": {
      "session_duration_hours": 3.25,
      "total_session_cost": 40.63,
      "hourly_rate_saved": 12.50,
      "estimated_daily_savings": 300.00
    },
    "data_preservation": {
      "volumes_preserved": ["root", "data"],
      "total_data_size_gb": 890.4,
      "snapshots_created": 1,
      "backup_status": "completed"
    },
    "final_metrics": {
      "max_gpu_utilization": 94.3,
      "avg_gpu_utilization": 87.2,
      "peak_memory_usage_gb": 245.6,
      "total_compute_hours": 13.0
    }
  },
  "meta": {
    "request_id": "req_stop_456",
    "wait_for_completion": true,
    "total_wait_time_seconds": 522
  }
}
```

## Stop Progress Phases

When stopping clusters, the system goes through several phases:

| Phase | Description | Typical Duration |
| - | - | - |
| `notifying_processes` | Sending termination signals to running processes | 10-30 seconds |
| `waiting_for_graceful_exit` | Allowing processes to shut down cleanly | 1-15 minutes |
| `creating_snapshot` | Creating state snapshot (if requested) | 30 seconds - 5 minutes |
| `terminating_resources` | Releasing GPU and compute resources | 30-60 seconds |
| `cleaning_up` | Final cleanup and state updates | 10-30 seconds |
| `completed` | Stop operation finished | - |

## Use Cases

### Cost Optimization

Automatically stop idle clusters to save costs.

```python
def stop_idle_clusters(idle_threshold_minutes=30):
    """Stop clusters that have been idle for too long"""
    
    # Get all running clusters
    response = requests.get(
        "https://api.tensorone.ai/v1/clusters",
        headers={"Authorization": f"Bearer {API_KEY}"},
        params={"status": "running"}
    )
    
    clusters = response.json()["data"]["clusters"]
    stopped_clusters = []
    
    for cluster in clusters:
        # Check if cluster has been idle
        last_activity = cluster.get("last_accessed")
        if last_activity:
            from datetime import datetime, timedelta
            last_activity_time = datetime.fromisoformat(last_activity.replace('Z', '+00:00'))
            idle_time = datetime.now().timestamp() - last_activity_time.timestamp()
            idle_minutes = idle_time / 60
            
            if idle_minutes > idle_threshold_minutes:
                # Stop idle cluster
                result = stop_cluster_graceful(
                    cluster["id"], 
                    grace_minutes=5,
                    reason=f"Auto-stop: idle for {idle_minutes:.1f} minutes"
                )
                
                if result["success"]:
                    stopped_clusters.append({
                        "cluster_id": cluster["id"],
                        "name": cluster["name"],
                        "idle_minutes": idle_minutes,
                        "cost_saved_per_hour": cluster["cost"]["hourly_rate"]
                    })
    
    return stopped_clusters
```

### Scheduled Maintenance

Stop clusters for scheduled maintenance windows.

```javascript
async function scheduleMaintenanceStop(clusterIds, maintenanceWindow) {
  const results = [];
  
  for (const clusterId of clusterIds) {
    try {
      // Get cluster info to determine appropriate grace period
      const clusterResponse = await fetch(`https://api.tensorone.ai/v1/clusters/${clusterId}`, {
        headers: { 'Authorization': 'Bearer ' + API_KEY }
      });
      
      const cluster = await clusterResponse.json();
      
      if (!cluster.success) {
        results.push({ clusterId, success: false, error: cluster.error.message });
        continue;
      }
      
      // Determine grace period based on cluster type
      let gracePeriod = 5; // default
      if (cluster.data.name.includes('training')) {
        gracePeriod = 15; // More time for training clusters
      } else if (cluster.data.name.includes('prod')) {
        gracePeriod = 10; // Production clusters need time to drain
      }
      
      const stopResult = await stopClusterGracefully(clusterId, {
        gracePeriod: gracePeriod,
        createSnapshot: true,
        snapshotName: `maintenance_${maintenanceWindow.id}_${clusterId}`,
        reason: `Scheduled maintenance: ${maintenanceWindow.description}`,
        notifyUsers: cluster.data.project_info.team_members || []
      });
      
      results.push({
        clusterId,
        success: true,
        gracePeriod,
        snapshotId: stopResult.snapshot_id,
        estimatedDowntime: maintenanceWindow.duration_minutes
      });
      
    } catch (error) {
      results.push({
        clusterId,
        success: false,
        error: error.message
      });
    }
  }
  
  return results;
}
```

### Training Completion Handler

Stop training clusters when jobs complete with proper state preservation.

```python
def handle_training_completion(cluster_id, model_name, final_checkpoint_path):
    """Handle training completion with comprehensive state saving"""
    
    # Create final snapshot with model artifacts
    snapshot_name = f"final_model_{model_name}_{int(time.time())}"
    
    stop_config = {
        "force": False,
        "grace_period_minutes": 20,  # Allow time for final checkpoint
        "save_state": True,
        "snapshot_name": snapshot_name,
        "preserve_data": True,
        "wait_for_completion": True,
        "stop_reason": f"Training completed for model: {model_name}",
        "timeout_minutes": 30
    }
    
    # Add environment variable to signal final checkpoint save
    # This would be picked up by the training script
    update_env_response = requests.patch(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/environment",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={
            "TRAINING_COMPLETED": "true",
            "FINAL_CHECKPOINT_PATH": final_checkpoint_path,
            "MODEL_NAME": model_name
        }
    )
    
    # Wait a bit for the training script to notice and save final checkpoint
    time.sleep(60)
    
    # Now stop the cluster
    response = requests.post(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/stop",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json=stop_config
    )
    
    result = response.json()
    
    if result["success"]:
        completion_info = {
            "cluster_id": cluster_id,
            "model_name": model_name,
            "final_snapshot_id": result["data"]["snapshot_creation"]["snapshot_id"],
            "training_duration_hours": result["data"]["cost_summary"]["session_duration_hours"],
            "total_cost": result["data"]["cost_summary"]["total_session_cost"],
            "final_checkpoint_path": final_checkpoint_path,
            "stopped_at": result["data"]["stopped_at"]
        }
        
        # Log completion
        print(f"Training completed for {model_name}")
        print(f"Final snapshot: {completion_info['final_snapshot_id']}")
        print(f"Total cost: ${completion_info['total_cost']:.2f}")
        
        return completion_info
    
    return result
```

### Batch Cluster Management

Stop multiple clusters with different strategies based on their usage patterns.

```python
def intelligent_batch_stop(project_id, stop_criteria):
    """Stop clusters based on intelligent criteria"""
    
    # Get all clusters for the project
    response = requests.get(
        "https://api.tensorone.ai/v1/clusters",
        headers={"Authorization": f"Bearer {API_KEY}"},
        params={
            "project_id": project_id,
            "status": "running",
            "include_metrics": True
        }
    )
    
    clusters = response.json()["data"]["clusters"]
    stop_decisions = []
    
    for cluster in clusters:
        decision = {
            "cluster_id": cluster["id"],
            "name": cluster["name"],
            "should_stop": False,
            "reason": "",
            "stop_config": {}
        }
        
        metrics = cluster["metrics"]["current"]
        cost = cluster["cost"]["hourly_rate"]
        
        # Criteria 1: Low utilization + high cost
        if metrics["gpu_utilization"] < stop_criteria.get("min_gpu_util", 20) and cost > stop_criteria.get("max_cost_for_low_util", 5.0):
            decision["should_stop"] = True
            decision["reason"] = f"Low utilization ({metrics['gpu_utilization']}%) with high cost (${cost}/hr)"
            decision["stop_config"] = {
                "grace_period_minutes": 5,
                "save_state": False,
                "reason": "Cost optimization - low utilization"
            }
        
        # Criteria 2: Development clusters after hours
        elif "dev" in cluster["name"].lower() and stop_criteria.get("stop_dev_after_hours", False):
            decision["should_stop"] = True
            decision["reason"] = "Development cluster - after hours shutdown"
            decision["stop_config"] = {
                "grace_period_minutes": 10,
                "save_state": True,
                "reason": "Scheduled dev environment shutdown"
            }
        
        # Criteria 3: Idle clusters
        elif cluster.get("uptime_seconds", 0) > stop_criteria.get("max_idle_seconds", 3600):
            last_access = cluster.get("last_accessed")
            if last_access:
                # Calculate idle time and decide
                pass  # Implementation depends on last access format
        
        stop_decisions.append(decision)
    
    # Execute stop operations
    results = []
    for decision in stop_decisions:
        if decision["should_stop"]:
            result = stop_cluster_graceful(
                decision["cluster_id"],
                **decision["stop_config"]
            )
            results.append({
                "cluster_id": decision["cluster_id"],
                "name": decision["name"],
                "reason": decision["reason"],
                "success": result["success"],
                "response": result
            })
    
    return results
```

## Error Handling

```json Invalid State
{
  "success": false,
  "error": {
    "code": "INVALID_STATE",
    "message": "Cluster is not in a running state",
    "details": {
      "current_status": "stopped",
      "required_status": "running",
      "suggestion": "Cluster is already stopped"
    }
  }
}
```

```json Stop In Progress
{
  "success": false,
  "error": {
    "code": "OPERATION_IN_PROGRESS",
    "message": "Cluster stop operation is already in progress",
    "details": {
      "current_operation": "stopping",
      "started_at": "2024-01-15T16:25:00Z",
      "estimated_completion": "2024-01-15T16:35:00Z"
    }
  }
}
```

```json Snapshot Creation Failed
{
  "success": false,
  "error": {
    "code": "SNAPSHOT_CREATION_FAILED",
    "message": "Failed to create snapshot before stopping",
    "details": {
      "snapshot_error": "Insufficient storage space for snapshot",
      "available_space_gb": 45.2,
      "required_space_gb": 156.8,
      "suggestion": "Either free up space or stop without creating snapshot"
    }
  }
}
```

```json Processes Won't Terminate
{
  "success": false,
  "error": {
    "code": "GRACEFUL_STOP_FAILED",
    "message": "Some processes did not terminate gracefully",
    "details": {
      "grace_period_minutes": 10,
      "processes_still_running": 3,
      "suggestion": "Use force=true to terminate immediately or increase grace period"
    }
  }
}
```

## Security Considerations

* **Data Protection**: Always preserve important data before stopping clusters
* **Process Safety**: Use appropriate grace periods for critical workloads
* **Access Control**: Verify permissions before stopping shared clusters
* **Audit Logging**: Include stop reasons for compliance and troubleshooting

## Best Practices

1. **Graceful Shutdown**: Always prefer graceful stops over forced termination
2. **State Preservation**: Create snapshots for important work states
3. **Cost Monitoring**: Use stop operations for effective cost management
4. **Communication**: Notify team members before stopping shared clusters
5. **Automation**: Implement intelligent stopping based on usage patterns
6. **Data Backup**: Ensure critical data is backed up before stopping clusters


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.