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:- Create or find a server
- Create or find a channel within that server
- Add agents to the channel
- Manage channel participants
- Handle channel lifecycle (creation, deletion, cleanup)
- Create a session with an agent
- Send messages
- (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
- Creation: Initialize session with configuration
- Active: Process messages and maintain state
- Near Expiration: Warning state before timeout
- Renewed: Lifetime extended (auto or manual)
- Expired: Session exceeded timeout
- Deleted: Explicit termination
- 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
-
Session Not Found (404)
- Session may have expired or been deleted
- Create a new session and retry
- Check session ID format
-
Session Expired (410)
- Session exceeded its timeout period
- Check the
expiresAt
timestamp in error details - Create a new session or adjust timeout configuration
-
Cannot Renew Session (422)
- Session has reached maximum duration limit
- Check
maxDurationMinutes
configuration - Must create a new session
-
Invalid Timeout Configuration (400)
- Timeout values outside allowed range (5-1440 minutes)
- Check configuration values against limits
- Adjust to valid ranges
-
Agent Not Available
- Ensure the agent is started and running
- Check agent logs for errors
- Verify agent ID is correct
Debugging
Enable debug logging: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:-
Session Store Distribution
- Use Redis for distributed session storage
- Implement session affinity for WebSocket connections
- Use consistent hashing for session distribution
-
Message Queue Integration
- Decouple message processing from API responses
- Use message queues for agent processing
- Implement async response patterns
-
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: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
Get Session Information
Retrieves detailed information about a session including its current status.GET /api/messaging/sessions/{sessionId}
Get session details and current status
404 Not Found
- Session does not exist410 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
400 Bad Request
- Invalid content or metadata404 Not Found
- Session not found410 Gone
- Session expired
Get Messages
Retrieves messages from a session with pagination support.GET /api/messaging/sessions/{sessionId}/messages
Retrieve conversation history
Renew Session
Manually renews a session to extend its expiration time.POST /api/messaging/sessions/{sessionId}/renew
Manually extend session lifetime
404 Not Found
- Session not found410 Gone
- Session expired422 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
SessionInfoResponse
Errors:
400 Bad Request
- Invalid timeout configuration404 Not Found
- Session not found410 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
SessionInfoResponse
with updated expiration information.
Errors:
404 Not Found
- Session not found410 Gone
- Session expired
Delete Session
Explicitly ends and removes a session.DELETE /api/messaging/sessions/{sessionId}
End and delete a session
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
Health Check
Checks the health status of the Sessions API service.GET /api/messaging/sessions/health
Check service health
Error Responses
All error responses follow a consistent format:Common Error Codes
Status Code | Error Type | Description |
---|---|---|
400 | Bad Request | Invalid input parameters or request body |
404 | Not Found | Session or resource not found |
410 | Gone | Session has expired |
422 | Unprocessable Entity | Operation cannot be completed (e.g., max duration reached) |
500 | Internal Server Error | Unexpected server error |
Error Classes
The API uses specific error classes for different scenarios:SessionNotFoundError
- Session does not existSessionExpiredError
- Session has exceeded its timeoutSessionCreationError
- Failed to create sessionAgentNotFoundError
- Specified agent not foundInvalidUuidError
- Invalid UUID formatMissingFieldsError
- Required fields missingInvalidContentError
- Message content validation failedInvalidMetadataError
- Metadata exceeds size limitInvalidPaginationError
- Invalid pagination parametersInvalidTimeoutConfigError
- Invalid timeout configurationSessionRenewalError
- Cannot renew sessionMessageSendError
- 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:Variable | Default | Description |
---|---|---|
SESSION_DEFAULT_TIMEOUT_MINUTES | 30 | Default session timeout |
SESSION_MIN_TIMEOUT_MINUTES | 5 | Minimum allowed timeout |
SESSION_MAX_TIMEOUT_MINUTES | 1440 | Maximum allowed timeout (24 hours) |
SESSION_MAX_DURATION_MINUTES | 720 | Maximum total session duration (12 hours) |
SESSION_WARNING_THRESHOLD_MINUTES | 5 | When to trigger expiration warning |
SESSION_CLEANUP_INTERVAL_MINUTES | 5 | How often to clean expired sessions |
CLEAR_SESSIONS_ON_SHUTDOWN | false | Clear all sessions on server shutdown |