Operazioni e-mail guidate dagli eventi

Smetti di fare polling delle dashboard per aggiornamenti di consegna. Invia accettato, consegnato, rimbalzato e reclamo direttamente alla tua applicazione e ai tuoi workflow.

Usa webhook per sincronizzare stato prodotto, attivare retry, avvisare team e mantenere accurato lo stato cliente.

Webhook delivery depends on stable routing and proper retry logic. Pair with email routing for failover-aware delivery and deliverability monitoring for reputation-aware event handling.

Vista flusso eventi webhook

Capacità webhook

I webhook trasformano l'e-mail da scatola nera in flusso di eventi che il prodotto può interpretare in tempo reale.

Sincronizzazione stato consegna

Aggiorna lo stato visibile all'utente mentre i messaggi passano da accettato a consegnato o rimbalzato.

Automazione fallimenti

Attiva percorsi di retry e avvisi interni quando si rilevano fallimenti transitori o permanenti.

Protezione reputazione

Gestisci automaticamente reclami e rimbalzi per tenere indirizzi problematici fuori dagli invii futuri.

Integrazioni workflow

Alimenta CRM, data warehouse, worker di coda e sistemi di risposta agli incidenti.

Verifica firme

Valida le firme dei webhook in ingresso così elabori solo eventi Sendarix fidati.

Consumer sicuri con retry

Progetta handler idempotenti che elaborano in sicurezza consegne duplicate ed eventi ritardati.

Ciclo di vita webhook

Un flusso chiaro per costruire automazioni affidabili guidate dagli eventi.

1. Invia messaggio

Il messaggio entra nella pipeline di consegna tramite API o SMTP.

2. Evento generato

Il sistema di consegna crea eventi di stato (accettato, consegnato, rimbalzato, reclamo).

3. Webhook consegnato

Gli eventi vengono inviati al tuo endpoint per elaborazione immediata.

4. L'app reagisce

I tuoi sistemi aggiornano stato utente, attivano job o avvisano team automaticamente.

Real-World Scenario: Bounce-Driven Suppression

An application POSTs a message via the email API. The recipient server returns a hard bounce, which is captured by email webhooks and relayed to your system. Your handler adds the address to the suppression list, ensuring no further send attempts. email analytics reflects the suppressed status in the next reporting cycle.

Supported Event Types

Sendarix delivers webhooks for the following event types. Filter by event type when configuring your endpoint.

Event Type Description
acceptedMessage accepted by Sendarix infrastructure
deliveredMessage accepted by recipient mail server
bouncePermanent delivery failure (invalid address)
soft_bounceTemporary delivery failure (mailbox full, Greylisted)
complaintRecipient marked message as spam
unsubscribeRecipient clicked unsubscribe link
openMessage opened (tracking pixel fired)
clickTracked link clicked
deferredTemporary delay - will retry automatically

Example Webhook Payload

Below is a simplified example of a delivery event:

{
  "event": "delivered",
  "message_id": "abc123",
  "recipient": "user@example.com",
  "timestamp": 1710000000
}

Common Webhook Implementation Mistakes

Not handling retries properly

Ignoring duplicate events (lack of idempotency)

Not verifying webhook signatures

Slow endpoints causing delivery timeouts

Pair webhooks with the email API for event-driven automation, and use email analytics to monitor delivery rates and identify issues in real time.

Payload Examples

Every webhook delivers a JSON payload with a consistent envelope structure. Below are examples of the most common event types.

Envelope Structure

All payloads share this top-level structure:

{
  "event_id": "evt_8f3k2j1h9g6d",
  "event_type": "delivered",
  "timestamp": "2026-04-19T14:32:01Z",
  "message_id": "msg_abc123xyz",
  "recipient": "user@example.com",
  "data": {
    // event-specific fields
  }
}

Delivered Event

Fired when a message is accepted by the recipient's mail server.

{
  "event_id": "evt_8f3k2j1h9g6d",
  "event_type": "delivered",
  "timestamp": "2026-04-19T14:32:01Z",
  "message_id": "msg_abc123xyz",
  "recipient": "user@example.com",
  "data": {
    "smtp_response": "250 OK",
    "server": "mail-sor-iad.example.com",
    "delivery_latency_ms": 312
  }
}

Bounce Event

Fired when a message is rejected by the recipient's mail server. Includes bounce type (hard/soft) and error code.

