# Webhooks (https://inference.net/docs/api/async/webhooks)

<Callout tone="warning">

Webhook support is available for all slow endpoints: `/chat/completions`,
`/completions`, and `/embeddings` calls.

</Callout>

Webhooks notify your application when an asynchronous generation completes.
Instead of repeatedly polling the API for the status of a
[`/v1/slow`](/docs/api/async/overview/) or [group](/docs/api/async/group/)
request, your endpoint receives a POST when the result is ready.

## Why use webhooks

- **Resource efficiency:** no API calls spent on status checks
- **Real-time updates:** a notification arrives about one second after a
  generation completes
- **Scalability:** handle thousands of concurrent generations
- **Better user experience:** update your UI as soon as results are ready

## Set up a webhook

<Steps>
  <Step title="Create a webhook endpoint">

Your application needs an HTTPS endpoint that accepts POST requests. The
endpoint should:

1. Accept JSON payloads
2. Respond with HTTP 200 immediately
3. Process the webhook data asynchronously

<CodeTabs>

```typescript
import express from "express";

const app = express();

app.post("/webhooks/inference", express.json(), (req, res) => {
  const { event, data } = req.body;

  // Verify webhook source via headers
  const webhookId = req.headers["x-inference-webhook-id"];

  if (event === "generation.completed") {
    console.log(`Generation ${data.id} completed with status: ${data.state}`);

    // Process asynchronously
    setImmediate(() => {
      processGenerationResult(data);
    });
  } else if (event === "async-embedding.completed") {
    console.log(`Embedding ${data.id} completed with status: ${data.state}`);

    setImmediate(() => {
      processEmbeddingResult(data);
    });
  }

  // Always respond immediately
  res.status(200).json({ received: true });
});

app.listen(3000, () => {
  console.log("Webhook receiver listening on port 3000");
});
```

```python
from fastapi import FastAPI, Request, BackgroundTasks
from pydantic import BaseModel
from typing import Optional, Dict, Any

app = FastAPI()

class WebhookPayload(BaseModel):
    event: str
    timestamp: str
    webhookId: str
    data: Dict[str, Any]

def process_generation(payload: WebhookPayload):
    """Process generation result asynchronously"""
    if payload.event == "generation.completed":
        print(f"Processing generation {payload.data['id']}")
        # Your processing logic here
    elif payload.event == "async-embedding.completed":
        print(f"Processing embedding {payload.data['id']}")
        # Your embedding processing logic here

@app.post("/webhooks/inference")
async def handle_webhook(
    payload: WebhookPayload,
    request: Request,
    background_tasks: BackgroundTasks,
):
    # Verify webhook source
    webhook_id = request.headers.get("x-inference-webhook-id")

    # Queue for background processing
    background_tasks.add_task(process_generation, payload)

    return {"received": True}
```

```go
package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

type WebhookPayload struct {
    Event      string         `json:"event"`
    Timestamp  string         `json:"timestamp"`
    WebhookID  string         `json:"webhookId"`
    Data       map[string]any `json:"data"`
}

func handleWebhook(w http.ResponseWriter, r *http.Request) {
    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Failed to read body", http.StatusBadRequest)
        return
    }

    var payload WebhookPayload
    if err := json.Unmarshal(body, &payload); err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }

    // Verify webhook source
    webhookID := r.Header.Get("X-Inference-Webhook-ID")

    // Process asynchronously
    go func() {
        switch payload.Event {
        case "generation.completed":
            fmt.Printf("Processing generation %s\n", payload.Data["id"])
            // Your processing logic here
        case "async-embedding.completed":
            fmt.Printf("Processing embedding %s\n", payload.Data["id"])
            // Your embedding processing logic here
        }
    }()

    // Respond immediately
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(map[string]bool{"received": true})
}

func main() {
    http.HandleFunc("/webhooks/inference", handleWebhook)
    fmt.Println("Webhook server listening on :3000")
    http.ListenAndServe(":3000", nil)
}
```

</CodeTabs>

  </Step>
  <Step title="Deploy your endpoint">

Your webhook endpoint must be publicly reachable over HTTPS. For development,
consider:

- **ngrok:** `ngrok http 3000`
- **Cloudflare Tunnel:** provides a stable URL
- **localtunnel:** `lt --port 3000`

