Skip to content

Long sessions

Keep sessions running longer and survive disconnects with keep alive and custom timeouts

Updated View as Markdown

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 “I need my session to run longer than the default”
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:

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

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:

const browsers = new Browsers({ apiKey: process.env.AGENTMQ_TOKEN! });
const session = await browsers.sessions.create({
  keepAlive: true,
});
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:

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",
  });
})();
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));
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")
# 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())

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.

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,
  });
})();
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));
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
)
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.

Navigation

Type to search…

↑↓ navigate↵ selectEsc close