{
  "event_id": "evt_9h4k3l2m7n5p",
  "event_type": "bounce",
  "timestamp": "2026-04-19T14:30:45Z",
  "message_id": "msg_abc123xyz",
  "recipient": "invalid@example.com",
  "data": {
    "bounce_type": "hard",
    "bounce_category": "invalid_email",
    "smtp_code": 550,
    "smtp_message": "No such user",
    "was_automatic": true
  }
}

Complaint Event

Fired when a recipient marks your message as spam. Automatically suppressed for future sends.

{
  "event_id": "evt_1a2b3c4d5e6f",
  "event_type": "complaint",
  "timestamp": "2026-04-19T15:01:22Z",
  "message_id": "msg_abc123xyz",
  "recipient": "user@example.com",
  "data": {
    "complaint_type": "abuse",
    "feedback_type": "auth-failure",
    "user_agent": "Mozilla/5.0 (complaint reporter)"
  }
}

Open Event

Fired when a message is opened by the recipient (requires tracking pixel).

{
  "event_id": "evt_7g8h9i0j1k2l",
  "event_type": "open",
  "timestamp": "2026-04-19T14:45:10Z",
  "message_id": "msg_abc123xyz",
  "recipient": "user@example.com",
  "data": {
    "ip": "203.0.113.42",
    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
    "os": "Windows 10",
    "client": "Chrome 124.0"
  }
}

Click Event

Fired when a recipient clicks a tracked link in the message.

{
  "event_id": "evt_3m4n5o6p7q8r",
  "event_type": "click",
  "timestamp": "2026-04-19T14:47:33Z",
  "message_id": "msg_abc123xyz",
  "recipient": "user@example.com",
  "data": {
    "link_id": "lnk_abc123",
    "url": "https://yoursite.com/confirm?token=xyz",
    "ip": "203.0.113.42",
    "user_agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4)",
    "os": "iOS 17.4"
  }
}

Retry Logic and Failure Handling

Webhook delivery uses exponential backoff with jitter to handle transient failures without overwhelming your endpoint.

Retry Schedule

Failed deliveries (non-2xx, timeout, connection error) are retried at increasing intervals: attempt 1 immediately, attempt 2 after 30 seconds, attempt 3 after 5 minutes, attempt 4 after 30 minutes, attempt 5 after 2 hours, attempt 6 after 5 hours. After 6 failed attempts, the event is marked as permanently failed and no further retries occur.

1
Immediate
2
30s
3
5min
4
30min
5
2hr
6
5hr

Best Practices for Retry-Safe Handlers

Use the event ID in a deduplication table or cache to prevent duplicate processing.

Acknowledge the HTTP request immediately (< 1 second) and process events asynchronously.

Return 2xx before validating signatures to avoid timeout-triggered retries of valid events.

Log received event IDs to aid debugging and manual replay if needed.

Implement a dead-letter queue for events that permanently fail so they can be manually inspected.

Timeout Behavior

If your endpoint does not respond within 10 seconds, the delivery is marked as failed and enters the retry queue immediately.

Security and Verification

Webhook endpoints should validate that requests originate from Sendarix and are not replayed or tampered with.

HMAC Signature Verification

Each webhook request includes an X-Sendarix-Signature header containing an HMAC-SHA256 signature of the raw request body, signed with your endpoint's shared secret. Always verify this signature before processing the payload.

// Node.js signature verification example
const crypto = require('crypto');

function verifySignature(rawBody, signature, secret) {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody, 'utf8')
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

// Express.js middleware
app.post('/webhooks', (req, res) => {
  const signature = req.headers['x-sendarix-signature'];
  const timestamp = req.headers['x-sendarix-timestamp'];
  const secret = process.env.WEBHOOK_SECRET;
  
  // Check timestamp freshness (reject > 5 min old)
  if (Date.now() - parseInt(timestamp, 10) * 1000 > 300000) {
    return res.status(401).send('Timestamp expired');
  }
  
  // Verify signature
  const rawBody = req.rawBody; // must be raw buffer, not parsed JSON
  if (!verifySignature(rawBody, signature, secret)) {
    return res.status(401).send('Invalid signature');
  }
  
  // Process event
  const event = JSON.parse(rawBody);
  res.status(200).send('OK');
});

Timestamp Validation