To check the endpoint before you register it, [test it](#test-your-endpoint).

</Step>
<Step title="Register the webhook">

1. Go to [**Settings → Webhooks**](/dashboard/settings/webhooks/) in the
   dashboard.
2. Create a webhook.
3. Enter a descriptive name and your HTTPS endpoint URL.
4. Save the webhook.

The URL must use HTTPS and point to a public host. URLs for `localhost`, private
networks, IP addresses in private ranges, and `inference.net` or `inference.cool`
hosts (including their subdomains) are rejected.

You get a webhook identifier (for example `AhALzdz8S`) to use when you create
generations.

  </Step>
  <Step title="Link the webhook to generations">

Include the webhook identifier in the request metadata when you create a
generation:

<CodeTabs>

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.inference.net/v1/slow",
  apiKey: process.env.INFERENCE_API_KEY,
});

const response = await client.chat.completions.create({
  model: "kimi-k3-fast",
  messages: [{ role: "user", content: "Explain quantum computing" }],
  // @ts-expect-error metadata is not in the OpenAI SDK types
  metadata: {
    webhook_id: "AhALzdz8S",
  },
});
```

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.inference.net/v1/slow",
    api_key=os.environ["INFERENCE_API_KEY"],
)

response = client.chat.completions.create(
    model="kimi-k3-fast",
    messages=[{"role": "user", "content": "Explain quantum computing"}],
    extra_body={
        "metadata": {"webhook_id": "AhALzdz8S"},
    },
)
```

```bash
curl https://api.inference.net/v1/slow/chat/completions \
  -H "Authorization: Bearer $INFERENCE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "kimi-k3-fast",
    "messages": [
      {"role": "user", "content": "Explain quantum computing"}
    ],
    "metadata": {
      "webhook_id": "AhALzdz8S"
    }
  }'
```

</CodeTabs>

When the generation completes, your endpoint receives a notification.

If `webhook_id` does not match a webhook in your team, the request fails with
`400` and error type `WebhookNotFound`. A disabled webhook is accepted, but no
notification is sent. With [Zero Data Retention (ZDR)](/docs/data-retention/) on,
a disabled webhook fails with `400` and error type `WebhookDisabled` instead.

  </Step>
</Steps>

## Webhook events

### generation.completed

Sent when a generation finishes processing, successfully or with a failure:

```json
{
  "event": "generation.completed",
  "timestamp": "2025-01-03T06:46:22.838Z",
  "webhookId": "AhALzdz8S",
  "data": {
    "id": "XBKcs7F1s2oJ_AHiLMbF4",
    "state": "Success",
    "stateMessage": "Generation successful",
    "request": {
      "messages": [
        { "role": "system", "content": "You are a helpful assistant." },
        { "role": "user", "content": "Explain quantum computing" }
      ],
      "model": "kimi-k3-fast",
      "stream": false,
      "max_tokens": 100,
      "metadata": {
        "webhook_id": "AhALzdz8S"
      }
    },
    "response": {
      "id": "XBKcs7F1s2oJ_AHiLMbF4",
      "object": "chat.completion",
      "created": 1748933182,
      "model": "kimi-k3-fast",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "Quantum computing is a revolutionary approach..."
          },
          "finish_reason": "stop"
        }
      ],
      "usage": {
        "prompt_tokens": 28,
        "completion_tokens": 42,
        "total_tokens": 70
      }
    },
    "model": "kimi-k3-fast",
    "createdAt": "2025-01-03T06:46:18.000Z",
    "dispatchedAt": "2025-01-03T06:46:19.100Z",
    "firstChunkAt": "2025-01-03T06:46:20.200Z",
    "finishedAt": "2025-01-03T06:46:22.307Z",
    "deadlineAt": null,
    "usage": {
      "prompt_tokens": 28,
      "completion_tokens": 42,
      "total_tokens": 70
    }
  }
}
```

The generation ID is the `data.id` field. The `response` object is compatible
with the types exported from the official OpenAI SDKs.

<CodeTabs>

```typescript
import type { OpenAI } from "openai";

const response = responseJsonObject as OpenAI.Chat.Completions.ChatCompletion;
```

```python
from openai.types.chat.chat_completion import ChatCompletion

response: ChatCompletion = webhook_payload.data["response"]
```

</CodeTabs>

### async-embedding.completed

