Webhook e integrazioni per il monitoraggio uptime: workflow personalizzati
Collega il monitoraggio uptime ai tuoi sistemi tramite webhook. Guida completa all'automazione degli incidenti, notifiche custom e integrazione workflow.
Perché i webhook sono importanti per il monitoraggio#
Gli avvisi email ti raggiungono prima o poi. Gli avvisi Slack appaiono in un canale. Ma i webhook ti permettono di fare cose quando accadono gli incidenti.
Senza webhook:
- Scatta l'avviso → Crei manualmente un ticket Jira → Aggiorni manualmente la status page → Contatti manualmente l'ingegnere on-call
- Tempo di risposta: 5-10 minuti
Con webhook:
- Scatta l'avviso → Si attiva il webhook → Crea automaticamente un ticket Jira → Aggiorna la status page → Contatta l'ingegnere on-call
- Tempo di risposta: 10 secondi
Per infrastrutture critiche, questa differenza di 5 minuti previene l'impatto sui clienti.
Come funzionano i webhook#
Quando il tuo sito va offline e il monitoraggio lo rileva:
1. Il servizio di monitoraggio Nova Uptime rileva l'errore
2. Nova Uptime chiama il tuo URL webhook con i dati dell'incidente
3. Il tuo server riceve un POST HTTP con:
- Dominio
- Stato
- Orario di rilevamento
- Tempo di risposta
- Risultato del controllo precedente
4. Il tuo sistema decide cosa fare
- Creare un ticket Jira?
- Contattare l'on-call?
- Aggiornare la status page?
- Postare su Slack?
5. Le azioni vengono eseguite automaticamente
Configurare i webhook#
Passo 1: crea un receiver per il webhook#
Il tuo receiver del webhook è un semplice endpoint HTTP che riceve i dati dell'incidente.
Esempio: receiver webhook Express.js
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhooks/uptime-incident', async (req, res) => {
const { domain, status, detectedAt, responseTime } = req.body;
console.log(`Incident detected: ${domain} is ${status}`);
// Handle the incident
await handleIncident({
domain,
status,
detectedAt,
responseTime
});
// Respond with 200 OK to acknowledge receipt
res.json({ success: true });
});
app.listen(3000, () => {
console.log('Webhook receiver listening on port 3000');
});
Passo 2: configura il webhook in Nova Uptime#
- Accedi a go.novauptime.com
- Impostazioni dominio → Webhook
- Clicca "Add Webhook"
- Inserisci l'URL del tuo endpoint:
https://yourdomain.com/webhooks/uptime-incident - Seleziona gli eventi da attivare:
- ✅ Sito down
- ✅ Sito ripristinato
- ✅ Avviso tempo di risposta
- Salva
Passo 3: testa il webhook#
La maggior parte degli strumenti ha un pulsante "Test Webhook":
- Clicca "Test" nelle impostazioni del webhook
- Il tuo endpoint riceve dati di test
- Verifica che il tuo sistema risponda con 200 OK
Pattern di webhook nel mondo reale#
Pattern 1: creare ticket per gli incidenti#
Quando il sito va offline, crea automaticamente un ticket Jira.
async function handleIncident({ domain, status, detectedAt }) {
if (status === 'down') {
// Create Jira ticket
const ticket = await createJiraTicket({
project: 'OPS',
issueType: 'Incident',
summary: `Production Incident: ${domain} is down`,
description: `
Domain: ${domain}
Detected: ${detectedAt}
Status: DOWN
Actions:
1. Check server status
2. Review recent deployments
3. Check error logs
`,
priority: 'Critical',
labels: ['incident', 'production']
});
console.log(`Created ticket: ${ticket.key}`);
}
}
Pattern 2: aggiornare la status page#
Quando accade un incidente, aggiorna automaticamente la tua status page pubblica.
async function handleIncident({ domain, status, detectedAt }) {
if (status === 'down') {
// Create incident on status page
await createStatusPageIncident({
name: `${domain} is Down`,
status: 'investigating',
body: `We're investigating an issue with ${domain}. More info coming soon.`,
affectedComponents: [domain]
});
} else if (status === 'up') {
// Resolve incident on status page
await updateStatusPageIncident({
status: 'resolved',
body: `${domain} is now back online. We apologize for the inconvenience.`
});
}
}
Pattern 3: contattare l'ingegnere on-call#
Invia un SMS alla persona on-call immediatamente per gli incidenti critici.
async function handleIncident({ domain, status, detectedAt }) {
if (status === 'down') {
// Get current on-call engineer from PagerDuty
const oncall = await getOnCallEngineer();
// Send SMS
await sendSMS({
to: oncall.phone,
message: `CRITICAL: ${domain} is down. Incident ticket: JIRA-123`
});
// Also post to #incidents Slack channel
await postToSlack({
channel: '#incidents',
text: `@${oncall.slackHandle}: ${domain} is down. See JIRA-123`
});
}
}
Pattern 4: archiviare lo storico degli incidenti#
Logga tutti gli incidenti nel tuo database per le analisi.
async function handleIncident({ domain, status, detectedAt, responseTime }) {
// Store in database
const incident = await Incident.create({
domain,
status,
detectedAt,
responseTime,
createdAt: new Date(),
handledAt: new Date(),
ticketCreated: false,
statusPageUpdated: false
});
console.log(`Stored incident: ${incident._id}`);
// Later: calculate MTTR, uptime %, etc.
await updateIncidentMetrics(domain);
}
Pattern 5: orchestrazione multi-servizio#
Quando un servizio fallisce, attiva azioni su più piattaforme.
async function handleIncident({ domain, status, detectedAt }) {
if (status === 'down') {
// Parallel actions: Don't wait for each to finish
await Promise.all([
createJiraTicket({ domain, status }),
createStatusPageIncident({ domain }),
pageOnCallEngineer({ domain }),
postSlackAlert({ domain }),
storeIncidentHistory({ domain, detectedAt }),
triggerPostmortemWorkflow({ domain })
]);
}
}
Pattern avanzati#
Pattern 6: logica condizionale basata sulla gravità#
Azioni diverse per livelli di gravità diversi.
async function handleIncident({ domain, status, severity }) {
if (severity === 'critical') {
// Critical: Page everyone
await pageOnCall({ priority: 'high' });
await updateStatusPage({ status: 'major_outage' });
await createJiraTicket({ priority: 'Critical' });
} else if (severity === 'warning') {
// Warning: Slack + Jira, no SMS
await postSlackAlert({ channel: '#alerts' });
await createJiraTicket({ priority: 'Medium' });
} else if (severity === 'info') {
// Info: Log only, no alert
await storeIncidentHistory({ domain });
}
}
Pattern 7: deduplicazione#
Previeni ticket/avvisi duplicati se lo stesso dominio fallisce più volte.
async function handleIncident({ domain, status }) {
if (status === 'down') {
// Check if active incident already exists
const activeIncident = await Incident.findOne({
domain,
status: 'active',
createdAfter: new Date(Date.now() - 15 * 60 * 1000) // Last 15 mins
});
if (activeIncident) {
// Incident already reported, just update
activeIncident.lastSeen = new Date();
await activeIncident.save();
console.log(`Updated existing incident: ${activeIncident._id}`);
} else {
// New incident, create everything
await createJiraTicket({ domain });
await pageOnCall({ domain });
// ... etc
}
}
}
Pattern 8: ritentare i webhook falliti#
Se il tuo receiver del webhook è offline, Nova Uptime dovrebbe ritentare.
Configurazione Nova Uptime:
- Impostazioni dominio → Webhook
- Clicca sul webhook
- Impostazioni avanzate → Retry Policy
- Abilita: "Retry on failure"
- Tentativi massimi: 3
- Ritardo tra tentativi: esponenziale (5s, 10s, 20s)
Il tuo receiver del webhook dovrebbe essere idempotente (sicuro da chiamare più volte):
// Good: Idempotent
async function handleIncident({ domain, status, eventId }) {
// Check if already processed
const processed = await ProcessedEvents.findOne({ eventId });
if (processed) {
return res.json({ success: true, cached: true });
}
// Process incident
await doActualWork();
// Record as processed
await ProcessedEvents.create({ eventId, processedAt: new Date() });
res.json({ success: true });
}
Esempi di integrazione webhook#
Integrazione 1: Zapier#
Se non vuoi costruire webhook personalizzati, usa Zapier:
- Nova Uptime → Zapier → Slack/Jira/Email/ecc.
- Nessuna codifica richiesta
- Limitazioni: meno controllo, aggiunge latenza
Integrazione 2: GitHub Actions#
In caso di incidente, attiva una GitHub Action (per esempio auto-scaling, rollback):
async function handleIncident({ domain, status }) {
if (status === 'down') {
// Trigger GitHub Actions workflow
await triggerGitHubAction({
repo: 'mycompany/infrastructure',
workflow: 'incident-response.yml',
inputs: {
domain,
action: 'scale-up'
}
});
}
}
Integrazione 3: AWS Lambda#
Usa Lambda per la gestione serverless dei webhook:
# AWS Lambda function
import json
import boto3
def lambda_handler(event, context):
body = json.loads(event['body'])
domain = body['domain']
status = body['status']
if status == 'down':
# Auto-scale on AWS
ec2 = boto3.client('ec2')
ec2.start_instances(InstanceIds=['i-1234567890abcdef0'])
return {
'statusCode': 200,
'body': json.dumps({'success': True})
}
Sicurezza dei webhook#
Verifica della firma webhook#
Nova Uptime firma ogni webhook con HMAC-SHA256. Verifica prima di processare:
const crypto = require('crypto');
app.post('/webhooks/uptime-incident', (req, res) => {
const signature = req.headers['x-gum-signature'];
const body = JSON.stringify(req.body);
const secret = process.env.NOVAUPTIME_WEBHOOK_SECRET;
// Compute expected signature
const expected = crypto
.createHmac('sha256', secret)
.update(body)
.digest('hex');
if (signature !== expected) {
console.error('Invalid webhook signature');
return res.status(401).json({ error: 'Unauthorized' });
}
// Process webhook
handleIncident(req.body);
res.json({ success: true });
});
Rate limiting#
Il tuo receiver del webhook dovrebbe limitare il numero di chiamate:
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 100 // max 100 requests per minute
});
app.post('/webhooks/uptime-incident', limiter, (req, res) => {
// Handle webhook
});
Gestione del timeout#
Il receiver del webhook dovrebbe rispondere rapidamente:
app.post('/webhooks/uptime-incident', async (req, res) => {
// Respond immediately
res.json({ success: true });
// Do real work in background
setTimeout(async () => {
await handleIncident(req.body);
}, 0);
});
Testare i tuoi webhook#
Metodo di test 1: test locale con ngrok#
- Avvia il receiver del webhook locale su localhost:3000
- Esegui ngrok:
ngrok http 3000 - Ottieni l'URL pubblico:
https://abc123.ngrok.io - Configura in Nova Uptime:
https://abc123.ngrok.io/webhooks/uptime-incident - Clicca "Test" in Nova Uptime → Vedi la richiesta nella console locale
Metodo di test 2: tester di webhook#
Usa webhook.site per test gratuiti:
- Vai su webhook.site
- Copia il tuo URL univoco
- Configuralo in Nova Uptime come receiver del webhook
- Test → Vedi la richiesta nella dashboard di webhook.site
Monitorare i tuoi webhook#
Traccia la salute dei webhook:
async function monitorWebhookHealth() {
const stats = await WebhookEvent.aggregate([
{
$group: {
_id: null,
totalEvents: { $sum: 1 },
successCount: { $sum: { $cond: ['$success', 1, 0] } },
failureCount: { $sum: { $cond: ['$success', 0, 1] } },
avgResponseTime: { $avg: '$responseTime' }
}
}
]);
const successRate = stats[0].successCount / stats[0].totalEvents;
if (successRate < 0.95) {
// Alert: Webhook success rate below 95%
await alertSlack(`
Webhook health: ${(successRate * 100).toFixed(1)}% success rate
Failed events: ${stats[0].failureCount}
`);
}
}
Riepilogo: checklist per l'integrazione webhook#
- ✅ Costruisci l'endpoint receiver del webhook
- ✅ Configura il webhook nelle impostazioni di Nova Uptime
- ✅ Testa il webhook con dati di esempio
- ✅ Verifica la firma del webhook (HMAC-SHA256)
- ✅ Implementa logica di retry e idempotenza
- ✅ Aggiungi rate limiting all'endpoint del webhook
- ✅ Configura la gestione del timeout di risposta
- ✅ Crea il workflow per gli incidenti (Jira + Status Page + Slack)
- ✅ Testa con un incidente reale o un guasto forzato
- ✅ Monitora la salute del webhook e il tasso di successo
- ✅ Documenta gli endpoint webhook per il team
Inizia oggi#
I webhook trasformano il monitoraggio da soli avvisi a risposta agli incidenti completamente automatizzata.
Se usi Nova Uptime, vai nelle impostazioni del dominio e aggiungi il tuo primo webhook. Inizia in modo semplice: logga semplicemente gli incidenti nel tuo database. Poi aggiungi le integrazioni una alla volta.
Documentazione webhook: documentazione API Nova Uptime
Monitor Your Website Before It Goes Down
Get uptime monitoring, SSL tracking, domain expiry alerts, and email health checks. Free plan — no credit card required.
Start Monitoring FreeArticoli correlati
Come integrare il monitoraggio uptime con Slack: guida agli avvisi in tempo reale
Configura avvisi Slack per il downtime in 10 minuti. Instrada gli incidenti su #alerts e riduci il tempo di risposta da 30 minuti a 60 secondi.
Monitora i siti web con l'AI usando il Nova Uptime MCP Server
Collega Nova Uptime ad assistenti AI come Claude e Cursor tramite MCP. Configura monitoraggio AI e controlli di email health in pochi minuti.
Avvisi email personalizzati ed escalation: routing avanzato degli incidenti
Progetta workflow di escalation che notificano la persona giusta al momento giusto. Guida al routing degli avvisi, on-call e policy di escalation.