Salta al contenuto principale

Agentic platforms self-hosted: cost analysis

TCO analysis: self-hosted Ollama on Hetzner VPS (€228/year) vs cloud APIs. Break-even within 2-3 months at >30K requests/month.

Cosa ne pensi di questo articolo?

Agentic platforms self-hosted: cost analysis
Agentic PlatformsFoto:Pavel DanilyukPexels

In Breve

TCO analysis: self-hosted Ollama on Hetzner VPS (€228/year) vs cloud APIs. Break-even within 2-3 months at >30K requests/month.

Cost Analysis: Self-Hosted vs. Cloud Agentic Platforms

Una piattaforma agentic self-hosted con Ollama su VPS Hetzner CCX13 (€19/mese) costa circa €228 annui per l'infrastruttura base, più €0 per il modello LLM (open-source). Una soluzione cloud equivalente (API cloud proprietarie) con 100K richieste/mese costa €1.200-2.400/anno. Il break-even è immediato: after 2-3 mesi di utilizzo moderato, il self-hosted diventa più economico. Per aziende con >50K richieste/mese o latency-critical workflows, il ROI è garantito entro il primo anno.

Questo articolo analizza il costo totale di proprietà (TCO) di una piattaforma agentic self-hosted: infrastruttura hardware, licensing software, operazioni e manutenzione. Copriamo setup Docker Compose, configurazione Ollama con quantizzazione, monitoring con Prometheus, e un cost calculator interattivo per il tuo scenario specifico.

Cosa Imparerai in Questo Articolo

  • TCO self-hosted vs. cloud: numeri reali e comparazione ROI
  • Infrastruttura minima: VPS vs. on-premise vs. Kubernetes
  • Setup Ollama con quantizzazione per ottimizzare costi e latency
  • Monitoraggio e osservabilità: Prometheus + Grafana cost tracking
  • Scaling strategy: quando raddoppiare la capacità o migrare a cloud
  • Best practices per minimizzare costi operativi
  • FAQ e decision matrix: quale architettura per il tuo caso d'uso

Che Cosa Sono le Agentic Platforms

Una piattaforma agentic è un framework che permette di costruire agenti AI autonomi che possono:

  • Decomporre task complessi in sub-task
  • Richiamare tool e API esterne (RAG, database, CRUD)
  • Ragionare iterativamente e auto-correggersi
  • Coordinarsi con altri agenti in workflow multi-agente

Esempi mainstream: LangChain, LangGraph, CrewAI, AutoGen. Tutte supportano sia LLM cloud proprietari che self-hosted (Ollama, vLLM, Hugging Face TGI).

Self-Hosted vs. Cloud: Modelli Economici

Confrontiamo tre scenari di costo annuo per 100K richieste/mese (1.2M/anno):

Scenario Annuo: 100K richieste/mese

Componente Self-Hosted (Ollama) Cloud proprietario A Cloud proprietario B
VPS/Infrastructure €228 (CCX13) €0 €0
API Calls (1.2M/anno) €0 €1.200-1.800 €960-1.440
Ops & Maintenance €150-300 €0 €0
Backup & Storage €50 €0 €0
Total Annual €428-528 €1.200-1.800 €960-1.440
Cost per 1K calls €0.36-0.44 €1.00-1.50 €0.80-1.20

Quando Self-Hosted Vince: Break-Even Analysis

Il costo iniziale di setup self-hosted è ~€200 (prima fattura VPS + tempo setup 4-8 ore). Cloud è operativo in 10 minuti senza setup. Ma dopo:

  • 2-3 mesi: self-hosted break-even con 30-50K richieste/mese
  • 6 mesi: ROI positivo di €300-400
  • 1 anno: risparmi cumulati €700-1.200

Con >150K richieste/mese, il self-hosted è 60-70% più economico a regime.

Infrastruttura Minima: Opzioni e Costi

Opzione 1: VPS Hetzner CCX13 (Consigliato per startup)

  • Specs: 2 vCPU AMD EPYC, 4GB RAM, 40GB SSD, 20Gbps uplink
  • Prezzo: €19/mese (€228/anno)
  • Capacity: ~10-20K richieste/giorno con Ollama `llama3.1:8b-q4` (quantizzato)
  • TLS/DNS/Email: Let's Encrypt gratuito, Cloudflare DNS gratuito
  • Bottleneck: RAM (4GB) limite principale; spill to SSD dopo saturazione
  • Pro: setup semplice, billing trasparente, data center stabile EU
  • Contro: scaling verticale limitato (max CCX43 €380/mese)

