# External API

SteelEngine provides a comprehensive external API for querying workflow execution logs and setting up webhooks for real-time notifications when workflows complete.

## Authentication

All API requests require an API key passed in the `x-api-key` header:

```bash
curl -H "x-api-key: YOUR_API_KEY" \
  https://steelengine.com/api/v1/logs?workspaceId=YOUR_WORKSPACE_ID
```

Create workspace and personal keys from workspace **Settings → API Keys** by clicking **Create**. Organization keys, which can span several workspaces or workflows, are created from **Organization Settings → API keys**.

Self-hosted Entra deployment applications execute workflows through the platform MCP `steelengine_workflows.run` operation. Follow [Entra workload identities](/self-hosting/entra-workload-identities) for that Bearer path; it does not add Entra authentication to the REST routes on this page.

## Execute Workflow

`POST /api/workflows/{id}/execute` runs a deployed workflow. The [API Reference](/api-reference/getting-started) covers the full contract. The options below shape how SteelEngine admits a run and returns its result.

**Request headers:**

* `x-api-key` - Required unless the workflow has public API access enabled
* `X-Execution-Mode: async` - Queue the run and return `202` immediately with `jobId`, `executionId`, and a `statusUrl` to poll
* `X-Stream-Response: true` - Stream block outputs as Server-Sent Events instead of waiting for the final result (same as `"stream": true` in the body)
* `x-steelengine-deployment-version` - Pin the run to one deployment version ID instead of the live version
* `X-Callback-Url` and `X-Callback-Secret` - Async only. Get a signed POST when the run finishes instead of polling. See [Completion Callbacks](#completion-callbacks)

**Request body:**

* API-key callers put the workflow input at the top level of the body. Every field that is not a control field reaches the Start block, so `{ "message": "Hello" }` arrives as `message`
* `selectedOutputs` - Outputs to include in a streamed response, as `blockName.field` strings
* `stream` - Same as the `X-Stream-Response` header
* `includeFileBase64` (default `true`) and `base64MaxBytes` - Control inline file content in the response. See [Passing Files](/execution/files#receiving-files-in-api-responses)

`useDraftState`, `workflowStateOverride`, and `runFromBlock` are editor-session controls. API-key callers always run the deployed version. If they send one of these controls, the API returns `400`. Async mode also returns `400` for `selectedOutputs`, `includeFileBase64`, and `base64MaxBytes`.

**Response headers:**

* `X-Execution-Id` - The execution ID, on every response
* `X-SteelEngine-Response-Type` - `execution` (final JSON result), `response` (a Response block produced the body), `stream` (SSE), `async` (queued), or `pending` (see below)

**Status codes:**

* `200` - The execution result. When a Response block ran, its status code and body are returned instead.
* `202` with `"async": true` - Queued in async mode. Poll `statusUrl`.
* `202` with `"pending": true` - SteelEngine admitted the run, but the result was not ready before the request timed out. Poll `statusUrl` (`/api/jobs/{executionId}`). Do not resubmit. Session callers also receive a `reconnectUrl` for the execution's SSE stream.
* `503` with a `code` field - SteelEngine admitted the run, but it cannot recover the result. Poll `statusUrl`. Do not resubmit.
* `400` - Invalid body, an option that the authentication type or execution mode does not allow, or invalid [callback headers](#completion-callbacks).

### Completion Callbacks

Send `X-Callback-Url` and `X-Callback-Secret` with `X-Execution-Mode: async`, and SteelEngine POSTs to that URL once the run completes, fails, or is cancelled. You don't need to poll `statusUrl`.

```bash
curl -X POST https://steelengine.com/api/workflows/{workflowId}/execute \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "X-Execution-Mode: async" \
  -H "X-Callback-Url: https://example.com/hooks/steelengine" \
  -H "X-Callback-Secret: $CALLBACK_SECRET" \
  -d '{"message": "Hello"}'
```

The response is the usual async `202` receipt. The callback carries the same `executionId`.

#### Request headers

| Header              | Required                 | Rules                                                                                                                                                                                     |
| ------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `X-Callback-Url`    | With `X-Callback-Secret` | HTTPS only. Must resolve to a public address: private, loopback, and link-local addresses such as `10.0.0.1`, `192.168.1.10`, and `169.254.169.254` are refused. At most 2048 characters. |
| `X-Callback-Secret` | With `X-Callback-Url`    | 16 to 256 characters. SteelEngine stores it encrypted, never logs it, and signs every delivery with it.                                                                                   |

Callbacks are async only. The request returns `400`, and the run is not started, when:

* `X-Callback-Url` is not HTTPS, resolves to a private address, cannot be resolved, or is longer than 2048 characters
* `X-Callback-Secret` is shorter than 16 or longer than 256 characters
* one of the two headers is sent without the other
* a callback header is sent without `X-Execution-Mode: async`

SteelEngine checks the URL again before every delivery, pinning the resolved address so a DNS change cannot redirect it to a private one.

#### When the callback fires

* **Completed, failed, or cancelled:** the callback is sent once the run reaches one of these statuses. A run that the logs show as `denied`, because it stopped on a denial, reports `failed`.
* **Paused runs:** a run waiting for human input is not finished, so it does not trigger the callback. The callback fires when the resumed run finishes, with the same `executionId`.
* **Admission failures:** if the run cannot be started and the request returns `500` with `admissionState: "failed"`, or `409`, SteelEngine discards the callback and sends nothing. With `admissionState: "uncertain"` the run may still start, so the callback is kept and fires if it does.
* **Lost completion events:** if the completion event is lost, a background check picks the finished run up within a few minutes and sends the callback then.
* **Retention:** a callback whose run has not finished within 30 days is dropped.

For self-hosted installations, update both the web app and Temporal Workers. Workers dispatch completed-run callbacks through the web app; callback delivery and reconciliation must be available for the notification to arrive. See [Temporal execution](/self-hosting/temporal).

#### The request your endpoint receives

SteelEngine sends a `POST` with `Content-Type: application/json` and these headers:

| Header                    | Value                                                                                                                                      |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `steelengine-signature`   | `t=<timestamp>,v1=<signature>`, where `<signature>` is the hex HMAC-SHA256 of `<timestamp>.<raw body>` keyed with your `X-Callback-Secret` |
| `steelengine-timestamp`   | Unix timestamp in milliseconds when the attempt was signed. Same value as `t`                                                              |
| `steelengine-event`       | Always `workflow.execution.completed`                                                                                                      |
| `steelengine-delivery-id` | `callback_<executionId>`, the same on every attempt                                                                                        |
| `Idempotency-Key`         | Stable across every attempt for the run                                                                                                    |
| `X-Execution-Id`          | The run's execution ID                                                                                                                     |

The body is the JSON that [Get Job Status](/api-reference/workflows/getJobStatus) returns for the run. `status` is `completed`, `failed`, or `cancelled`. `success` is always `true`: it describes the lookup, not the run. `output` is the run-history copy of the result, size-capped with secrets removed, so `metadata.source` is `run-history`. Failed and cancelled runs also carry `error`.

```json
{
  "success": true,
  "taskId": "exec_abc123",
  "jobId": "exec_abc123",
  "status": "completed",
  "metadata": {
    "workflowId": "wf_1a2b3c4d5e",
    "workspaceId": "wsp_abc123",
    "executionId": "exec_abc123",
    "source": "run-history"
  },
  "output": { "result": "Hello, world!" },
  "startedAt": "2026-01-15T10:30:00.000Z",
  "completedAt": "2026-01-15T10:30:04.000Z"
}
```

#### Verifying the signature

Compute the HMAC over the raw request body exactly as received. Parsing the JSON and serializing it again can change the bytes and break the signature. Compare in constant time, and reject old timestamps to limit replays.

**Node.js**

```javascript
import crypto from 'node:crypto';
import express from 'express';

const TOLERANCE_MS = 5 * 60 * 1000;

function verifyCallback(rawBody, header, secret) {
  const parts = Object.fromEntries(header.split(',').map((part) => part.split('=')));
  const timestamp = Number(parts.t);
  if (!timestamp || Math.abs(Date.now() - timestamp) > TOLERANCE_MS) return false;

  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${parts.t}.${rawBody}`)
    .digest('hex');
  const received = Buffer.from(parts.v1 ?? '', 'hex');
  const computed = Buffer.from(expected, 'hex');
  return received.length === computed.length && crypto.timingSafeEqual(received, computed);
}

const app = express();

app.post('/hooks/steelengine', express.raw({ type: 'application/json' }), (req, res) => {
  const rawBody = req.body.toString('utf8');
  const header = req.get('steelengine-signature') ?? '';
  if (!verifyCallback(rawBody, header, process.env.CALLBACK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }

  const job = JSON.parse(rawBody);
  // Deduplicate on req.get('Idempotency-Key') or job.jobId, then handle job.status.
  res.sendStatus(204);
});
```

**Python**

```python
import hashlib
import hmac
import json
import os
import time

from flask import Flask, request

TOLERANCE_MS = 5 * 60 * 1000
app = Flask(__name__)

def verify_callback(raw_body: bytes, header: str, secret: str) -> bool:
    parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
    timestamp = parts.get("t", "")
    if not timestamp.isdigit() or abs(time.time() * 1000 - int(timestamp)) > TOLERANCE_MS:
        return False

    expected = hmac.new(
        secret.encode(),
        timestamp.encode() + b"." + raw_body,
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))

@app.post("/hooks/steelengine")
def steelengine_callback():
    raw_body = request.get_data()
    header = request.headers.get("steelengine-signature", "")
    if not verify_callback(raw_body, header, os.environ["CALLBACK_SECRET"]):
        return "Invalid signature", 401

    job = json.loads(raw_body)
    # Deduplicate on request.headers["Idempotency-Key"] or job["jobId"], then handle job["status"].
    return "", 204
```

#### Retries

* Return any `2xx` status to acknowledge the delivery. SteelEngine ignores the response body.
* A timeout, connection error, `408`, `429`, or `5xx` is retried. Delivery makes up to 6 attempts in total, waiting 5, 10, 20, and 40 seconds, then 1 minute, between them.
* Any other status, including `3xx` and other `4xx` responses, ends delivery without a retry. So does a failure on the sixth attempt.
* Each attempt has a 15-second deadline covering DNS validation, connection setup, and the response. A server that keeps sending small amounts of data cannot extend that deadline. Redirects are not followed.
* Each attempt is signed with a fresh timestamp, so check the signature on every attempt.
* Worker interruption leaves an unfinished delivery eligible for recovery. Once an attempt records a successful delivery, a late failure from an overlapping attempt cannot change it back to failed.

#### Handling duplicates

A delivery can arrive more than once, for example when your endpoint processed a request but timed out before it responded. Record `Idempotency-Key` (or `X-Execution-Id`, since each run sends one callback) when you process a callback, and acknowledge repeats with `2xx` without processing them again. Respond quickly and move slow work to a queue, so a delivery does not time out and get retried.

A callback reports one run back to the caller that started it. To send every run of a workflow to a webhook, email, or Slack, use [Notifications](#notifications) instead.

## Logs API

All API responses include information about your workflow execution limits and usage:

```json
"limits": {
  "workflowExecutionRateLimit": {
    "sync": {
      "requestsPerMinute": 150,  // Sustained rate limit per minute
      "maxBurst": 300,           // Maximum burst capacity
      "remaining": 298,          // Current tokens available (up to maxBurst)
      "resetAt": "..."           // When tokens next refill
    },
    "async": {
      "requestsPerMinute": 1000, // Sustained rate limit per minute
      "maxBurst": 2000,          // Maximum burst capacity
      "remaining": 1998,         // Current tokens available
      "resetAt": "..."           // When tokens next refill
    }
  },
  "usage": {
    "currentPeriodCost": 1.234,  // Current billing period usage in USD
    "limit": 10,                  // Usage limit in USD
    "plan": "pro",                // Current subscription plan
    "isExceeded": false           // Whether limit is exceeded
  }
}
```

**Note:** Rate limits use a token bucket algorithm. `remaining` can exceed `requestsPerMinute` up to `maxBurst` when you haven't used your full allowance recently, allowing for burst traffic. The rate limits in the response body are for workflow executions. The rate limits for calling this API endpoint are in the response headers (`X-RateLimit-*`).

### Query Logs

Query workflow execution logs with extensive filtering options.

**Request**

```http
GET /api/v1/logs
```

**Required Parameters:**

* `workspaceId` - Your workspace UUID. Find it by inspecting an `/{orgSlug}/{workspaceSlug}/...` dashboard URL and using the [List Workspaces](/api-reference/workspaces/listWorkspaces) endpoint to map the slug to its UUID. The API always uses the UUID, not the slug.

**Optional Filters:**

* `workflowIds` - Comma-separated workflow IDs
* `folderIds` - Comma-separated folder IDs
* `triggers` - Comma-separated trigger types: `manual`, `api`, `schedule`, `chat`, `webhook`, `mcp`, `a2a`, `copilot`, `mothership`, `workflow`, `form`, or an integration provider key such as `slack`
* `level` - Filter by level: `info`, `error`
* `startDate` - ISO timestamp for date range start
* `endDate` - ISO timestamp for date range end
* `executionId` - Exact execution ID match
* `minDurationMs` - Minimum execution duration in milliseconds
* `maxDurationMs` - Maximum execution duration in milliseconds
* `minCost` - Minimum execution cost
* `maxCost` - Maximum execution cost
* `model` - Filter by AI model used

**Pagination:**

* `limit` - Results per page (default: 100)
* `cursor` - Cursor for next page
* `order` - Sort order: `desc`, `asc` (default: desc)

To fetch the next page, pass the response's `nextCursor` as `cursor` and keep the workspace, filters, and sort order unchanged. Treat the cursor as opaque and URL-encode it (for example, with `URLSearchParams`). When `nextCursor` is absent, there are no more matching results.

Results are ordered by `startedAt`, then by log ID when timestamps match. Both fields follow `order`; the default descending order pages toward older executions.

**Detail Level:**

* `details` - Response detail level: `basic`, `full` (default: basic)
* `includeTraceSpans` - Include trace spans (default: false)
* `includeFinalOutput` - Include final output (default: false)

**Response**

```json
{
  "data": [
    {
      "id": "log_abc123",
      "workflowId": "wf_xyz789",
      "executionId": "exec_def456",
      "level": "info",
      "trigger": "api",
      "startedAt": "2025-01-01T12:34:56.789Z",
      "endedAt": "2025-01-01T12:34:57.123Z",
      "totalDurationMs": 334,
      "cost": {
        "total": 0.00234
      },
      "files": null
    }
  ],
  "nextCursor": "eyJzIjoiMjAyNS0wMS0wMVQxMjozNDo1Ni43ODlaIiwiaWQiOiJsb2dfYWJjMTIzIn0",
"limits": {
      "workflowExecutionRateLimit": {
        "sync": {
          "requestsPerMinute": 150,
          "maxBurst": 300,
          "remaining": 298,
          "resetAt": "2025-01-01T12:35:56.789Z"
        },
        "async": {
          "requestsPerMinute": 1000,
          "maxBurst": 2000,
          "remaining": 1998,
          "resetAt": "2025-01-01T12:35:56.789Z"
        }
      },
      "usage": {
        "currentPeriodCost": 1.234,
        "limit": 10,
        "plan": "pro",
        "isExceeded": false
      }
    }
}
```

### Get Log Details

Retrieve detailed information about a specific log entry.

**Request**

```http
GET /api/v1/logs/{id}
```

**Response**

```json
{
  "data": {
    "id": "log_abc123",
    "workflowId": "wf_xyz789",
    "executionId": "exec_def456",
    "level": "info",
    "trigger": "api",
    "startedAt": "2025-01-01T12:34:56.789Z",
    "endedAt": "2025-01-01T12:34:57.123Z",
    "totalDurationMs": 334,
    "workflow": {
      "id": "wf_xyz789",
      "name": "My Workflow",
      "description": "Process customer data"
    },
    "executionData": {
      "traceSpans": [...],
      "finalOutput": {...}
    },
    "cost": {
      "total": 0.00234,
      "tokens": {
        "prompt": 123,
        "completion": 456,
        "total": 579
      },
      "models": {
        "gpt-4o": {
          "input": 0.001,
          "output": 0.00134,
          "total": 0.00234,
          "tokens": {
            "prompt": 123,
            "completion": 456,
            "total": 579
          }
        }
      }
    }
  },
  "limits": {
    "workflowExecutionRateLimit": {
      "sync": {
        "requestsPerMinute": 150,
        "maxBurst": 300,
        "remaining": 298,
        "resetAt": "2025-01-01T12:35:56.789Z"
      },
      "async": {
        "requestsPerMinute": 1000,
        "maxBurst": 2000,
        "remaining": 1998,
        "resetAt": "2025-01-01T12:35:56.789Z"
      }
    },
    "usage": {
      "currentPeriodCost": 1.234,
      "limit": 10,
      "plan": "pro",
      "isExceeded": false
    }
  }
}
```

### Get Execution Details

Retrieve execution details including the workflow state snapshot.

**Request**

```http
GET /api/v1/logs/executions/{executionId}
```

**Response**

```json
{
  "executionId": "exec_def456",
  "workflowId": "wf_xyz789",
  "workflowState": {
    "blocks": {...},
    "edges": [...],
    "loops": {...},
    "parallels": {...}
  },
  "executionMetadata": {
    "trigger": "api",
    "startedAt": "2025-01-01T12:34:56.789Z",
    "endedAt": "2025-01-01T12:34:57.123Z",
    "totalDurationMs": 334,
    "cost": {...}
  }
}
```

## Notifications

Get real-time notifications when workflow executions complete via webhook, email, or Slack. Notifications are configured at the workspace level from the Logs page.

### Configuration

Configure notifications from the Logs page by clicking the menu button and selecting "Configure Notifications".

**Notification Channels:**

* **Webhook**: Send HTTP POST requests to your endpoint
* **Email**: Receive email notifications with execution details
* **Slack**: Post messages to a Slack channel

**Workflow Selection:**

* Select specific workflows to monitor
* Or choose "All Workflows" to include current and future workflows

**Filtering Options:**

* `levelFilter`: Log levels to receive (`info`, `error`)
* `triggerFilter`: Trigger types to receive (the same values as the Logs page trigger filter: `manual`, `api`, `schedule`, `chat`, `webhook`, `mcp`, `a2a`, `copilot`, `mothership`, `workflow`, `form`, and integration provider keys)

**Optional Data:**

* `includeFinalOutput`: Include the workflow's final output
* `includeTraceSpans`: Include detailed execution trace spans
* `includeRateLimits`: Include rate limit information (sync/async limits and remaining)
* `includeUsageData`: Include billing period usage and limits

### Alert Rules

Instead of receiving notifications for every execution, configure alert rules to be notified only when issues are detected:

**Consecutive Failures**

* Alert after X consecutive failed executions (e.g., 3 failures in a row)
* Resets when an execution succeeds

**Failure Rate**

* Alert when failure rate exceeds X% over the last Y hours
* Requires minimum 5 executions in the window
* Only triggers after the full time window has elapsed

**Latency Threshold**

* Alert when any execution takes longer than X seconds
* Useful for catching slow or hanging workflows

**Latency Spike**

* Alert when execution is X% slower than the average
* Compares against the average duration over the configured time window
* Requires minimum 5 executions to establish baseline

**Cost Threshold**

* Alert when a single execution costs more than $X
* Useful for catching expensive LLM calls

**No Activity**

* Alert when no executions occur within X hours
* Useful for monitoring scheduled workflows that should run regularly

**Error Count**

* Alert when error count exceeds X within a time window
* Tracks total errors, not consecutive

All alert types include a 1-hour cooldown to prevent notification spam.

### Webhook Configuration

For webhooks, additional options are available:

* `url`: Your webhook endpoint URL
* `secret`: Optional secret for HMAC signature verification

### Payload Structure

When a workflow execution completes, SteelEngine sends the following payload (via webhook POST, email, or Slack):

```json
{
  "id": "evt_123",
  "type": "workflow.execution.completed",
  "timestamp": 1735925767890,
  "data": {
    "workflowId": "wf_xyz789",
    "workflowName": "My Workflow",
    "executionId": "exec_def456",
    "status": "success",
    "level": "info",
    "trigger": "api",
    "startedAt": "2025-01-01T12:34:56.789Z",
    "endedAt": "2025-01-01T12:34:57.123Z",
    "totalDurationMs": 334,
    "cost": {
      "total": 0.00234,
      "tokens": {
        "prompt": 123,
        "completion": 456,
        "total": 579
      },
      "models": {
        "gpt-4o": {
          "input": 0.001,
          "output": 0.00134,
          "total": 0.00234,
          "tokens": {
            "prompt": 123,
            "completion": 456,
            "total": 579
          }
        }
      }
    },
    "finalOutput": {...},  // Only if includeFinalOutput=true
    "traceSpans": [...],   // Only if includeTraceSpans=true
    "rateLimits": {...},   // Only if includeRateLimits=true
    "usage": {...}         // Only if includeUsageData=true
  }
}
```

### Webhook Headers

Each webhook request includes these headers (webhook channel only):

* `steelengine-event`: Event type (always `workflow.execution.completed`)
* `steelengine-timestamp`: Unix timestamp in milliseconds
* `steelengine-delivery-id`: Unique delivery ID (`delivery_<id>`), the same on every retry of one delivery
* `steelengine-signature`: HMAC-SHA256 signature for verification (if secret configured)
* `Idempotency-Key`: `workspace-notification:<id>` for the same delivery, for duplicate detection

SteelEngine also sends each `steelengine-*` header under a legacy `recall-*` name with the same value.

### Signature Verification

If you configure a webhook secret, verify the signature to ensure the webhook is from SteelEngine:

**Node.js**

```javascript
import crypto from 'crypto';

function verifyWebhookSignature(body, signature, secret) {
  const [timestampPart, signaturePart] = signature.split(',');
  const timestamp = timestampPart.replace('t=', '');
  const expectedSignature = signaturePart.replace('v1=', '');
  
  const signatureBase = `${timestamp}.${body}`;
  const hmac = crypto.createHmac('sha256', secret);
  hmac.update(signatureBase);
  const computedSignature = hmac.digest('hex');
  
  return computedSignature === expectedSignature;
}

// In your webhook handler
app.post('/webhook', (req, res) => {
  const signature = req.headers['steelengine-signature'];
  const body = JSON.stringify(req.body);
  
  if (!verifyWebhookSignature(body, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }
  
  // Process the webhook...
});
```

**Python**

```python
import hmac
import hashlib
import json

def verify_webhook_signature(body: str, signature: str, secret: str) -> bool:
    timestamp_part, signature_part = signature.split(',')
    timestamp = timestamp_part.replace('t=', '')
    expected_signature = signature_part.replace('v1=', '')
    
    signature_base = f"{timestamp}.{body}"
    computed_signature = hmac.new(
        secret.encode(),
        signature_base.encode(),
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(computed_signature, expected_signature)

# In your webhook handler
@app.route('/webhook', methods=['POST'])
def webhook():
    signature = request.headers.get('steelengine-signature')
    body = json.dumps(request.json)
    
    if not verify_webhook_signature(body, signature, os.environ['WEBHOOK_SECRET']):
        return 'Invalid signature', 401
    
    # Process the webhook...
```

### Retry Policy

Failed webhook deliveries are retried with exponential backoff and jitter:

* Maximum attempts: 5
* Retry delays: 5 seconds, 15 seconds, 1 minute, 3 minutes, 10 minutes
* Jitter: Up to 10% additional delay to prevent thundering herd
* Any non-2xx response, timeout, or connection error triggers a retry
* Deliveries timeout after 30 seconds

Webhook deliveries are processed asynchronously and don't affect workflow execution performance.

## Best Practices

1. **Polling Strategy**: When polling for logs, use cursor-based pagination with `order=asc` and `startDate` to fetch new logs efficiently.

2. **Webhook Security**: Always configure a webhook secret and verify signatures to ensure requests are from SteelEngine.

3. **Idempotency**: Use the `Idempotency-Key` header to detect and handle duplicate webhook deliveries.

4. **Privacy**: By default, `finalOutput` and `traceSpans` are excluded from responses. Only enable these if you need the data and understand the privacy implications.

5. **Rate Limiting**: Implement exponential backoff when you receive 429 responses. Check the `Retry-After` header for the recommended wait time.

## Rate Limiting

The API uses a **token bucket algorithm** for rate limiting, providing fair usage while allowing burst traffic:

| Plan         | Requests/Minute | Burst Capacity |
| ------------ | --------------- | -------------- |
| Community    | 30              | 60             |
| Builder      | 100             | 200            |
| Team / Scale | 200             | 400            |
| Enterprise   | 500             | 1000           |

Self-hosted deployments with billing disabled apply the enterprise limits to every account: 600 sync, 5000 async, and 500 API endpoint requests per minute by default. Operators can change the sync and async limits with `RATE_LIMIT_ENTERPRISE_SYNC` and `RATE_LIMIT_ENTERPRISE_ASYNC`.

**How it works:**

* Tokens refill at `requestsPerMinute` rate
* You can accumulate up to `maxBurst` tokens when idle
* Each request consumes 1 token
* Burst capacity allows handling traffic spikes

Rate limit information is included in response headers:

* `X-RateLimit-Limit`: Requests per minute (refill rate)
* `X-RateLimit-Remaining`: Current tokens available
* `X-RateLimit-Reset`: ISO timestamp when tokens next refill

## Example: Polling for New Logs

```javascript
let cursor = null;
const workspaceId = 'YOUR_WORKSPACE_ID';
const startDate = new Date().toISOString();

async function pollLogs() {
  const params = new URLSearchParams({
    workspaceId,
    startDate,
    order: 'asc',
    limit: '100'
  });
  
  if (cursor) {
    params.append('cursor', cursor);
  }
  
  const response = await fetch(
    `https://steelengine.com/api/v1/logs?${params}`,
    {
      headers: {
        'x-api-key': 'YOUR_API_KEY'
      }
    }
  );
  
  if (response.ok) {
    const data = await response.json();
    
    // Process new logs
    for (const log of data.data) {
      console.log(`New execution: ${log.executionId}`);
    }
    
    // Update cursor for next poll
    if (data.nextCursor) {
      cursor = data.nextCursor;
    }
  }
}

// Poll every 30 seconds
setInterval(pollLogs, 30000);
```

## Example: Processing Webhooks

```javascript
import express from 'express';
import crypto from 'crypto';

const app = express();
app.use(express.json());

app.post('/steelengine-webhook', (req, res) => {
  // Verify signature
  const signature = req.headers['steelengine-signature'];
  const body = JSON.stringify(req.body);
  
  if (!verifyWebhookSignature(body, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }
  
  // Check timestamp to prevent replay attacks
  const timestamp = parseInt(req.headers['steelengine-timestamp']);
  const fiveMinutesAgo = Date.now() - (5 * 60 * 1000);
  
  if (timestamp < fiveMinutesAgo) {
    return res.status(401).send('Timestamp too old');
  }
  
  // Process the webhook
  const event = req.body;
  
  switch (event.type) {
    case 'workflow.execution.completed':
      const { workflowId, executionId, status, cost } = event.data;
      
      if (status === 'error') {
        console.error(`Workflow ${workflowId} failed: ${executionId}`);
        // Handle error...
      } else {
        console.log(`Workflow ${workflowId} completed: ${executionId}`);
        console.log(`Cost: $${cost.total}`);
        // Process successful execution...
      }
      break;
  }
  
  // Return 200 to acknowledge receipt
  res.status(200).send('OK');
});

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

## Common Questions

**How do I trigger async execution via the API?**

Set the X-Execution-Mode header to 'async' on your POST request to /api/workflows/{id}/execute. The API returns a 202 response with a jobId, executionId, and a statusUrl you can poll to check when the job completes. Async mode does not support draft state, workflow overrides, or selective output options.

**What authentication methods does the API support?**

The API supports two authentication methods: API keys passed in the x-api-key header, and session-based authentication for logged-in users. Workspace and personal API keys are created from workspace Settings > API Keys; organization keys from Organization Settings > API keys. Workflows with public API access enabled can also be called without authentication.

**How does the webhook retry policy work?**

Failed webhook deliveries are retried up to 5 times with exponential backoff: 5 seconds, 15 seconds, 1 minute, 3 minutes, and 10 minutes, plus up to 10% jitter. Any non-2xx response, timeout, or connection error triggers a retry. Each delivery times out after 30 seconds.

**What rate limits apply to the Logs API?**

Rate limits use a token bucket algorithm. Community gets 30 requests/minute with 60 burst capacity, Builder gets 100/200, Team and Scale get 200/400, and Enterprise gets 500/1000. These are separate from workflow execution rate limits, which are shown in the response body.

**How do I verify that a webhook is from SteelEngine?**

Configure a webhook secret when setting up notifications. SteelEngine signs each delivery with HMAC-SHA256 using the format 't={timestamp},v1={signature}' in the steelengine-signature header. Compute the HMAC of '{timestamp}.{body}' with your secret and compare it to the signature value.

**What alert rules are available for notifications?**

You can configure alerts for consecutive failures, failure rate thresholds, latency thresholds, latency spikes (percentage above average), cost thresholds, no-activity periods, and error counts within a time window. All alert types include a 1-hour cooldown to prevent notification spam.

**Can I filter which executions trigger notifications?**

Yes. You can filter notifications by specific workflows (or select all), log level (info or error), and trigger type (manual, api, schedule, chat, webhook, mcp, a2a, copilot, mothership, workflow, form, or an integration provider). You can also choose whether to include final output, trace spans, rate limits, and usage data in the notification payload.
