Authkestra

Session Stores

Authkestra provides multiple session storage backends. Choose based on your deployment architecture and scaling requirements.

Authkestra provides multiple session storage backends. Choose based on your deployment architecture and scaling requirements.

Overview

StoreBest ForPersistenceScaling
In-MemoryDevelopment, testingNone (lost on restart)Single instance
RedisProduction, high trafficOptional (RDB/AOF)Multi-instance
SQLProduction, existing DBFull persistenceMulti-instance

SessionStore Trait

The SessionStore trait handles session persistence. Authkestra provides implementations for memory, Redis, and SQL databases.

authkestra-session/src/lib.rs
use async_trait::async_trait;
use authkestra_core::SameSite;
pub use authkestra_core::{error::AuthError, state::Identity};

/// Represents an active user session.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Session {
    /// Unique session identifier.
    pub id: String,
    /// The identity associated with this session.
    pub identity: Identity,
    /// When the session expires.
    pub expires_at: chrono::DateTime<chrono::Utc>,
}

/// Trait for implementing session persistence.
#[async_trait]
pub trait SessionStore: Send + Sync + 'static {
    /// Load a session by its ID.
    async fn load_session(&self, id: &str) -> Result<Option<Session>, AuthError>;
    /// Save or update a session.
    async fn save_session(&self, session: &Session) -> Result<(), AuthError>;
    /// Delete a session by its ID.
    async fn delete_session(&self, id: &str) -> Result<(), AuthError>;
}

Custom Session Stores

You can implement custom session stores for databases like MongoDB, DynamoDB, or any other storage backend by implementing this trait.

In-Memory Store

The default store for quick setup. Sessions are stored in memory and lost when the application restarts.

memory_store.rs
use authkestra_session::MemoryStore;

// Create an in-memory session store (default)
let store = MemoryStore::new();

let authkestra = Authkestra::builder()
    .provider(OAuth2Flow::new(provider))
    .session_store(store)
    .build();

Not for Production

In-memory store is not suitable for production. Sessions will be lost on restart, and it doesn't work in multi-instance deployments.

Redis Store

Redis is ideal for production deployments. It provides fast access, automatic expiration, and works across multiple application instances.

redis_store.rs
use authkestra_session::RedisStore;

// Connect to Redis
let store = RedisStore::new("redis://127.0.0.1:6379")
    .await
    .expect("Failed to connect to Redis");

let authkestra = Authkestra::builder()
    .provider(OAuth2Flow::new(provider))
    .session_store(store)
    .build();

Add the Redis feature to your dependencies:

Cargo.toml
[dependencies]
authkestra = { version = "0.1.2", features = ["axum", "github"]}
authkestra-session = { version = "0.1.2", features = ["redis"] }

Redis Configuration

In production, use Redis with authentication and TLS: redis://username:password@redis.example.com:6379/0

SQL Store

SQL storage is perfect when you already have a database and want sessions alongside your application data.

sql_store.rs
use authkestra_session::SqlStore;
use sqlx::sqlite::SqlitePool;

// Connect to SQLite (also supports PostgreSQL, MySQL)
let pool = SqlitePool::connect("sqlite::memory:").await?;

// Create the sessions table
sqlx::query(
    "CREATE TABLE IF NOT EXISTS sessions (
        id TEXT PRIMARY KEY,
        data TEXT NOT NULL,
        expires_at INTEGER NOT NULL
    )"
)
.execute(&pool)
.await?;

// Create the SQL store
let store = SqlStore::new(pool);

let authkestra = Authkestra::builder()
    .provider(OAuth2Flow::new(provider))
    .session_store(store)
    .build();
Cargo.toml
[dependencies]
authkestra = { version = "0.1.2", features = ["axum", "github"] }
authkestra-session = { version = "0.1.2", features = ["sqlite"] }
sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "sqlite"] }

Custom Store

You can implement the SessionStore trait for custom backends like MongoDB, DynamoDB, or any other storage system.

The best way to learn how to implement a custom store is to look at the source code of the existing implementations in the authkestra-session crate for guidance:

  • MemoryStore: A simple in-memory implementation.
  • RedisStore: An implementation using Redis with automatic expiration.
  • SqlStore: A persistent implementation for SQL databases using sqlx.

These implementations provide excellent references for handling session serialization, database connectivity, and error mapping while adhering to the SessionStore trait.

On this page