# Understanding the 2-Second TTL for Ego-Lite Sessions

> Discover why ego-lite enforces a 2-second TTL for Chrome DevTools Protocol sessions. Learn how this setting optimizes caching and avoids repeated attachments in the citrolabs/ego-lite repository.

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

---

**Ego-lite uses a hard-coded 2-second TTL (time-to-live) defined as `SESSION_TTL_MS = 2000` in its browser runtime to cache Chrome DevTools Protocol sessions and avoid repeated attachments.**

The **2-second TTL for ego-lite sessions** controls how long the library reuses an existing Chrome DevTools Protocol (CDP) session before creating a new one. According to the citrolabs/ego-lite source code, this brief window balances performance optimization against the risk of stale connections. The implementation tracks session creation timestamps in milliseconds and validates them against a constant threshold defined in the browser runtime module.

## How the 2-Second TTL Works

When interacting with Chrome instances, ego-lite maintains a short-lived session cache to minimize redundant CDP attachments. The runtime stores the creation time in `state.sessionAt` and compares it against the current time on each request.

### Session Reuse Logic in browser-runtime.ts

The core validation occurs in [`src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/browser-runtime.ts). The code checks if `state.sessionId` exists and whether the elapsed time since `state.sessionAt` falls within the 2000-millisecond window:

```typescript
// Inside src/browser-runtime.ts
if (state.sessionId && Date.now() - state.sessionAt < SESSION_TTL_MS) {
  // Reuse the cached session
  return state.sessionId;
}

```

If the condition evaluates to true, the existing session ID returns immediately. If the TTL has expired or no session exists, the runtime falls back to creating a fresh connection.

### State Management

The runtime state persists in [`src/state.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/state.ts), which holds the `sessionId` string and `sessionAt` number timestamp. When a new session initializes, the runtime updates both values:

```typescript
// Fallback when TTL has passed or no session exists
const newSessionId = await createNewSession(); // implementation omitted
state.sessionId = newSessionId;
state.sessionAt = Date.now(); // reset timestamp

```

## Implementation Examples

The TTL check typically wraps inside helper functions that consumers call. Below is a complete usage pattern showing how the 2-second window operates in practice:

```typescript
async function ensureSession(): Promise<string> {
  // Triggers the TTL logic above
  return await getOrCreateSession(); // returns a valid session ID
}

```

This design ensures that rapid successive operations—such as multiple API calls occurring within milliseconds—reuse the same CDP session, while longer pauses trigger a fresh attachment to prevent stale handle errors.

## Performance vs. Reliability Trade-offs

The **2-second TTL for ego-lite sessions** represents a deliberate architectural choice. A shorter TTL would increase attachment overhead and slow down batch operations. A longer TTL risks attempting to reuse sessions that Chrome has already garbage collected or invalidated. The 2000-millisecond constant provides a buffer for typical async/await patterns and sequential function calls without keeping obsolete sessions alive.

## Summary

- **Constant location**: `SESSION_TTL_MS = 2000` is defined in [`src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/browser-runtime.ts)
- **Reuse condition**: `Date.now() - state.sessionAt < SESSION_TTL_MS` determines session validity
- **State storage**: `sessionId` and `sessionAt` are maintained in [`src/state.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/state.ts)
- **Purpose**: Prevents redundant CDP attachments while avoiding stale session errors

## Frequently Asked Questions

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

The TTL is exactly **2000 milliseconds** (2 seconds), defined as the constant `SESSION_TTL_MS` in the browser runtime module. This value is hard-coded and not configurable in the current implementation.

### Where does ego-lite check if a session is still valid?

The validation logic resides in [`src/browser-runtime.ts`](https://github.com/citrolabs/ego-lite/blob/main/src/browser-runtime.ts), specifically within the session retrieval function. The code compares the current timestamp against `state.sessionAt` to determine if the cached session remains within the 2-second window.

### How does ego-lite handle expired sessions?

When the TTL expires or no session exists, the runtime calls `createNewSession()` to establish a fresh Chrome DevTools Protocol connection. It then updates `state.sessionId` with the new identifier and resets `state.sessionAt` to the current timestamp using `Date.now()`.

### Why does ego-lite use such a short TTL instead of keeping sessions open longer?

The 2-second window prevents stale session errors that occur when Chrome invalidates CDP handles, while still allowing rapid successive operations to reuse connections. This balances reliability (avoiding invalid session errors) with performance (reducing attachment overhead for quick sequential calls).