Skip to main content

Overview

The Sessions API provides a sophisticated abstraction layer over the traditional messaging infrastructure, enabling persistent, stateful conversations with automatic timeout management and renewal capabilities.

Why Use Sessions?

The Sessions API eliminates the complexity of channel management. Traditional messaging approaches require you to:
  1. Create or find a server
  2. Create or find a channel within that server
  3. Add agents to the channel
  4. Manage channel participants
  5. Handle channel lifecycle (creation, deletion, cleanup)
With Sessions API, you simply:
  1. Create a session with an agent
  2. Send messages
  3. (Optional) Configure timeout and renewal policies

Key Features

  • Zero Channel Management: No need to create servers, channels, or manage participants
  • Instant Setup: Start conversations immediately with just agent and user IDs
  • Automatic Timeout Management: Sessions automatically expire after periods of inactivity
  • Session Renewal: Support for both automatic and manual session renewal
  • Expiration Warnings: Get notified when sessions are about to expire
  • Configurable Policies: Customize timeout, renewal, and duration limits per session or agent
  • Resource Optimization: Automatic cleanup of expired sessions to prevent memory leaks
  • Persistent Conversations: Maintain chat history and context across multiple messages
  • State Management: Track conversation stage, renewal count, and expiration status
  • Multi-Platform Support: Works across different platforms with metadata support

Sessions Architecture

Core Design Principles

Abstraction Over Complexity

The Sessions API abstracts away channel and server management complexity:

State Management

Sessions maintain state across multiple dimensions:

Session Lifecycle

Lifecycle Phases

  1. Creation: Initialize session with configuration
  2. Active: Process messages and maintain state
  3. Near Expiration: Warning state before timeout
  4. Renewed: Lifetime extended (auto or manual)
  5. Expired: Session exceeded timeout
  6. Deleted: Explicit termination
  7. Cleanup: Resource cleanup

Timeout Configuration

Configuration Interface

Configuration Hierarchy

Configuration follows a three-tier precedence:

Environment Variables

Global default configuration:
  • SESSION_DEFAULT_TIMEOUT_MINUTES (default: 30)
  • SESSION_MIN_TIMEOUT_MINUTES (default: 5)
  • SESSION_MAX_TIMEOUT_MINUTES (default: 1440)
  • SESSION_MAX_DURATION_MINUTES (default: 720)
  • SESSION_WARNING_THRESHOLD_MINUTES (default: 5)

Quick Start

Complete Example: Chat Application

Session Creation

Creation Process

Session Operations

Send Messages

Retrieve Message History

Manual Session Renewal

Update Timeout Configuration

Active Session Management

Message Handling

Renewal Mechanism

Renewal Engine

Heartbeat Strategy

Session Store

In-Memory Storage

Cleanup Service

Automatic Cleanup

Integration Examples

React Hook with Session Management

WebSocket Integration

Handling Session Expiration

Error Handling

Custom Error Classes

Error Handling Examples

Performance Optimization

Pagination Strategy

Configuration Caching

Memory Management

Memory Leak Prevention

Cache with TTL

Troubleshooting

Common Issues

  1. Session Not Found (404)
    • Session may have expired or been deleted
    • Create a new session and retry
    • Check session ID format
  2. Session Expired (410)
    • Session exceeded its timeout period
    • Check the expiresAt timestamp in error details
    • Create a new session or adjust timeout configuration
  3. Cannot Renew Session (422)
    • Session has reached maximum duration limit
    • Check maxDurationMinutes configuration
    • Must create a new session
  4. Invalid Timeout Configuration (400)
    • Timeout values outside allowed range (5-1440 minutes)
    • Check configuration values against limits
    • Adjust to valid ranges
  5. Agent Not Available
    • Ensure the agent is started and running
    • Check agent logs for errors
    • Verify agent ID is correct

Debugging

Enable debug logging:
Check session cleanup logs:

When to Use Sessions vs Traditional Messaging

Use Sessions When:

  • Building chat interfaces: Web apps, mobile apps, or any UI with a chat component
  • Direct user-to-agent conversations: One-on-one interactions between a user and an agent
  • Simplified integration: You want to get up and running quickly without infrastructure complexity
  • Stateful conversations: You need the agent to maintain context throughout the conversation
  • Session management required: You need timeout, renewal, and expiration handling
  • Resource optimization: You want automatic cleanup of inactive conversations
  • Personal assistants: Building AI assistants that remember user preferences and conversation history

Use Traditional Messaging When:

  • Multi-agent coordination: Multiple agents need to communicate in the same channel
  • Group conversations: Multiple users and agents interacting together
  • Platform integrations: Integrating with Discord, Slack, or other platforms that have their own channel concepts
  • Broadcast scenarios: One agent sending messages to multiple channels/users
  • Complex routing: Custom message routing logic between different channels and servers
  • Permanent history: You need conversations to persist indefinitely without timeout

Scalability Considerations

Horizontal Scaling

