Guida all'Idempotenza

Ripeti le richieste in sicurezza senza duplicare le operazioni

Usa l'header Idempotency-Key per ripetere una richiesta in sicurezza senza creare duplicati.

Perché l'Idempotenza è Importante

I guasti di rete capitano. Senza idempotenza:

  • Ripeti una richiesta di invio email → 2 email inviate
  • Ripeti l'invio di una campagna → 2 campagne inviate

Con l'idempotenza:

  • Ripeti una richiesta di invio email → stessa risposta, 1 sola email inviata

Come Funziona

  1. Genera un UUID v4 per la tua operazione
  2. Includilo nell'header Idempotency-Key
  3. Se la richiesta fallisce, riprova con la stessa chiave
  4. Tratto restituisce la risposta originale (o lo stesso risultato)

Implementazione

Node.js

import { v4 as uuidv4 } from 'uuid';

const idempotencyKey = uuidv4();

const response = await fetch('https://api.tratto.email/v1/emails', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer tratto_live_...',
    'Idempotency-Key': idempotencyKey,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    from: '[email protected]',
    to: '[email protected]',
    subject: 'Hello',
    text: 'Test',
  }),
});

// Se la richiesta fallisce, riprova con la stessa chiave
const data = await response.json();

Python

import uuid
import requests

idempotency_key = str(uuid.uuid4())

response = requests.post(
  'https://api.tratto.email/v1/emails',
  headers={
    'Authorization': 'Bearer tratto_live_...',
    'Idempotency-Key': idempotency_key,
  },
  json={
    'from': '[email protected]',
    'to': '[email protected]',
    'subject': 'Hello',
    'text': 'Test',
  },
)

data = response.json()

Endpoint Supportati

Due endpoint rispettano Idempotency-Key:

  • POST /v1/emails: Invio email
  • POST /v1/api-keys: Creazione di una chiave API

Inviare l'header ad altri endpoint è innocuo ma non ha alcun effetto.

Formato della Chiave

Usa un UUID v4 (RFC 4122):

550e8400-e29b-41d4-a716-446655440000

Tecnicamente è valida qualsiasi stringa univoca, ma UUID v4 è il formato consigliato.

Durata della Cache

Le chiavi di idempotenza restano in cache per 24 ore. Se riprovi entro 24 ore ottieni la stessa risposta; dopo, la chiave scade.

Buone Pratiche

1. Usala Sempre per le Operazioni Critiche

// Includila sempre nell'invio email
const idempotencyKey = uuidv4();

2. Genera Chiavi Nuove

// ✅ Una chiave nuova per ogni operazione
const key1 = uuidv4();
const key2 = uuidv4();

// ❌ Riutilizzare la chiave per operazioni diverse
const key = uuidv4();
sendEmail(key); // OK
sendCampaign(key); // Sbagliato! Operazione diversa

3. Strategia di Retry con Idempotenza

async function sendWithIdempotency(emailData) {
  const idempotencyKey = uuidv4();

  for (let attempt = 0; attempt < 3; attempt++) {
    try {
      const response = await fetch('https://api.tratto.email/v1/emails', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer tratto_live_...',
          'Idempotency-Key': idempotencyKey, // Stessa chiave su tutti i retry
        },
        body: JSON.stringify(emailData),
      });
      return await response.json();
    } catch (error) {
      if (attempt < 2) {
        const delay = Math.pow(2, attempt) * 1000;
        await new Promise(r => setTimeout(r, delay));
      } else {
        throw error;
      }
    }
  }
}

Prossimo: Rate Limit


Modifica questa pagina su GitHub

Ultimo aggiornamento