Sent when an async embedding request finishes processing. The payload has the
same shape as `generation.completed`, with an embeddings request in `request`
and a standard OpenAI embeddings response in `response`. The generation ID is
the `data.id` field. See the
[webhooks reference](/docs/api/async/webhooks-reference/#async-embeddingcompleted)
for the full structure.

### slow-group.completed

Sent when every request in a [group](/docs/api/async/group/) finishes, or when
the group fails. See the
[webhooks reference](/docs/api/async/webhooks-reference/#slow-groupcompleted)
for the payload.

## Headers

All webhook requests include these headers:

| Header                         | Description                           | Example                 |
| ------------------------------ | ------------------------------------- | ----------------------- |
| `X-Inference-Event`            | Event type                            | `generation.completed`  |
| `X-Inference-Webhook-ID`       | Webhook identifier                    | `AhALzdz8S`             |
| `X-Inference-Generation-ID`    | Generation ID (for generation events) | `XBKcs7F1s2oJ_AHiLMbF4` |
| `X-Inference-Embedding-ID`     | Generation ID (for embedding events)  | `EMB_abc123`            |
| `X-Inference-Group-ID`         | Group ID (for group events)           | `GRP_XYZ123`            |
| `X-Inference-Delivery-Attempt` | Delivery attempt, starting at 1       | `1`                     |
| `User-Agent`                   | Inference.net webhook agent           | `Kuzco-Webhook/1.0`     |
| `Content-Type`                 | Always `application/json`             | `application/json`      |

Embedding events send `X-Inference-Generation-ID` too, with the same value as
`X-Inference-Embedding-ID`. Each delivery attempt is a single `POST` request.
There is no `OPTIONS` preflight.

### Verify the request source

<Callout tone="warning">

The `X-Inference-Webhook-ID` header is how you verify that a payload comes from
the Inference.net API.

This ID is unique to your webhook, and private to you and your team.

If the ID does not match what you see in the dashboard, your endpoint has most
likely been discovered by a malicious actor.

</Callout>

## Test your endpoint

Send a sample event to a URL and see how your endpoint answers. A test does not
create or change a webhook.

1. Go to [**Settings → Webhooks**](/dashboard/settings/webhooks/) in the
   dashboard.
2. Click **Test a URL**. To test a saved webhook, click **Send test** on that
   webhook instead.
3. Enter the HTTPS URL and choose an event type: `generation.completed`,
   `slow-group.completed`, or `async-embedding.completed`.
4. Click **Send test event**.

The result shows:

- The HTTP status and the latency. Any `2xx` status is a success.
- For a `3xx` status, its `Location`. The test does not follow redirects, so a
  `3xx` is a failure.
- The first 2 KB of the response body, as plain text.
- The request headers and JSON payload that were sent, with copy buttons.

Live deliveries follow only `307` and `308` redirects. Register the final URL,
not a URL that redirects.

### What a test sends

A test sends one `POST` with the same headers and payload shape as a live
delivery, with these differences:

- The payload is sample data with no customer data. IDs start with `test-`. See
  [dashboard test events](/docs/api/async/webhooks-reference/#dashboard-test-events).
- The test is not retried. `X-Inference-Delivery-Attempt` is `1`.
- A URL that is not saved as a webhook has no webhook identifier, so
  `X-Inference-Webhook-ID` and the payload `webhookId` (`webhook_id` for
  `webhook.test`) are `test-webhook`. A test of a saved webhook sends its real
  identifier.
- The test is not counted in the webhook's invocation stats.

If your endpoint
[checks `X-Inference-Webhook-ID`](#verify-the-request-source), it rejects
`test-webhook`. To test that check, test the saved webhook.

### Test limits

- The URL must use HTTPS. Private, loopback, and link-local hosts are rejected,
  along with `inference.net`, `inference.cool`, and their subdomains, as well as
  host names that resolve to those addresses or zones.
- Your endpoint must respond within 30 seconds, the same as for live deliveries.
- You can send 5 tests per minute per user and 20 per minute per team. Over that
  limit, a test fails with `429 Too Many Requests`.
- Tests can come from different IP addresses than live deliveries. An IP
  allowlist that admits live deliveries can still block a test.

## Manage webhooks

[**Settings → Webhooks**](/dashboard/settings/webhooks/) lists your active and
disabled webhooks. From there you can:

- Create a webhook with a name and URL
- Send a test event
- Disable a webhook to stop notifications, and enable it again
- Delete a webhook
- See recent invocation stats

## Best practices

### Respond immediately

Your endpoint must respond within 30 seconds. Always return a 200 status
immediately and process the webhook asynchronously:

<CodeTabs>

```typescript
// Correct approach
app.post("/webhook", (req, res) => {
  res.status(200).send("OK");
  processWebhookAsync(req.body);
});

// Incorrect approach — may timeout
app.post("/webhook", async (req, res) => {
  await heavyProcessing(req.body); // Risk of timeout
  res.status(200).send("OK");
});
```

```python
# Correct approach — process in background
@app.post("/webhook")
async def handle_webhook(
    payload: WebhookPayload,
    background_tasks: BackgroundTasks,
):
    background_tasks.add_task(process_webhook, payload)
    return {"received": True}

# Incorrect approach — may timeout
@app.post("/webhook")
async def handle_webhook(payload: WebhookPayload):
    await heavy_processing(payload)  # Risk of timeout
    return {"received": True}
```

</CodeTabs>

### Make processing idempotent

Failed webhooks are retried, and a retry can arrive after your endpoint already
processed the event. Use `data.id` to make sure you don't process the same event
twice. The `timestamp` field is the same on every attempt for an event, and
`X-Inference-Delivery-Attempt` tells you which attempt you received:

<CodeTabs>

```typescript
const processedGenerations = new Set<string>();

async function processWebhook(payload: any) {
  const generationId = payload.data.id;
  if (processedGenerations.has(generationId)) {
    return; // Already processed
  }

  processedGenerations.add(generationId);
  // Process the generation
}
```

```python
processed_generations: set[str] = set()

def process_webhook(payload: WebhookPayload):
    generation_id = payload.data["id"]
    if generation_id in processed_generations:
        return  # Already processed

    processed_generations.add(generation_id)
    # Process the generation
```

</CodeTabs>

For `slow-group.completed` events, use the top-level `groupId` field for
idempotency.

### Validate the webhook source

Verify that webhooks come from Inference.net by checking for the expected
headers:

<CodeTabs>

```typescript
function validateWebhookSource(headers: Record<string, string>): boolean {
  const requiredHeaders = ["x-inference-webhook-id", "x-inference-event"];
  return requiredHeaders.every((header) => headers[header]);
}
```

```python
def validate_webhook_source(headers: dict) -> bool:
    required_headers = ["x-inference-webhook-id", "x-inference-event"]
    return all(headers.get(h) for h in required_headers)
```

</CodeTabs>

### Handle errors gracefully

Handle errors so one failure doesn't affect the rest of your system:

<CodeTabs>

```typescript
async function handleWebhook(payload: any) {
  try {
    await processWebhook(payload);
  } catch (error) {
    console.error("Webhook processing failed:", error);
    // Log to monitoring service
    // Return 200 to prevent unnecessary retries
  }
}
```

```python
async def handle_webhook(payload: WebhookPayload):
    try:
        await process_webhook(payload)
    except Exception as error:
        print(f"Webhook processing failed: {error}")
        # Log to monitoring service
        # Return 200 to prevent unnecessary retries
```

</CodeTabs>

### Monitor webhook processing

Track these metrics to keep webhook processing reliable:

- Webhook receipt rate
- Processing success and failure rates
- Average processing time
- Queue depth (if you use queues)

## Troubleshooting

### Not receiving webhooks

1. **Check webhook status:** make sure the webhook is not disabled in
   [Settings → Webhooks](/dashboard/settings/webhooks/).
2. **Test connectivity:** [send a test event](#test-your-endpoint).
3. **Verify the URL:** confirm your endpoint is publicly reachable over HTTPS.
4. **Check logs:** review your server logs and any reverse proxy logs.
5. **Validate metadata:** make sure you include the correct `webhook_id` in
   generation requests.

### Webhooks arriving late

- Make sure your endpoint responds quickly (ideally under 1 second).
- Don't do heavy processing before responding.
- Monitor your server load and resource usage.

### Duplicate deliveries

- Make processing idempotent with `data.id` (or `groupId` for group events).
- Make sure your endpoint always returns 200 OK for a successful receipt.
- Check for errors in your webhook processing that might trigger retries.

## FAQ

**What happens if my endpoint is down?**
A failed delivery is retried after 5 seconds, 30 seconds, 2 minutes, 10
minutes, 30 minutes, 1 hour, and 2 hours, and then every 4 hours. Each delay
varies by up to 20%. After 24 attempts (about 3 days), the event is dropped.
See [Retries and delivery](/docs/api/async/webhooks-reference/#retries-and-delivery)
for the full schedule and which failures are not retried.
A dropped event's request and response content is deleted, so its result
cannot be fetched. See [Data retention](/docs/data-retention/#asynchronous-results-are-kept-until-delivery-finishes).

**What's the webhook timeout?**
Webhook endpoints must respond within 30 seconds. A timeout is treated as a
failure and triggers retries.

**Can I filter which events I receive?**
No. Webhooks receive all event types.

**How secure are webhooks?**
Webhook URLs must use HTTPS. Validate the webhook source with the headers above.
Webhooks are not signed with an HMAC signature.

**What's the maximum payload size?**
Payloads scale with the size of the generation they describe; a payload is
larger for generations with long requests or responses. There is no fixed size
limit.

**Can I replay missed webhooks?**
No. A result's content is deleted once its event is delivered or dropped, so
store each result when your endpoint receives it.

## Support

For help with webhooks, email
[support@inference.net](mailto:support@inference.net).