Opzione 2: VPS Hetzner CCX23 (Scaling intermedio)

  • Specs: 4 vCPU, 16GB RAM, 160GB SSD
  • Prezzo: €68/mese (€816/anno)
  • Capacity: ~50-100K richieste/giorno con 2-3 istanze Ollama parallele
  • Multi-model: ospitare simultaneamente `llama3.1:8b` + `mistral:7b` + embedding model
  • Break-even con CCX13: convenibile a >20K richieste/giorno

Opzione 3: On-Premise (HW proprio, laboratorio)

  • Specs: NVIDIA RTX 4090 (€1.800) + CPU Ryzen 9 (€600) + motherboard/RAM/storage (~€1.500)
  • Total capex: €3.900
  • Electricity: ~1.2 kW/h, €220/anno (EU avg €0.19/kWh)
  • Capacity: 2-5x più veloce che VPS equivalente (GPU native vs. CPU emulation)
  • Payback period: 2-3 anni con >500K richieste/mese
  • Pro: ownership completo, zero latency di rete
  • Contro: maintenance burden, electricity volatilità, spazio fisico

Setup Ollama su VPS: Docker Compose

Ecco una configurazione production-ready di Ollama + Postgres + Redis su CCX13:

version: '3.8'
services:
  ollama:
    image: ollama/ollama:latest
    container_name: agentic-ollama
    ports:
      - "11434:11434"
    environment:
      - OLLAMA_MODELS=/data/models
      - CUDA_VISIBLE_DEVICES=0
    volumes:
      - ollama_data:/data
      - ollama_cache:/root/.ollama
    restart: always
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:11434/api/tags"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - agentic-network

  postgres:
    image: postgres:16-alpine
    container_name: agentic-postgres
    environment:
      POSTGRES_USER: agentic_user
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: agentic_db
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    restart: always
    networks:
      - agentic-network

  redis:
    image: redis:7-alpine
    container_name: agentic-redis
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    restart: always
    networks:
      - agentic-network

volumes:
  ollama_data:
  ollama_cache:
  postgres_data:
  redis_data:

networks:
  agentic-network:
    driver: bridge

Deployment Step-by-Step

  • SSH into VPS: ssh root@your-vps-ip
  • Install Docker: curl -fsSL https://get.docker.com | sh
  • Clone config: git clone https://repo/agentic-platform && cd agentic-platform
  • Set secrets: echo "POSTGRES_PASSWORD=secure_pwd" > .env
  • Start stack: docker-compose up -d
  • Pull model (first run ~4 GB): curl http://localhost:11434/api/pull -d '{"name":"llama3.1:8b-q4"}'
  • Verify health: curl http://localhost:11434/api/tags

Quantizzazione: Ridurre Memoria e Latency

I modelli LLM grandi (70B params) consumano 140 GB RAM. Quantizzare significa comprimere i pesi con perdita minima:

Quantizzazione: Memory Footprint vs. Quality

Formato Model Size (8B) Memory (VPS CCX13) Latency Quality Loss
FP32 (no quant) 32 GB ❌ Out of RAM Slow None
INT8 (8-bit) 8 GB ✅ Fits (barely) 2x faster ~1%
INT4 (4-bit Q4) 4 GB ✅ Comfortable 3-4x faster ~2-3%
INT2 (2-bit) 2 GB ✅ Very fast 5x faster ~5-10%

Raccomandazione: Su CCX13, usare llama3.1:8b-q4 (Ollama gestisce automaticamente). Su CCX23, puoi fare llama3.1:70b-q4 (8 GB).

Monitoring Costs in Real-Time: Prometheus + Grafana

Tracking consumo GPU e call rate è fondamentale per ROI monitoring:

services:
  prometheus:
    image: prom/prometheus:latest
    container_name: agentic-prometheus
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheus_data:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
    networks:
      - agentic-network

  grafana:
    image: grafana/grafana:latest
    container_name: agentic-grafana
    ports:
      - "3000:3000"
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
    volumes:
      - grafana_data:/var/lib/grafana
      - ./grafana/dashboards:/etc/grafana/provisioning/dashboards
      - ./grafana/datasources:/etc/grafana/provisioning/datasources
    networks:
      - agentic-network