Requests also include an X-Sendarix-Timestamp header. Reject any request where the timestamp is older than 5 minutes to prevent replay attacks.

Security Best Practices

Never expose your webhook secret in client-side code or version control.

Use HTTPS endpoints only. HTTP endpoints will be rejected.

Rotate secrets periodically and immediately upon suspected compromise.

Validate both signature and timestamp on every request.

Log all validation failures for security audit purposes.

Idempotent Event Handling

Duplicate webhook deliveries are a reality, not an edge case. Network timeouts trigger Sendarix retries, and your endpoint may receive the same event more than once. Idempotent handlers ensure duplicates do not corrupt your application state.

Why Duplicates Happen

Sendarix retries any delivery that returns non-2xx, times out, or fails DNS. If your endpoint returns 200 OK but the response is lost mid-network, Sendarix retries and delivers a second copy. Some load balancers also cause duplicate deliveries when retrying failed requests upstream.

Idempotency Pattern

The standard approach uses a deduplication table keyed on event_id. Before processing, check if the event_id has been processed. If yes, return 200 OK immediately. If no, process the event, mark it as processed, then return 200 OK.

Implementation Example

This example uses a simple in-memory store. In production, use Redis or your database for durability across restarts.

// Node.js idempotent webhook handler
const processedEvents = new Map(); // Replace with Redis/DB in production

app.post('/webhooks', (req, res) => {
  const event = req.body;
  const eventId = event.event_id;

  // Idempotency check - reject if already processed
  if (processedEvents.has(eventId)) {
    console.log(`Duplicate event received: ${eventId}`);
    return res.status(200).send('OK'); // Still return 200 to stop retries
  }

  // Process the event
  try {
    switch (event.event_type) {
      case 'delivered':
        updateNotificationStatus(event.message_id, 'delivered');
        break;
      case 'bounce':
        suppressRecipient(event.recipient);
        break;
      case 'complaint':
        suppressRecipient(event.recipient, 'complaint');
        break;
    }

    // Mark as processed before returning
    processedEvents.set(eventId, Date.now());
    return res.status(200).send('OK');
  } catch (err) {
    console.error('Processing error:', err);
    return res.status(500).send('Processing failed');
  }
});

// TTL cleanup - run periodically in production
setInterval(() => {
  const cutoff = Date.now() - 24 * 60 * 60 * 1000;
  for (const [id, timestamp] of processedEvents) {
    if (timestamp < cutoff) processedEvents.delete(id);
  }
}, 60 * 60 * 1000);

Best Practices

Always check event_id before processing, never after.

Mark events processed atomically: use INSERT ON CONFLICT UPDATE (Postgres) or equivalent.

Keep processed event IDs for at least 24 hours to handle delayed retries.

Process business logic in a separate transaction from the dedup check to avoid race conditions.

Consider setting a TTL on your dedup cache so it does not grow indefinitely for high-volume event streams.

Webhook Endpoint Design Best Practices

A robust webhook endpoint goes beyond signature verification. These practices ensure your integration handles production workloads reliably and avoids the pitfalls that cause data inconsistency and missed events.

Set Appropriate Timeouts

Configure your HTTP client with a 10-second timeout for webhook requests. Sendarix waits up to 10 seconds for a response before triggering a retry. If your handler takes longer (e.g., database writes, external API calls), acknowledge the request immediately with 200 OK and process asynchronously via a job queue.

Process Asynchronously

Webhook handlers should acknowledge within 1 second and defer actual work to a background job. This prevents timeout-triggered retries during slow processing and keeps your endpoint responsive for high event volumes. Use Redis, SQS, or a database-backed job queue.

Return 2xx for Retryable vs Permanent Failures

Return 200 OK for successful processing or permanent failures (unknown event type, invalid payload structure). Return non-2xx only for transient errors (database unavailable, dependency timeout). This tells Sendarix whether to retry immediately or stop retrying.

Log Before and After Processing

Log the event_id, timestamp, and event_type on receipt before processing. Log the outcome (success/failure) and any error details after processing. This gives you a complete record for debugging missed events and reconstructing state during incidents.

Implement a Dead-Letter Queue

After 6 failed delivery attempts, Sendarix marks the event as permanently failed. However, your handler may encounter errors that are not retriable (e.g., a specific recipient is blacklisted in your system, a custom business rule fails). Route these to a dead-letter queue for manual inspection rather than returning a retryable error code.

