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

# Create Session

> Create a new isolated execution session

## Overview

Creates a new session that provides an isolated Bun runtime environment. Sessions persist files, processes, and state across multiple API calls during a conversation or workflow.

## Request

<ParamField header="Authorization" type="string" required>
  Bearer token with your API key
</ParamField>

<ParamField header="Content-Type" type="string" required>
  Must be `application/json`
</ParamField>

<ParamField header="Idempotency-Key" type="string" optional>
  Unique key to safely retry requests
</ParamField>

### Request Body

<ParamField body="ttl" type="integer" optional>
  Time-to-live in seconds. Default: 86400 (24 hours). Max: 604800 (7 days)
</ParamField>

<ParamField body="metadata" type="object" optional>
  Custom metadata to attach to the session (max 16KB)
</ParamField>

<ParamField body="resourceLimits" type="object" optional>
  Override default resource limits (paid plans only)

  <Expandable title="properties">
    <ParamField body="memory" type="integer" optional>
      Memory limit in MB (default: 1024)
    </ParamField>

    <ParamField body="cpu" type="number" optional>
      CPU cores (default: 0.25)
    </ParamField>

    <ParamField body="timeout" type="integer" optional>
      Default execution timeout in seconds (default: 30, max: 300)
    </ParamField>
  </Expandable>
</ParamField>

## Response

<ResponseField name="sessionId" type="string" required>
  Unique identifier for the session (format: `ses_` + alphanumeric)
</ResponseField>

<ResponseField name="expiresAt" type="string" required>
  ISO 8601 timestamp when the session will be deleted
</ResponseField>

<ResponseField name="previewUrl" type="string" required>
  URL for accessing web apps running in this session
</ResponseField>

<ResponseField name="createdAt" type="string" required>
  ISO 8601 timestamp when the session was created
</ResponseField>

<ResponseField name="resourceLimits" type="object" required>
  Applied resource limits

  <Expandable title="properties">
    <ResponseField name="memory" type="integer">
      Memory limit in MB
    </ResponseField>

    <ResponseField name="cpu" type="number">
      CPU cores allocated
    </ResponseField>

    <ResponseField name="timeout" type="integer">
      Default execution timeout in seconds
    </ResponseField>

    <ResponseField name="disk" type="integer">
      Disk space limit in MB
    </ResponseField>
  </Expandable>
</ResponseField>

## Example

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.buntime.sh/sessions/create \
    -H "Authorization: Bearer $BUNTIME_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "ttl": 3600,
      "metadata": {
        "userId": "user_123",
        "conversationId": "conv_456"
      }
    }'
  ```

  ```typescript TypeScript SDK theme={null}
  import { Buntime } from 'buntime.sh';

  const client = new Buntime({
    apiKey: process.env.BUNTIME_API_KEY
  });

  const session = await client.sessions.create({
    ttl: 3600,
    metadata: {
      userId: 'user_123',
      conversationId: 'conv_456'
    }
  });

  console.log('Session ID:', session.id);
  console.log('Preview URL:', session.previewUrl);
  ```

  ```javascript JavaScript theme={null}
  const Buntime = require('buntime.sh');

  const client = new Buntime({
    apiKey: process.env.BUNTIME_API_KEY
  });

  const session = await client.sessions.create({
    ttl: 3600,
    metadata: {
      userId: 'user_123',
      conversationId: 'conv_456'
    }
  });

  console.log('Session ID:', session.id);
  console.log('Preview URL:', session.previewUrl);
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "sessionId": "ses_abc123def456ghi789",
    "expiresAt": "2024-01-20T10:30:00Z",
    "previewUrl": "https://ses-abc123def456ghi789.buntime.sh",
    "createdAt": "2024-01-19T10:30:00Z",
    "resourceLimits": {
      "memory": 1024,
      "cpu": 0.25,
      "timeout": 30,
      "disk": 1024
    }
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "error": {
      "code": "unauthorized",
      "message": "Invalid API key"
    }
  }
  ```

  ```json 429 Rate Limited theme={null}
  {
    "error": {
      "code": "rate_limit_exceeded",
      "message": "Rate limit exceeded. Try again in 60 seconds.",
      "retryAfter": 60
    }
  }
  ```

  ```json 400 Bad Request theme={null}
  {
    "error": {
      "code": "invalid_request",
      "message": "Invalid TTL value",
      "details": {
        "field": "ttl",
        "value": 999999,
        "max": 604800
      }
    }
  }
  ```
</ResponseExample>

## Session Lifecycle

1. **Active**: Session is running and accepting requests
2. **Idle**: No requests for 5 minutes, container sleeps (billed at reduced rate)
3. **Deep Sleep**: No requests for 30 minutes, filesystem saved to storage
4. **Expired**: TTL reached, session and all data deleted

<Note>
  Sessions automatically wake from sleep when you make a request. Wake time is typically under 3 seconds.
</Note>

## Use Cases

<AccordionGroup>
  <Accordion icon="comments" title="AI Conversations">
    Create a session at the start of a conversation. Files and state persist across messages, allowing iterative development.
  </Accordion>

  <Accordion icon="code" title="Code Playgrounds">
    Give users their own isolated environment to experiment with code.
  </Accordion>

  <Accordion icon="robot" title="Agent Workflows">
    Each agent workflow gets its own session with a custom TTL based on expected duration.
  </Accordion>

  <Accordion icon="database" title="Stateful Processing">
    Run databases or other stateful services that need to persist between API calls.
  </Accordion>
</AccordionGroup>

## Best Practices

<CardGroup cols={2}>
  <Card title="Set appropriate TTL" icon="clock">
    Use shorter TTLs (1 hour) for ephemeral tasks, longer (24 hours) for conversations
  </Card>

  <Card title="Use metadata" icon="tag">
    Track sessions with metadata for easier debugging and analytics
  </Card>

  <Card title="Idempotency keys" icon="rotate">
    Use idempotency keys when retrying failed requests to avoid duplicate sessions
  </Card>

  <Card title="Clean up" icon="trash">
    Delete sessions when done to free resources and reduce costs
  </Card>
</CardGroup>

## Limits

| Plan       | Concurrent Sessions | Max TTL  | Resource Overrides |
| ---------- | ------------------- | -------- | ------------------ |
| Free       | 10                  | 24 hours | No                 |
| Paid       | 100                 | 7 days   | Yes                |
| Enterprise | Custom              | Custom   | Yes                |

## Related Endpoints

<CardGroup cols={3}>
  <Card title="Get Session Info" icon="info" href="/api-reference/sessions/info">
    Retrieve session details
  </Card>

  <Card title="Delete Session" icon="trash" href="/api-reference/sessions/delete">
    Delete a session
  </Card>

  <Card title="Execute Code" icon="play" href="/api-reference/execution/execute">
    Run code in the session
  </Card>
</CardGroup>
