> ## Documentation Index
> Fetch the complete documentation index at: https://docs.webrun.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Cost Optimization

> Reduce costs while maintaining performance

WebRun charges for session time and token usage. Three quick changes can cut your costs by 50% or more.

## Quick Wins

### 1. Terminate Sessions Explicitly

Set `terminateOnCompletion: true` on your final task, or call terminate explicitly. This alone reduces costs by 50% if you're currently letting sessions timeout.

```javascript theme={null}
// Single task - auto-terminates
const result = await fetch("https://connect.webrun.ai/start/run-task", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${API_KEY}`
  },
  body: JSON.stringify({
    task: {
      prompt: "Extract data from this page"
    }
  })
});

// Multi-task - terminate on last task
const finalTask = await fetch("https://connect.webrun.ai/start/send-message", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${API_KEY}`
  },
  body: JSON.stringify({
    sessionId,
    message: {
      actionType: "newTask",
      prompt: "Final task here",
      terminateOnCompletion: true
    }
  }
});
```

***

### 2. Write Concise Task Descriptions

Shorter descriptions = fewer input tokens. Be specific, not verbose.

❌ **Verbose (150 tokens):**

```
"Please navigate to the Amazon website and then perform a search for wireless keyboards. After you get the results, I need you to look through them carefully and find the ones that have good ratings, preferably above 4 stars, and then return me a list of the top 5 products with their titles, prices, and rating information."
```

✅ **Concise (35 tokens):**

```
"Go to Amazon, search 'wireless keyboard'. Return top 5 with rating ≥ 4.0 as JSON: title, price, rating."
```

**Impact:** 75% reduction in input tokens for this task.

***

### 3. Set `startingUrl` When Known

Skip navigation by providing the starting URL directly.

```javascript theme={null}
{
  "mode": "default",
  "task": {
    "prompt": "Search for products",
    "startingUrl": "https://amazon.com"  // Skips "go to amazon.com" step
  }
}
```

**Impact:** Saves 5-10 seconds and \~500-1000 tokens per task.

***

## Additional Optimizations

### Set Appropriate `maxDuration`

Limit task duration to prevent runaway costs:

```javascript theme={null}
{
  "task": {
    "prompt": "Quick search task",
    "maxDuration": 30000  // 30 seconds max task duration
  }
}
```

**Guidelines:**

* Simple searches: 30,000ms (30s)
* Form filling: 60,000ms (1 min)
* Multi-step workflows: 120,000ms (2 min)

***

### Batch Related Tasks in Single Sessions

Reuse sessions for related tasks instead of creating new ones.

❌ **Expensive:**

```javascript theme={null}
await runTask("Go to amazon.com");      // New session
await runTask("Search for keyboards");  // Another new session
await runTask("Get first result");      // Yet another session
```

✅ **Optimized:**

```javascript theme={null}
const session = await startSession("Go to amazon.com");
await sendTask(session, "Search for keyboards");
await sendTask(session, "Get first result", { terminateOnCompletion: true });
```

**Impact:** 3x reduction in session overhead costs.

***

### Limit Token Usage

For simple tasks, reduce token limits:

```javascript theme={null}
{
  "task": {
    "prompt": "Get product price",
    "maxInputTokens": 10000,   // Lower for simple tasks (default: 100000)
    "maxOutputTokens": 1000    // Lower for short responses (default: 100000)
  }
}
```

***

### Use Policies to Prevent Detours

Use [automation policies](/concepts/policies) with domain rules to block unnecessary domains and prevent wasted navigation.

***

### Use Custom Proxies for High-Bandwidth Tasks

WebRun-managed proxies cost **\$2 per GB** of data transfer. For tasks that download large files or scrape image-heavy pages, use your own proxy to avoid per-GB charges. Only enable proxies when you actually need geographic targeting or IP management — each proxied session adds 2-3 seconds of cold-start latency.

```javascript theme={null}
{
  "proxy": {
    "source": "custom",
    "type": "http",
    "host": "your-proxy.com",
    "port": "8080"
  },
  "task": {
    "prompt": "Download all product images from the catalog"
  }
}
```

See the [Proxies guide](/usage-guides/proxies) for configuration details.

***

## Monitoring Costs

**Real-time:** Check `usage.cost` in every API response.

```json theme={null}
{
  "success": true,
  "sessionId": "abc123",
  "taskId": "xyz789",
  "type": "task_completed",
  "data": {
    "message": "Task completed successfully"
  },
  "usage": {
    "prompt_tokens": 12450,
    "completion_tokens": 3200,
    "total_tokens": 15650,
    "completion_time": 23.5,
    "cost": 0.0124
  }
}
```

**Dashboard:** View historical usage at [app.webrun.ai/usage](https://app.webrun.ai/usage).

**During polling:** The `usage` object updates in real-time as tasks execute.

***

## Cost Optimization Checklist

* [ ] Use `/start/run-task` for single tasks (auto-terminates)
* [ ] Set `terminateOnCompletion: true` on final tasks in multi-task workflows
* [ ] Write concise, specific task descriptions
* [ ] Provide `startingUrl` when the starting point is known
* [ ] Set appropriate `maxDuration` based on task complexity
* [ ] Batch related tasks into single sessions
* [ ] Limit `maxInputTokens` and `maxOutputTokens` for simple tasks
* [ ] Use [policies](/concepts/policies) to prevent accidental navigation
* [ ] Use custom proxies instead of WebRun-managed for high-bandwidth tasks
* [ ] Monitor `usage.cost` in responses to track spending

***

## Example: Before & After

**Before: Expensive**

```javascript theme={null}
// Creates 3 separate sessions
const result1 = await runTask("Go to amazon.com");
await sleep(5000); // Forgot to terminate, paying for idle time
const result2 = await runTask("Please navigate to the search box and then type in 'wireless keyboard' and press enter");
await sleep(5000);
const result3 = await runTask("Get me information about the first result");
```

**After: Optimized**

```javascript theme={null}
// Single session, concise tasks, explicit termination
const session = await startSession({
  mode: "default",
  task: {
    prompt: "Go to amazon.com",
    startingUrl: "https://amazon.com",
    maxDuration: 60000  // 1 minute max
  }
});

await sendTask(session, "Search 'wireless keyboard'");

await sendTask(session, "Return first result as JSON: title, price, rating", {
  terminateOnCompletion: true
});
```

**Savings:** \~70% cost reduction from session reuse, concise prompts, and explicit termination.

***

<CardGroup cols={2}>
  <Card title="Pricing" icon="credit-card" href="/concepts/pricing">
    Understand WebRun's pricing model
  </Card>

  <Card title="Session Control" icon="gamepad" href="/usage-guides/controlling-sessions">
    Manage session lifecycle
  </Card>

  <Card title="Multi-Task Workflows" icon="list-check" href="/usage-guides/multi-task-workflows">
    Chain tasks efficiently
  </Card>

  <Card title="Structured Output" icon="code" href="/usage-guides/structured-output">
    Request minimal, structured responses
  </Card>
</CardGroup>