Handle High-Volume Bursts

Campaign launches and provider incidents can generate webhook bursts of 10,000+ events per minute. Ensure your endpoint scales horizontally (multiple instances behind a load balancer) and your job queue can absorb spikes without losing events or falling behind.

Common Webhook Implementation Mistakes

These mistakes cause the most production incidents in webhook integrations. Avoid them to build a reliable event-driven system.

Processing Synchronously in the HTTP Handler

If your handler writes to a database, calls an external API, or performs complex computation before returning 200 OK, you risk timeouts and unnecessary Sendarix retries. Always enqueue work and return 200 immediately.

Not Validating Event Order

Events may arrive out of order (e.g., a complaint arrives before the delivered event for the same message). Your system must handle this by using message_id as the primary key for state, not relying on event arrival order.

Returning 500 for Permanent Failures

If processing fails because the event is malformed or violates a business rule, return 200 OK to tell Sendarix not to retry. Returning 500 causes Sendarix to retry, which generates duplicate processing attempts and potentially corrupts your state.

Ignoring HTTP Method Validation

Some webhook libraries accept GET and POST to the same endpoint. Sendarix sends POST only. Validate the HTTP method and return 405 Method Not Allowed for any other verb to prevent unexpected behavior.

Processing Without Idempotency Checks

Without event_id deduplication, retry-triggered duplicates cause double-processing: marking a user as unsubscribed twice, decrementing a credit balance twice, sending a notification twice. This is the most common cause of data corruption in webhook integrations.

Hardcoding Webhook Secret

Embedding the webhook secret in source code means rotation requires a code deployment. Store secrets in environment variables or a secrets manager (AWS Secrets Manager, HashiCorp Vault) and rotate without redeployment.

Not Monitoring Endpoint Health

If your endpoint goes down, events queue at Sendarix for up to 5 hours. Monitor your endpoint's availability, queue depth in the Sendarix dashboard, and set up alerts for queue depth exceeding 1,000 events or processing lag exceeding 5 minutes.

Integrating Webhooks with Your Email Stack

Improving Deliverability with Webhook Data

Webhook event data is your primary signal for improving deliverability. Combine bounce and complaint events with your deliverability dashboard to identify reputation issues before they affect your sender score. High bounce rates (>5%) signal list quality problems; high complaint rates trigger provider-level filtering.

Transactional Email with Real-Time Tracking

Webhook events integrate with your transactional email workflow to provide real-time status updates in your application UI. When a delivery confirmation webhook arrives, update the order status. When a bounce fires, trigger an alternative notification path.

Email Analytics Powered by Webhook Events

Raw webhook events feed your email analytics pipeline with complete delivery and engagement data. Stream events to BigQuery or Redshift for custom reporting, A/B test analysis, and long-term trend tracking beyond what the Sendarix dashboard provides.

Common Webhook Use Cases

Real-time event delivery enables patterns that are difficult or impossible to implement with polling.

User Notification State Sync

Update the notification_status field in your user database when messages are delivered or bounce. Show "Email sent" → "Delivered" in the UI without refreshing.

Suppression List Automation

Automatically add bounced and complained addresses to your suppression list via webhook handler. Prevents wasted send attempts and protects sender reputation.

CRM Engagement Tracking

Feed open and click events into your CRM to score leads, trigger follow-up sequences, or update deal stages based on email engagement.

Incident Alerting

Monitor bounce rates and complaint rates via webhooks. Alert on-call engineers when bounce rates exceed 5% or complaint webhooks fire, indicating potential reputation issues.

Data Warehouse Streaming

Stream all email events to your data warehouse (BigQuery, Redshift, Snowflake) via webhook handler for real-time analytics, ML feature engineering, or compliance archival.

Transactional Workflow Triggers

Trigger downstream workflows when email events fire: send a Slack message to sales when a lead opens a demo email, update shipping status when delivery confirmation arrives.

Start Receiving Email Events in Real Time

Configure your webhook endpoint in minutes. Get delivery, bounce, complaint, open, and click events as they happen.

Implementazioni più comuni

Timeline cliente, retry notifiche, logging conformità, dashboard supporto e sync coinvolgimento CRM.

Abbinamento consigliato

Usa con API e-mail per logica prodotto guidata dagli eventi e analitica e-mail per revisione prestazioni cross-flusso.

