Understanding Spot vs On-Demand

What We're Building

A decision engine that automatically chooses between spot and on-demand rentals based on job characteristics, plus a spot manager that handles preemption gracefully.

Prerequisites

Spot vs On-Demand: Quick Comparison

Feature
On-Demand
Spot

Price

Fixed hourly rate

Bid-based (usually 30-70% cheaper)

Availability

Guaranteed once rented

Can be outbid/preempted

Platform Fee

10%

2.5%

Best For

Production, long-running jobs

Batch processing, fault-tolerant workloads

Risk

None

Preemption possible

Step 1: Analyzing the Spot Market

# spot_analyzer.py
"""Analyze spot market to find optimal bidding strategies."""

import requests
from typing import Dict, List, Optional
from dataclasses import dataclass
from datetime import datetime
import statistics

@dataclass
class SpotAnalysis:
    """Spot market analysis for a server."""
    server_id: int
    gpu_type: str
    on_demand_price_usd: float
    min_spot_price_usd: float
    current_winning_bid_usd: Optional[float]
    recommended_bid_usd: float
    savings_percent: float
    competition_level: str  # low, medium, high

class SpotAnalyzer:
    """Analyze spot market opportunities."""
    
    BASE_URL = "https://api.clore.ai"
    
    def __init__(self, api_key: str):
        self.headers = {"auth": api_key}
    
    def _request(self, endpoint: str, **kwargs) -> dict:
        response = requests.get(f"{self.BASE_URL}{endpoint}", 
                               headers=self.headers, **kwargs)
        return response.json()
    
    def analyze_server(self, server_id: int) -> SpotAnalysis:
        """Analyze spot market for a specific server."""
        
        # Get marketplace data
        marketplace = self._request("/v1/marketplace")
        server = next((s for s in marketplace["servers"] if s["id"] == server_id), None)
        
        if not server:
            raise ValueError(f"Server {server_id} not found")
        
        # Get spot market data
        spot_data = self._request("/v1/spot_marketplace", params={"market": server_id})
        
        # Extract prices
        on_demand = server["price"]["usd"].get("on_demand_clore", 0)
        min_spot = server["price"]["usd"].get("spot", 0)
        
        # Get current bids
        offers = spot_data.get("market", {}).get("offers", [])
        active_bids = [o for o in offers if o.get("active")]
        
        # Find winning bid (if any)
        winning_bid = None
        if active_bids:
            # Convert to USD
            rates = spot_data.get("market", {}).get("currency_rates_in_usd", {})
            winning_bid = max(o["bid"] * rates.get(o["currency"], 1) for o in active_bids)
        
        # Calculate recommended bid
        if winning_bid:
            # Bid 10% above current winner
            recommended = winning_bid * 1.10
        else:
            # Start at minimum + 20%
            recommended = min_spot * 1.20
        
        # Ensure recommended is reasonable
        recommended = max(recommended, min_spot)
        recommended = min(recommended, on_demand * 0.8)  # Don't bid more than 80% of on-demand
        
        # Calculate savings
        savings = ((on_demand - recommended) / on_demand * 100) if on_demand else 0
        
        # Assess competition
        if len(active_bids) == 0:
            competition = "low"
        elif len(active_bids) < 3:
            competition = "medium"
        else:
            competition = "high"
        
        return SpotAnalysis(
            server_id=server_id,
            gpu_type=str(server.get("gpu_array", [])),
            on_demand_price_usd=on_demand,
            min_spot_price_usd=min_spot,
            current_winning_bid_usd=winning_bid,
            recommended_bid_usd=recommended,
            savings_percent=savings,
            competition_level=competition
        )
    
    def find_best_spot_deals(self, gpu_type: str = None, 
                             max_price: float = 1.0,
                             min_savings: float = 30.0) -> List[SpotAnalysis]:
        """Find the best spot market deals."""
        
        marketplace = self._request("/v1/marketplace")
        servers = marketplace["servers"]
        
        deals = []
        for server in servers:
            if server.get("rented"):
                continue
            
            # Filter by GPU type
            if gpu_type:
                gpus = server.get("gpu_array", [])
                if not any(gpu_type in g for g in gpus):
                    continue
            
            try:
                analysis = self.analyze_server(server["id"])
                
                # Filter by price and savings
                if analysis.recommended_bid_usd <= max_price and \
                   analysis.savings_percent >= min_savings:
                    deals.append(analysis)
                    
            except Exception as e:
                continue  # Skip servers with issues
        
        # Sort by savings
        deals.sort(key=lambda x: -x.savings_percent)
        return deals
    
    def print_analysis(self, analysis: SpotAnalysis):
        """Print formatted analysis."""
        print(f"\n{'='*50}")
        print(f"πŸ“Š Server {analysis.server_id} ({analysis.gpu_type})")
        print(f"{'='*50}")
        print(f"On-Demand Price: ${analysis.on_demand_price_usd:.2f}/hr")
        print(f"Min Spot Price:  ${analysis.min_spot_price_usd:.2f}/hr")
        
        if analysis.current_winning_bid_usd:
            print(f"Current Winner:  ${analysis.current_winning_bid_usd:.2f}/hr")
        else:
            print(f"Current Winner:  No active bids")
        
        print(f"\nπŸ’‘ Recommended Bid: ${analysis.recommended_bid_usd:.2f}/hr")
        print(f"πŸ’° Potential Savings: {analysis.savings_percent:.0f}%")
        print(f"πŸ“ˆ Competition: {analysis.competition_level}")


if __name__ == "__main__":
    analyzer = SpotAnalyzer("YOUR_API_KEY")
    
    # Find best RTX 4090 spot deals
    print("πŸ” Finding best RTX 4090 spot deals...")
    deals = analyzer.find_best_spot_deals(
        gpu_type="RTX 4090",
        max_price=0.40,
        min_savings=40.0
    )
    
    print(f"\nFound {len(deals)} great deals!")
    for deal in deals[:5]:
        analyzer.print_analysis(deal)

Step 2: Smart Rental Decision Engine

Step 3: Spot Manager with Preemption Handling

Decision Flowchart

Cost Comparison Example

Next Steps

Last updated

Was this helpful?