# Session TTL in ego-browser: How 2-Second CDP Caching Impacts Session Management

> Understand how ego-browser's 2-second session TTL impacts CDP session management. Learn how this short cache affects session reuse and recreation for smoother debugging.

- Repository: [CitroLabs/ego-lite](https://github.com/citrolabs/ego-lite)
- Tags: deep-dive
- Published: 2026-07-26

---

**The session TTL in ego-browser is hardcoded to 2 seconds (2000ms), determining whether the Chrome DevTools Protocol (CDP) session is reused or recreated based on elapsed time since the last recorded activity.**

In the `citrolabs/ego-lite` repository, `ego-browser` manages browser automation through ephemeral CDP connections. The **session TTL** (time-to-live) constant defined in [`src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/browser-runtime.ts) governs how long these sessions remain cached in the global state, creating a critical balance between execution performance and connection stability.

## How the Session TTL Mechanism Works

The TTL validation relies on a fixed constant of **2000 milliseconds** within the browser runtime. When automation helpers request a CDP session, the logic checks the global `state` object for two values: `state.sessionId` and `state.sessionAt`.

If `state.sessionId` exists and the elapsed time since `state.sessionAt` is less than 2000ms, the existing session is reused. If the elapsed time exceeds this threshold, the runtime invalidates the cached reference and instantiates a fresh CDP session, updating `state.sessionAt` with the current timestamp.

## Impact on CDP Session Management

The 2-second TTL creates distinct operational behaviors depending on your automation timing:

- **Rapid successive calls:** When operations like `click()` and `type()` execute within 2 seconds of each other, the cached CDP session persists. This eliminates repeated session handshakes, minimizing latency for tightly grouped commands.

- **Longer pauses between calls:** If your script delays execution beyond 2 seconds—such as a lengthy `wait()` followed by `navigate()`—the TTL expires. The system discards the stale session and establishes a new connection, preventing failures from timed-out browser sockets.

- **Browser or network disruptions:** The short TTL acts as a recovery mechanism. By forcing reconnection attempts every 2 seconds, `ego-browser` avoids retrying commands against potentially dead connections, improving robustness in unstable network environments.

## Practical Code Examples

The following patterns demonstrate how the TTL governs session behavior using helpers exported from [`src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/helpers.ts).

### Session Reuse Within the TTL Window

When commands execute within 2 seconds, they share the same underlying CDP connection:

```javascript
await click('#login-button');      // Creates new CDP session, sets state.sessionAt
await wait(1_000);                 // Wait 1s—still within TTL
await type('#username', 'alice');    // Reuses existing session (state.sessionId valid)

```

### TTL Expiration Triggering Recreation

Operations spaced beyond the threshold force a fresh session:

```javascript
await wait(3_000);                 // Wait 3s—exceeds 2000ms TTL
await navigate('https://example.com'); // Triggers new CDP session creation

```

### Manual Session Invalidation

To force a new session before the natural TTL expires—such as after a manual browser reset—clear the cached state directly:

```javascript
import { state } from 'ego-browser';   // Accesses global state from state.ts

state.sessionId = undefined;           // Invalidate cached identifier
state.sessionAt = 0;                   // Reset timestamp to force TTL failure
// Next helper call establishes a fresh CDP session

```

## Core Source Files

Understanding the TTL implementation requires examining these specific files in `citrolabs/ego-lite`:

- **[`src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/browser-runtime.ts)**: Contains the 2000ms TTL constant and implements the conditional logic for reusing versus recreating CDP sessions based on `state.sessionAt` timestamps.

- **[`src/state.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/state.ts)**: Defines the global `state` object that persists `sessionId` and `sessionAt` across helper invocations, enabling temporal session validation.

- **[`src/helpers.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/helpers.ts)**: Exposes the public automation API (`click`, `navigate`, `type`, etc.) that implicitly invokes the session management logic from [`browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/browser-runtime.ts).

## Summary

- **Session TTL is fixed at 2 seconds** (2000ms) in [`browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/browser-runtime.ts), creating a short-lived cache for CDP connections.
- **TTL expiration forces new session creation** when `Date.now() - state.sessionAt >= 2000`, preventing operations against stale connections.
- **Rapid automation benefits** from session reuse, eliminating handshake overhead for operations executed within the 2-second window.
- **Manual invalidation** is achieved by clearing `state.sessionId` and resetting `state.sessionAt`, useful for recovery after browser restarts.
- The mechanism optimizes for **both performance** (caching) and **resilience** (forced reconnection) in browser automation workflows.

## Frequently Asked Questions

### What is the exact duration of the session TTL in ego-browser?

The session TTL is hardcoded to **2000 milliseconds** (2 seconds) as defined in [`src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/browser-runtime.ts). This value represents the maximum age of a cached CDP session before the runtime mandates a fresh connection.

### How can I manually invalidate a cached CDP session before the TTL expires?

Import the global `state` object from `ego-browser` and clear its properties: set `state.sessionId` to `undefined` and `state.sessionAt` to `0`. This forces the next helper call to create a new CDP session regardless of the elapsed time.

### Why is the session TTL set to 2 seconds instead of a longer duration?

The 2-second TTL optimizes for browser automation stability over long-running scripts. CDP connections are susceptible to interruption from browser crashes, navigation events, or network issues. By forcing frequent reconnection attempts, `ego-browser` ensures that automation scripts recover automatically from transient failures within 2 seconds, rather than attempting to use a dead session that would cause command failures.

### Does session TTL affect the browser instance or only the CDP connection?

The session TTL affects only the **CDP protocol session** (the DevTools Protocol connection), not the underlying browser instance itself. The browser process may continue running, but the control channel (CDP session) is refreshed if the TTL expires between operations.