What sets Sendarix apart: Webhooks on Sendarix are not a polling mechanism — they are pushed events with built-in retry, signature verification, and delivery confirmation. You get infrastructure control over event routing, not just a webhook URL.

Domande frequenti

I webhook sostituiscono completamente il polling?

Per la maggior parte dei flussi guidati dagli eventi, sì. I team usano ancora analitica per analisi storica e reporting.

Quali eventi sono più importanti all'inizio?

Inizia con consegnato, rimbalzato e reclamo. Poi espandi a coinvolgimento o eventi workflow personalizzati.

I webhook sono solo per sistemi grandi?

No. Anche app piccole beneficiano di sincronizzazione immediata dello stato e meno debug supporto manuale.

Come verifichiamo che le richieste webhook siano autentiche?

Usa segreti condivisi, firme o header HMAC dove forniti; valida timestamp contro replay; rifiuta payload che falliscono i controlli prima di aggiornare stato produzione.

Se il nostro endpoint è giù quando parte un webhook?

Affidati a policy di retry e handler idempotenti. Registra ID evento ricevuti così duplicati da retry non corrompono database o notifiche utente.

L'elaborazione webhook deve essere sincrona nella richiesta HTTP?

Di solito no. Accetta rapidamente, metti in coda il lavoro a un job runner ed elabora in modo asincrono così task lenti non causano timeout e retry innecessari.

Possiamo fan-out dello stesso evento a più servizi interni?

Sì, tramite message bus o router. Un solo ingresso che valida e normalizza payload, poi distribuzione a fatturazione, CRM, warehouse o alerting.

Come aiutano i webhook con rimbalzi e reclami?

Permettono di aggiornare liste di soppressione, mettere in pausa campagne rischiose o segnalare account quasi in tempo reale invece di scoprire ore dopo dai ticket.

Servono URL webhook separati per staging e produzione?

Fortemente consigliato. Endpoint isolati evitano che eventi di test tocchino dati utenti reali e facilitano rotazione credenziali in modo indipendente.

What is the format of webhook payloads?

All payloads are JSON with a consistent envelope: event type, timestamp, message ID, and event-specific data. See the Payload Examples section for full schemas.

What happens if our endpoint returns a non-2xx response?

Any response outside the 2xx range triggers a retry. Timeouts, connection refusals, and DNS failures also count as failures and trigger retry logic.

How long does Sendarix wait for our endpoint to respond?

Default timeout is 10 seconds. If your endpoint does not respond within this window, the request is considered failed and enters the retry queue.

Can we filter which events we receive?

Yes. Configure event type filters per endpoint to receive only the events relevant to your integration (e.g., bounces and complaints only).

What HTTP methods does Sendarix use for webhook delivery?

Sendarix sends POST requests only. If your endpoint receives a GET, PUT, PATCH, or DELETE request to the webhook URL, return 405 Method Not Allowed. This prevents accidental processing of unrelated traffic that may hit your endpoint.

How do we handle webhooks during deployment downtime?

Sendarix queues events during the retry window. If your endpoint is down for less than 5 hours, all events are preserved and delivered when your endpoint returns. For extended downtime (maintenance windows, incidents), queue events in Sendarix and process them after recovery via the event replay API.

Should our webhook endpoint be idempotent across different event types?

Yes. Process the event_id regardless of event_type. A given event_id represents one specific event (e.g., evt_abc123 = bounce for msg_xyz). If you receive evt_abc123 twice, return 200 OK on the second attempt without reprocessing. The event_id is globally unique across all event types.

How do we test webhooks in a staging environment without affecting production data?

Configure a separate webhook endpoint in your staging environment with its own secret. Use the Sendarix sandbox mode to send test events that do not count against production limits or affect real recipient addresses. This allows integration testing without generating fake suppression entries or polluting analytics.

What is the maximum number of events we can receive per second?

Sendarix delivers events in real time with no artificial rate limit on webhook delivery. During burst scenarios (e.g., a campaign delivery wave), your endpoint may receive hundreds of events per second. Design your endpoint to scale horizontally and your job queue to absorb these spikes. Monitor queue depth via the API to detect when processing falls behind.

Pronti a passare a un'infrastruttura email affidabile?

Iniziate gratis senza carta o parlate con il commerciale per volumi elevati e enterprise.

Inizia a inviareParla con il commerciale