---
title: "Long sessions"
description: "Keep sessions running longer and survive disconnects with keep alive and custom timeouts"
image: "https://help.agent.mq/og.svg"
---

> Documentation Index
> Fetch the complete documentation index at: https://help.agent.mq/llms.txt
> Use this file to discover all available pages before exploring further.

# Long sessions

- **Keep Alive** — [Keep sessions available after disconnects so you can reconnect without starting over.](/browsers/long-sessions/keep-alive)

- **Timeout** — [Extend session duration beyond the default timeout for long-running tasks.](/browsers/long-sessions/timeouts)

By default, Browsers sessions automatically terminate in two scenarios:

1. When a session disconnects
2. When the session reaches its timeout

This behavior optimizes resource utilization and session management, but you may need sessions that run longer or survive disconnections.

Browsers offers session keep alive and custom timeout to address this need.

## Two ways to extend sessions

| Feature                                                          | Problem it solves                                              |
| ---------------------------------------------------------------- | -------------------------------------------------------------- |
| [**Session Timeouts**](/browsers/long-sessions/timeouts) | "I need my session to run longer than the default"             |
| [**Keep Alive**](/browsers/long-sessions/keep-alive)     | "I need to disconnect and reconnect without ending my session" |

### When to use each

**Timeouts** extend how long a session can run before it automatically terminates. Use this when you have long-running tasks that exceed the default timeout.

**Keep Alive** lets you disconnect and reconnect to the same session. Use this when your workflow involves multiple connections, when you need resilience against network issues, or when you want to reuse the same session for multiple runs.

### Using both together

If you need a session that both survives disconnects and runs for an extended period, configure both options:

```typescript
const session = await browsers.sessions.create({
  keepAlive: true,
  timeout: 3600, // 1 hour
});
```

> **Note**
>
> Session keep alive is only available on plans that include it.

## Why keep sessions alive?

Custom timeouts and session keep alive support a broad spectrum of use cases. Key benefits include:

* Avoid interrupting long-running tasks and workflows.
* Connect, disconnect, and reconnect to the same session.
* Keep working with a session without worrying about it timing out.
* Reusing existing sessions is more performant than creating new ones.

## Keep alive sessions

The `keepAlive` feature allows you to keep sessions alive across disconnects, permitting you to continue using it as long as needed.

### Create a keep alive session

Setting `keepAlive` to `true` will keep the session available for later use. You can reconnect to the keep alive session using the same connection URL as the original session.

Here's an example of how to keep a session alive:

### Node.js

```typescript SDK
const browsers = new Browsers({ apiKey: process.env.AGENTMQ_TOKEN! });
const session = await browsers.sessions.create({
  keepAlive: true,
});
```

### Python

```python SDK
browsers = Browsers(api_key=os.environ["AGENTMQ_TOKEN"])
session = browsers.sessions.create(
  keep_alive=True
)
```

Next time you run the script, you can reconnect to the same session after a disconnect, reusing it for multiple runs.

### Stop a keep alive session

To stop the session, use the Browsers API or SDK:

### Node.js

```typescript SDK
  import Browsers from "agentmq";

  const AGENTMQ_TOKEN = process.env.AGENTMQ_TOKEN!;

  const browsers = new Browsers({
    apiKey: AGENTMQ_TOKEN,
  });

  // Create a session with keep alive set.
  // Then, end it by closing it.
  (async () => {
    const session = await browsers.sessions.create({
      keepAlive: true,
    });

    await browsers.sessions.update(session.id, {
      status: "REQUEST_RELEASE",
    });
  })();
```

```typescript API
  const options = {
    method: "POST",
    headers: {
      "Authorization: Bearer": "<your-api-key>",
      "Content-Type": "application/json",
    },
    body: '{"keepAlive": true, "sessionId": "<your-session-id>", "status": "REQUEST_RELEASE"}',
  };

  fetch("https://api.agent.mq/v1/browsers/sessions", options)
    .then((response) => response.json())
    .then((response) => console.log(response))
    .catch((err) => console.error(err));
```

### Python