Prometheus Config per Ollama

global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: ollama
    static_configs:
      - targets: ['localhost:11434']
    metrics_path: /metrics

  - job_name: docker
    static_configs:
      - targets: ['localhost:9323']

  - job_name: node_exporter
    static_configs:
      - targets: ['localhost:9100']

Key metrics da tracciare: ollama_request_duration_ms, ollama_memory_allocated_bytes, ollama_tokens_per_second, container_memory_usage_bytes per stimare margini di upgrade.

Cost Calculator: Stima il Tuo Scenario

Usa questa formula per calcolare il TCO annuo self-hosted:

def estimate_tco_self_hosted(
    monthly_requests: int,
    hours_ops_per_month: float = 5,
    vps_tier: str = 'CCX13'  # 'CCX13' | 'CCX23' | 'CCX43'
) -> dict:
    # VPS costs
    vps_monthly = {
        'CCX13': 19,
        'CCX23': 68,
        'CCX43': 380
    }[vps_tier]

    # Ops (sysadmin maintenance, monitoring alerts, patching)
    ops_hourly_rate = 50  # €/hour (junior DevOps avg in EU)
    ops_annual = hours_ops_per_month * 12 * ops_hourly_rate

    # Backups & storage (Hetzner Storage Box)
    backup_monthly = 3.20 if monthly_requests > 50_000 else 0

    # CDN for artifact caching (optional, Cloudflare free tier covers most)
    cdn_monthly = 0

    total_annual = (vps_monthly + backup_monthly + cdn_monthly) * 12 + ops_annual
    cost_per_1k_calls = (total_annual / (monthly_requests * 12 / 1000)) if monthly_requests > 0 else 0

    return {
        'vps_annual': vps_monthly * 12,
        'ops_annual': ops_annual,
        'backup_annual': backup_monthly * 12,
        'cdn_annual': cdn_monthly * 12,
        'total_annual': total_annual,
        'cost_per_1k_calls': cost_per_1k_calls,
        'breakeven_months_vs_cloud': (total_annual / (monthly_requests * 12)) / 0.01 if monthly_requests > 0 else float('inf'),
        'recommendation': 'SELF_HOSTED' if cost_per_1k_calls < 0.80 else 'HYBRID'
    }

# Example: 100K requests/month
result = estimate_tco_self_hosted(monthly_requests=100_000, hours_ops_per_month=5, vps_tier='CCX13')
print(f"Annual TCO: €{result['total_annual']:.0f}")
print(f"Cost per 1K calls: €{result['cost_per_1k_calls']:.2f}")
print(f"vs cloud: {((1.00 - result['cost_per_1k_calls']) / 1.00 * 100):.0f}% savings")

Scaling Strategy: Quando Upgrade?

Monitora questi KPI per decidere se scalare:

  • Memory utilization >80%: Upgrade a CCX23 o aggiungere istanza Ollama con load balancer
  • Request queue >100ms: Indica saturazione CPU; quantizzare più aggressivamente o scale
  • Latency P99 >2s: Timeout per applicazioni real-time; richiede dedicata GPU o upgrade
  • Monthly bill breakeven vs. cloud: Se self-hosted è ancora 40%+ più economico, mantieni; altrimenti ibrido

Hybrid Model: Best of Both Worlds

Molti team usano un modello ibrido:

  • Self-hosted Ollama: Task alto-volume, bassa latency (chat, summarization) — €428/anno
  • Cloud API: Task complessi che richiedono reasoning profondo (Claude 3.5 Sonnet) — €200/anno (10K calls/month)
  • Total hybrid: €628/anno, vs. €1.200 cloud-only

Risk Analysis: Cosa Può Andare Male

  • Ollama crash → Implementa health-check e auto-restart (vedi docker-compose)
  • GPU memory leak → Monitora con Prometheus; restart settimanale se needed
  • Disk full → Model caching può esplodere; setup quotidiano cleanup con cron
  • DDoS su VPS → Abilita Cloudflare rate limiting; whitelisting clienti trusted
  • Network partitioning → Failover a backup API cloud con circuit breaker
#!/bin/bash
# Health check + auto-restart Ollama

