Prompt

How do I build an API with webhook support and retries?

Technology / API Platforms1 observationLast seen Oct 22, 2026

Latest observation

Oct 22, 2026OpenAI APIWeb search: off

To build an API with webhook support and retries, you need two main pieces:

  1. Your API publishes events
  2. Your system delivers those events reliably to subscribers’ webhook URLs

A good design treats webhooks as an asynchronous delivery system, not a direct part of the request that triggered the event.


1) Basic architecture

Flow

  1. A user action happens in your API, like order.created
  2. Your system stores the event in a database
  3. A background worker reads pending events
  4. The worker sends an HTTP POST to each subscriber’s webhook URL
  5. If delivery fails, retry with backoff
  6. Mark delivery as succeeded or permanently failed after max attempts

Core components

  • Event store: records what happened
  • Subscription store: stores webhook endpoints and event filters
  • Delivery queue/worker: sends webhook requests asynchronously
  • Retry logic: handles transient failures
  • Signing/authentication: lets receivers verify requests
  • Delivery logs: help debugging and support

2) Data model

A simple schema might include:

webhook_subscriptions

  • id
  • customer_id
  • url
  • events (list of event types subscribed to)
  • secret
  • active
  • created_at
  • updated_at

webhook_events

  • id
  • event_type
  • payload
  • created_at

webhook_deliveries

  • id
  • event_id
  • subscription_id
  • attempt_count
  • status (pending, delivered, failed)
  • next_retry_at
  • last_response_code
  • last_error
  • created_at
  • updated_at

This lets you track each event delivery independently.


3) Webhook request format

Use a consistent JSON body:

{
  "id": "evt_123",
  "type": "order.created",
  "created_at": "2026-10-22T10:00:00Z",
  "data": {
    "order_id": "ord_456",
    "amount": 1999,
    "currency": "USD"
  }
}

Include:

  • unique event ID
  • event type
  • timestamp
  • payload data

4) Send webhooks asynchronously

Never make webhook delivery part of the main user request path. If you do, your API becomes slow and unreliable.

Recommended pattern

  • API request completes quickly
  • Emit event to DB/queue
  • Worker sends webhook in the background

Common tools:

  • Queue: RabbitMQ, SQS, Redis Queue, Kafka, Sidekiq, Celery, BullMQ
  • Worker: any background job runner

5) Retry strategy

Retries should happen for transient failures only.

Retry on:

  • network timeouts
  • DNS failures
  • connection errors
  • HTTP 408
  • HTTP 429
  • HTTP 500, 502, 503, 504

Do not retry on:

  • HTTP 400, 401, 403, 404, 422
  • invalid URL
  • permanently rejected requests

Retry policy example

  • attempt 1 immediately
  • attempt 2 after 1 minute
  • attempt 3 after 5 minutes
  • attempt 4 after 30 minutes
  • attempt 5 after 2 hours
  • then mark as failed

Use exponential backoff with jitter to avoid retry storms.

Example formula:

delay = min(base * 2^attempt, max_delay) + random_jitter

6) Make deliveries idempotent

Webhooks can be delivered more than once due to retries, so receivers must be able to safely handle duplicates.

Include an idempotency key

Add headers like:

  • Webhook-Event-Id: evt_123
  • Webhook-Attempt: 3

The receiver should store processed event IDs and ignore duplicates.


7) Sign webhook requests

To prevent spoofing, sign each request body with a shared secret.

Example approach

  1. Concatenate timestamp + raw body
  2. Compute HMAC SHA-256 using the subscriber secret
  3. Send signature in a header

Example headers:

  • X-Webhook-Timestamp
  • X-Webhook-Signature

The receiver verifies the signature before processing.

Pseudocode

signature = HMAC_SHA256(secret, timestamp + "." + raw_body)

This protects against tampering and replay attacks.


8) Handle timeouts

Webhook endpoints should respond quickly.

Recommendations

  • connect timeout: 3–5 seconds
  • read timeout: 5–10 seconds
  • total timeout: 10–15 seconds max

If the receiver doesn’t respond in time, treat it as a failure and retry.


9) Delivery worker logic

Pseudo-flow:

for each pending delivery:
    send POST request with event payload
    if response 2xx:
        mark delivered
    else if retryable:
        schedule retry with backoff
    else:
        mark failed

Important details

  • limit concurrent requests per subscriber
  • use circuit breakers for failing endpoints
  • stop after max retries
  • preserve response details for debugging

10) Rate limiting and backpressure

Some webhook endpoints may be slow or overloaded.

To protect your system:

  • rate limit deliveries per customer or endpoint
  • queue events instead of sending synchronously
  • cap worker concurrency
  • pause endpoints that consistently fail

You may also want to implement a dead-letter queue for permanently failed deliveries.


11) Observability

Expose delivery status in your dashboard or API:

  • event ID
  • webhook ID
  • last attempt time
  • response code
  • error message
  • next retry time
  • total attempts

This makes support and debugging much easier.


12) Minimal API endpoints

A simple webhook management API might include:

Create subscription

POST /webhooks/subscriptions

List subscriptions

GET /webhooks/subscriptions

Update subscription

PATCH /webhooks/subscriptions/{id}

Delete subscription

DELETE /webhooks/subscriptions/{id}

View delivery attempts

GET /webhooks/deliveries?subscription_id=...

Test webhook

POST /webhooks/subscriptions/{id}/test


13) Example implementation outline

On event creation

def create_order(order_data):
    order = save_order(order_data)
    event = save_event("order.created", {"order_id": order.id})

    subscriptions = get_matching_subscriptions("order.created")
    for sub in subscriptions:
        create_delivery(event.id, sub.id)
        enqueue_delivery_job(event.id, sub.id)

    return order

Delivery worker

def deliver_webhook(event_id, subscription_id):
    event = load_event(event_id)
    sub = load_subscription(subscription_id)

    body = json.dumps({
        "id": event.id,
        "type": event.type,
        "created_at": event.created_at,
        "data": event.payload
    })

    timestamp = now_iso8601()
    signature = sign(sub.secret, timestamp + "." + body)

    response = http_post(
        url=sub.url,
        headers={
            "Content-Type": "application/json",
            "X-Webhook-Timestamp": timestamp,
            "X-Webhook-Signature": signature,
            "Webhook-Event-Id": event.id
        },
        body=body,
        timeout=10
    )

    if 200 <= response.status_code < 300:
        mark_delivered()
    elif is_retryable(response.status_code):
        schedule_retry()
    else:
        mark_failed()

14) Best practices checklist

  • Deliver webhooks asynchronously
  • Store events and delivery attempts
  • Retry only retryable failures
  • Use exponential backoff with jitter
  • Sign requests with HMAC
  • Include event IDs for idempotency
  • Set strict timeouts
  • Provide delivery logs and status
  • Support manual redelivery
  • Rate limit and isolate bad endpoints

15) If you want a quick tech stack recommendation

A common setup:

  • API: Node.js/Express, FastAPI, Django, Go, or Rails
  • Queue: SQS or RabbitMQ
  • Worker: Celery / Sidekiq / BullMQ / custom worker
  • DB: PostgreSQL
  • HTTP client: axios / requests / net/http / faraday
  • Signing: HMAC SHA-256

If you want, I can also provide:

  1. a full example in Node.js, Python, or Go
  2. a database schema
  3. a retry algorithm with code
  4. a webhook receiver example

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (1 observation for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.