```python SDK
  from agentmq.browsers import Browsers
  import os

  # Initialize the SDK
  AGENTMQ_TOKEN = os.environ["AGENTMQ_TOKEN"]

  browsers = Browsers(api_key=AGENTMQ_TOKEN)

  # Create a session with keep alive set

  session = browsers.sessions.create(keep_alive=True)

  # Manually complete the session to end it

  browsers.sessions.update(session.id, status="REQUEST_RELEASE")
```

```python API
  # Stop a session
  import os
  from pprint import pprint

  import requests

  API_KEY = os.environ["AGENTMQ_TOKEN"]

  SESSION_ID = "<The id of the session to stop>"

  headers = {"Authorization": API_KEY}
  json = {
      "status": "REQUEST_RELEASE",
  }

  response = requests.post(
      f"https://api.agent.mq/v1/browsers/sessions/{SESSION_ID}",
      json=json,
      headers=headers,
  )

  # Raise an exception if there wasn't a good response from the endpoint.
  response.raise_for_status()

  # print the response
  pprint(response.json())
```

> **Note**
>
> Stop your keep alive sessions explicitly when no longer
> needed. They'll time out eventually, but you may be charged for the unneeded
> browser minutes.

## Session timeouts

After the script exceeds the default timeout, you'll see a `TimeoutError`: `Timeout _____ms exceeded`

Browsers has application-wide settings for session timeout. You can change the session timeout to a different value in the toggle.

### Custom session timeout

You can also set a custom timeout for a created session through code.

If you'd like to set a custom timeout that isn't shown in the toggle, set it in the `createSession` function.

To set a custom timeout for your session, specify the `timeout` option in the API request body or
with the SDK.

### Node.js

```typescript SDK
  import Browsers from "agentmq";

  const AGENTMQ_TOKEN = process.env.AGENTMQ_TOKEN!;

  const browsers = new Browsers({
    apiKey: AGENTMQ_TOKEN,
  });

  // Creates a session with a timeout of 3600 seconds
  (async () => {
    const session = await browsers.sessions.create({
      timeout: 3600,
    });
  })();
```

```typescript API
  const options = {
    method: "POST",
    headers: {
      "Authorization: Bearer": "<your-api-key>",
      "Content-Type": "application/json",
    },
    body: '{"timeout": 3600}',
  };

  fetch("https://api.agent.mq/v1/browsers/sessions", options)
    .then((response) => response.json())
    .then((response) => console.log(response))
    .catch((err) => console.error(err));
```

### Python

```python SDK
  from agentmq.browsers import Browsers
  import os

  AGENTMQ_TOKEN = os.environ["AGENTMQ_TOKEN"]

  browsers = Browsers(
      api_key=AGENTMQ_TOKEN,
  )

  # Creates a session with a timeout of 3600 seconds
  session = browsers.sessions.create(
      api_timeout=3600
  )
```

```python API
  import os
  from pprint import pprint

  import requests

  AGENTMQ_TOKEN = os.environ["AGENTMQ_TOKEN"]

  headers = {"Authorization": AGENTMQ_TOKEN}
  json = {
      "api_timeout": 3600,
  }

  response = requests.post(
      "https://api.agent.mq/v1/browsers/sessions", json=json, headers=headers
  )

  # Raise an exception if there wasn't a good response from the endpoint.
  response.raise_for_status()

  # print the response
  pprint(response.json())
```

Here the timeout has been set to 3600 seconds (1 hour), overriding the default. That means
that unless explicitly closed beforehand, the session will continue running for an hour before
terminating. At disconnect, it will end.

Setting a custom timeout won't keep the session alive after disconnecting. To reconnect
to a session after disconnecting, configure it for keep alive.

> **Note**
>
> The maximum duration of a session is 6 hours. Once a session times out, it can
> no longer be used.

## Related guides

- **Session timeouts** — [Extend session duration beyond the default](/browsers/long-sessions/timeouts)

- **Keep alive** — [Survive disconnects and reconnect to sessions](/browsers/long-sessions/keep-alive)

- **Session inspector** — [Watch your session in real time and debug issues after the session has ended](/browsers/observability/observability)

Source: https://help.agent.mq/browsers/long-sessions/overview/index.mdx