while true; do
  health=$(curl -s http://localhost:11434/api/tags)
  if [ $? -ne 0 ]; then
    echo "$(date): Ollama unhealthy, restarting..."
    docker restart agentic-ollama
    sleep 10
  fi

  # Memory check
  mem=$(docker stats agentic-ollama --no-stream --format "{{.MemUsage}}" | grep -oE "[0-9]+")
  if [ "$mem" -gt 3500 ]; then  # >3.5GB on CCX13
    echo "$(date): Memory >3.5GB, clearing model cache..."
    curl -X DELETE http://localhost:11434/api/chat -d '{"model":"llama3.1:8b-q4"}'
  fi

  sleep 60
done

Best Practices: Minimizzare Costi Operativi

  • Quantizzazione aggressiva: Q4 per 8B, Q3 per 70B (trade-off qualità minimo)
  • Request batching: Inviare 10-100 richieste simultaneamente →utilization +40%, latency -30%
  • Caching responses: Redis per risultati identici; TTL 24h per wiki, 1h per real-time
  • Lazy loading models: Non caricare tutti i modelli. Load-on-demand con autoscaling
  • Cost allocation per feature: Traccia quale feature usa quanto; refactor i feature costos

Roadmap 2027: Evoluzione dei Costi

Previsioni per il prossimo anno:

  • Q1 2027: Modelli 4-bit standardizzati per tutti i provider; costi CPU dimezzati
  • Q2 2027: Inference acceleration (AMD MI300, NVIDIA RTX 6000 Ada) diventa mainstream; VPS GPU-accelerated costa 50% meno
  • Q3 2027: Distilled models (1-3B params) con 95%+ quality di 8B; perfetti per edge/VPS
  • Q4 2027: Cloud pricing converge verso self-hosted? AWS/cloud pressione competitiva

FAQ: Domande Frequenti

D: Self-hosted vs. Cloud — quale scegliere?

Self-hosted se:

  • Prevedi >30K richieste/mese
  • Hai team DevOps o disponi 5-10h/mese ops
  • Requisiti latency <500ms o data residency (privacy/compliance)

Cloud se:

  • Startup fase iniziale, budget ristretto in capex
  • Demand volatile (spike mensili)
  • Richiedi reasoning profondo (Claude 3.5 Sonnet non disponibile self-hosted ancora)

D: Quale modello scegliere per Ollama?

Llama 3.1 8B: Il miglior trade-off; riesce Q4 con 4GB RAM, qualità pari a un modello cloud mid-tier per task standard.

Mistral 7B: Più veloce di Llama 3.1, qualità leggermente inferiore. Scegliere se latency <200ms è critica.

Llama 3.1 70B: Qualità "reasoning" buona, richiede 16GB RAM. Upgrade a CCX23 (€816/anno) per convenienza.

D: Come gestiamo failover e disaster recovery?

Setup minimo:

  • Database backup: pg_dump giornaliero (3 backup rolling, S3/Backblaze €5/mese)
  • Model cache: Non critica (ri-scaricabili in 5 min da Ollama registry)
  • API fallback: Circuit breaker a cloud API proprietaria se self-hosted down >60s
  • RTO (Recovery Time Objective): 15 minuti con failover manuale; 2 minuti con scripting automatico

D: Posso containerizzare tutto con Kubernetes invece di Docker Compose?

Sì, ma sopra 10 istanze Ollama parallele solo. Per single VPS, Docker Compose è sufficiente e meno overhead. Se usi K8s, il costo infra sale di 20-30% (controller management), ma scaling diventa automatico.

D: Cosa fare se Ollama non riesce a stare nei 4GB di CCX13?

Opzioni in ordine di convenienza:

  • Usare quantizzazione più aggressiva: Q2 invece di Q4 (perdita qualità ~5%)
  • Distilled models: Phi-2 (2.7B) o TinyLlama (1.1B) con qualità 85% di 8B
  • Upgrade VPS: CCX23 (+€49/mese, ancora convenibile con >20K richieste/mese)
  • Sharding: Due istanze Ollama leggere separate, load balancer tra loro

Prova Questi Strumenti

Strumenti gratuiti correlati a questo argomento.

Commenti

Caricamento commenti...

Accedi per commentare

Discuti questo articolo nella community

Unisciti al gruppo Telegram per discutere con altri sviluppatori, fare domande e condividere le tue esperienze.

Ti è piaciuto questo articolo?

Esplora altri contenuti sul blog o scopri i miei progetti