For production deployments:
  1. Session Store Distribution
    • Use Redis for distributed session storage
    • Implement session affinity for WebSocket connections
    • Use consistent hashing for session distribution
  2. Message Queue Integration
    • Decouple message processing from API responses
    • Use message queues for agent processing
    • Implement async response patterns
  3. Database Optimization
    • Index session-related columns
    • Implement connection pooling
    • Consider read replicas for message retrieval

Monitoring Metrics

Security Considerations

Input Validation

Rate Limiting

Best Practices

Session Design

  • Appropriate Timeouts: Choose timeouts based on use case
  • Auto-Renewal: Enable for active conversations
  • Max Duration: Set limits to prevent infinite sessions
  • Warning Handling: Notify users before expiration
  • Cleanup Strategy: Regular cleanup of expired sessions

Implementation

  • Error Recovery: Graceful handling of session loss
  • State Persistence: Consider persistent storage for production
  • Monitoring: Track session metrics and health
  • Testing: Test timeout and renewal scenarios
  • Documentation: Document session behavior clearly

Agent Configuration

Configure timeout defaults for specific agents via environment variables:
Or configure programmatically in the agent:

Complete API Reference

The Sessions API provides a comprehensive set of endpoints for managing stateful conversations with ElizaOS agents. This reference covers all available endpoints, request/response schemas, and error handling.

Base URL

Authentication

Currently, the Sessions API does not require authentication. In production environments, you should implement appropriate authentication mechanisms.

Endpoints

Create Session

Creates a new conversation session with an agent.

POST /api/messaging/sessions

Create a new session with configurable timeout policies
Request Body:
Response (201 Created):
Example:

Get Session Information

Retrieves detailed information about a session including its current status.

GET /api/messaging/sessions/{sessionId}

Get session details and current status
Response (200 OK):
Errors:
  • 404 Not Found - Session does not exist
  • 410 Gone - Session has expired

Send Message

Sends a message within a session. Automatically renews the session if auto-renewal is enabled.

POST /api/messaging/sessions/{sessionId}/messages

Send a message in the conversation
Request Body:
Response (201 Created):
Errors:
  • 400 Bad Request - Invalid content or metadata
  • 404 Not Found - Session not found
  • 410 Gone - Session expired

Get Messages

Retrieves messages from a session with pagination support.

GET /api/messaging/sessions/{sessionId}/messages

Retrieve conversation history
Query Parameters:
Response (200 OK):

Renew Session

Manually renews a session to extend its expiration time.

POST /api/messaging/sessions/{sessionId}/renew

Manually extend session lifetime
Response (200 OK):
Errors:
  • 404 Not Found - Session not found
  • 410 Gone - Session expired
  • 422 Unprocessable Entity - Cannot renew (max duration reached)

Update Timeout Configuration

Updates the timeout configuration for an active session.

PATCH /api/messaging/sessions/{sessionId}/timeout

Modify session timeout settings
Request Body:
Response (200 OK): Returns updated SessionInfoResponse Errors:
  • 400 Bad Request - Invalid timeout configuration
  • 404 Not Found - Session not found
  • 410 Gone - Session expired

Send Heartbeat

Keeps a session alive and optionally renews it if auto-renewal is enabled.

POST /api/messaging/sessions/{sessionId}/heartbeat

Keep session alive with periodic heartbeat
Response (200 OK): Returns SessionInfoResponse with updated expiration information. Errors:
  • 404 Not Found - Session not found
  • 410 Gone - Session expired

Delete Session

Explicitly ends and removes a session.

DELETE /api/messaging/sessions/{sessionId}

End and delete a session
Response (200 OK):
Errors:
  • 404 Not Found - Session not found

List Sessions (Admin)

Lists all active sessions in the system. This is an administrative endpoint.

GET /api/messaging/sessions

List all active sessions
Response (200 OK):

Health Check

Checks the health status of the Sessions API service.

GET /api/messaging/sessions/health

Check service health
Response (200 OK):

Error Responses

All error responses follow a consistent format:

Common Error Codes

Error Classes

The API uses specific error classes for different scenarios:
  • SessionNotFoundError - Session does not exist
  • SessionExpiredError - Session has exceeded its timeout
  • SessionCreationError - Failed to create session
  • AgentNotFoundError - Specified agent not found
  • InvalidUuidError - Invalid UUID format
  • MissingFieldsError - Required fields missing
  • InvalidContentError - Message content validation failed
  • InvalidMetadataError - Metadata exceeds size limit
  • InvalidPaginationError - Invalid pagination parameters
  • InvalidTimeoutConfigError - Invalid timeout configuration
  • SessionRenewalError - Cannot renew session
  • MessageSendError - Failed to send message

Rate Limiting

Currently, the Sessions API does not implement rate limiting. In production, you should implement appropriate rate limiting based on your requirements.

WebSocket Events

When using WebSocket connections alongside the Sessions API, the following events are available:

Environment Variables

Configure the Sessions API behavior using these environment variables:

SDK Examples

JavaScript/TypeScript Client

Python Client

See Also

WebSocket Integration

Add real-time capabilities to your sessions

Core Concepts

Understand ElizaOS runtime architecture

Create a Plugin

Build custom plugins for your agents

Plugin Architecture

Build plugins that extend sessions