Skip to main content

CHUK Sessions provides a comprehensive, async-first session management system with automatic expiration, and support for both in-memory and Redis storage backends. Perfect for web applications, MCP servers, API gateways, and microservices that need reliable, scalable session handling.

Project description

CHUK Sessions

Simple, fast async session management for Python

Python 3.11+ License: Apache 2.0 Tests Coverage

Dead simple session management with automatic expiration, multiple storage backends, and multi-tenant isolation. Perfect for web apps, APIs, and any system needing reliable sessions.

๐Ÿ—๏ธ Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     Your Application                        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                  โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚   Convenience API Layer   โ”‚
                    โ”‚  get_session() / session  โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                  โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚     SessionManager        โ”‚
                    โ”‚  โ€ข Lifecycle Management   โ”‚
                    โ”‚  โ€ข TTL & Expiration       โ”‚
                    โ”‚  โ€ข Metadata & Validation  โ”‚
                    โ”‚  โ€ข Multi-tenant Isolation โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                  โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚    Provider Factory       โ”‚
                    โ”‚  Auto-detect from env     โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                  โ”‚
                โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                โ”‚                                   โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
    โ”‚  Memory Provider     โ”‚          โ”‚   Redis Provider     โ”‚
    โ”‚  โ€ข In-process cache  โ”‚          โ”‚  โ€ข Persistent store  โ”‚
    โ”‚  โ€ข 1.3M ops/sec      โ”‚          โ”‚  โ€ข Distributed       โ”‚
    โ”‚  โ€ข Dev/Testing       โ”‚          โ”‚  โ€ข Persistent store  โ”‚
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Features:
  โœ“ Pydantic models with validation    โœ“ Type-safe enums (no magic strings)
  โœ“ Automatic TTL expiration            โœ“ Multi-sandbox isolation
  โœ“ CSRF protection utilities           โœ“ Cryptographic session IDs
  โœ“ 202 tests, 90% coverage             โœ“ Battle-tested

๐Ÿš€ Quick Start

# Basic installation (memory provider only)
pip install chuk-sessions

# With Redis support
pip install chuk-sessions[redis]

# Full installation with all optional dependencies
pip install chuk-sessions[all]

# Development installation
pip install chuk-sessions[dev]
import asyncio
from chuk_sessions import get_session

async def main():
    async with get_session() as session:
        # Store with auto-expiration
        await session.setex("user:123", 3600, "Alice")  # 1 hour TTL
        
        # Retrieve
        user = await session.get("user:123")  # "Alice"
        
        # Automatically expires after TTL
        
asyncio.run(main())

That's it! Sessions automatically expire and you get instant performance.

๐Ÿ“– How It Works

Session Lifecycle:
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 1. Create   โ”‚  mgr.allocate_session(user_id="alice")
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ”‚ โ† Returns session_id: "sess-alice-1234..."
       โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 2. Validate โ”‚  mgr.validate_session(session_id)
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ”‚ โ† Returns: True (session exists & not expired)
       โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 3. Use      โ”‚  mgr.get_session_info(session_id)
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜  mgr.update_session_metadata(...)
       โ”‚ โ† Access/modify session data
       โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 4. Extend   โ”‚  mgr.extend_session_ttl(session_id, hours=2)
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜  (optional - keep session alive)
       โ”‚
       โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ 5. Expire   โ”‚  Automatic after TTL
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜  or mgr.delete_session(session_id)
       โ”‚
       โ–ผ
    [Done]

โœจ What's New in v0.6

  • ๐ŸŽฏ Pydantic Native: All models are Pydantic-based with automatic validation
  • ๐Ÿ”’ Type-Safe Enums: No more magic strings - SessionStatus.ACTIVE, ProviderType.REDIS
  • ๐Ÿ“ฆ Exported Types: Full IDE autocomplete for SessionMetadata, CSRFTokenInfo, etc.
  • โšก Async Native: Built from ground-up for async/await
  • ๐Ÿ”„ Backward Compatible: Existing code works unchanged
  • ๐Ÿ—‚๏ธ Bounded LRU Cache: In-process session cache is capped at 1024 entries (evicts LRU) โ€” no unbounded memory growth
  • โœ… 90%+ Test Coverage: 264 tests, battle-tested
from chuk_sessions import SessionManager, SessionStatus, SessionMetadata

# Type-safe with IDE autocomplete
mgr = SessionManager(sandbox_id="my-app")
session_id = await mgr.allocate_session()

# Pydantic models with validation
info: dict = await mgr.get_session_info(session_id)
metadata = SessionMetadata(**info)
print(metadata.status)  # SessionStatus.ACTIVE

โšก Major Features

๐ŸŽฏ Simple Storage with TTL

from chuk_sessions import get_session

async with get_session() as session:
    await session.set("key", "value")              # Default 1hr expiration
    await session.setex("temp", 60, "expires")     # Custom 60s expiration
    value = await session.get("key")               # Auto-cleanup when expired

๐Ÿข Multi-App Session Management

from chuk_sessions import SessionManager

# Each app gets isolated sessions
web_app = SessionManager(sandbox_id="web-portal")
api_service = SessionManager(sandbox_id="api-gateway")

# Full session lifecycle
session_id = await web_app.allocate_session(
    user_id="alice@example.com",
    custom_metadata={"role": "admin", "login_time": "2024-01-01T10:00:00Z"}
)

# Validate, extend, update
await web_app.validate_session(session_id)
await web_app.extend_session_ttl(session_id, additional_hours=2)
await web_app.update_session_metadata(session_id, {"last_activity": "now"})

โš™๏ธ Multiple Backends

# Development - blazing fast in-memory (default)
export SESSION_PROVIDER=memory

# Persistent - Redis standalone (requires chuk-sessions[redis])
export SESSION_PROVIDER=redis
export SESSION_REDIS_URL=redis://localhost:6379/0

# Persistent - Redis Cluster with automatic detection
export SESSION_PROVIDER=redis
export SESSION_REDIS_URL=redis://node1:7000,node2:7001,node3:7002

๐Ÿ“Š Performance (Real Benchmarks)

Actual performance from examples/performance_test.py:

Provider Operation Throughput Avg Latency P95 Latency
Memory GET 1,312,481 ops/sec 0.001ms 0.001ms
Memory SET 1,141,011 ops/sec 0.001ms 0.001ms
Memory DELETE 1,481,848 ops/sec 0.001ms 0.001ms
Redis GET ~20K ops/sec 0.05ms 0.08ms
Redis SET ~18K ops/sec 0.06ms 0.09ms

Concurrent Access (5 sessions, 500 ops):

  • Overall Throughput: 406,642 ops/sec
  • Average Latency: 0.002ms

๐Ÿ’ก Real-World Use Cases

Based on examples/chuk_session_example.py:

๐ŸŒ Web App Sessions

web_app = SessionManager(sandbox_id="my-web-app")

# Login
session_id = await web_app.allocate_session(
    user_id="alice@example.com",
    ttl_hours=8,
    custom_metadata={"role": "admin", "theme": "dark"}
)

# Middleware validation
if not await web_app.validate_session(session_id):
    raise Unauthorized("Please log in")

API Rate Limiting

api = SessionManager(sandbox_id="api-gateway", default_ttl_hours=1)

session_id = await api.allocate_session(
    user_id="client_123",
    custom_metadata={"tier": "premium", "requests": 0, "limit": 1000}
)

# Check/update rate limits
info = await api.get_session_info(session_id)
requests = info['custom_metadata']['requests']
if requests >= info['custom_metadata']['limit']:
    raise RateLimitExceeded()

await api.update_session_metadata(session_id, {"requests": requests + 1})

Temporary Verification Codes

from chuk_sessions import get_session

async with get_session() as session:
    # Email verification code (10 minute expiry)
    await session.setex(f"verify:{email}", 600, "ABC123")
    
    # Later: verify and consume
    code = await session.get(f"verify:{email}")
    if code == user_code:
        await session.delete(f"verify:{email}")  # One-time use
        return True

๐Ÿ”ง Configuration

Set via environment variables:

# Provider selection
export SESSION_PROVIDER=memory          # Default - no extra dependencies
export SESSION_PROVIDER=redis           # Requires: pip install chuk-sessions[redis]

# TTL settings
export SESSION_DEFAULT_TTL=3600         # 1 hour default

# Redis config (if using redis provider)
# Standalone Redis
export SESSION_REDIS_URL=redis://localhost:6379/0

# Redis Cluster (comma-separated hosts - automatically detected)
export SESSION_REDIS_URL=redis://node1:7000,node2:7001,node3:7002

# Redis with TLS
export SESSION_REDIS_URL=rediss://localhost:6380/0
export REDIS_TLS_INSECURE=1             # Set to 1 to skip certificate verification (dev only)

๐Ÿ“ฆ Installation Options

Command Includes Use Case
pip install chuk-sessions Memory provider only Development, testing, lightweight apps
pip install chuk-sessions[redis] + Redis support Persistent apps with Redis
pip install chuk-sessions[all] All optional features Maximum compatibility
pip install chuk-sessions[dev] Development tools Contributing, testing

๐Ÿ“– API Reference

Low-Level API

from chuk_sessions import get_session

async with get_session() as session:
    await session.set(key, value)           # Store with default TTL
    await session.setex(key, ttl, value)    # Store with custom TTL (seconds)
    value = await session.get(key)          # Retrieve (None if expired)
    deleted = await session.delete(key)     # Delete (returns bool)

SessionManager API

from chuk_sessions import SessionManager

mgr = SessionManager(sandbox_id="my-app", default_ttl_hours=24)

# Session lifecycle
session_id = await mgr.allocate_session(user_id="alice", custom_metadata={})
is_valid = await mgr.validate_session(session_id)
info = await mgr.get_session_info(session_id)
success = await mgr.update_session_metadata(session_id, {"key": "value"})
success = await mgr.extend_session_ttl(session_id, additional_hours=2)
success = await mgr.delete_session(session_id)

# Admin helpers
stats = mgr.get_cache_stats()
cleaned = await mgr.cleanup_expired_sessions()

๐ŸŽช Examples & Demos

All examples are tested and working! Run them to see CHUK Sessions in action:

๐Ÿš€ Getting Started

# Simple 3-line example - perfect first step
python examples/simple_example.py

# Interactive tutorial with explanations
python examples/quickstart.py

Output:

User: Alice
Token: secret123
Missing: None

๐Ÿ”ง Comprehensive Demo

# Complete feature demonstration
python examples/chuk_session_example.py

Shows:

  • โœ“ Low-level provider usage (memory/redis)
  • โœ“ High-level SessionManager API
  • โœ“ Multi-sandbox isolation (multi-tenant)
  • โœ“ Real-world scenarios (web app, MCP server, API gateway)
  • โœ“ Error handling & admin helpers

๐Ÿ“Š Performance Testing

# Benchmark your system
python examples/performance_test.py

Output includes:

  • Throughput measurements (1.3M+ ops/sec)
  • Latency percentiles (P50, P95, P99)
  • Memory usage analysis
  • Concurrent access tests
  • README-ready performance tables

๐Ÿ” Security Demos

# CSRF protection examples
python examples/csrf_demo.py

# Secure session ID generation
python examples/session_id_demo.py

Features demonstrated:

  • HMAC-based CSRF tokens
  • Double-submit cookie pattern
  • Encrypted stateless tokens
  • Cryptographic session IDs with entropy analysis
  • Protocol-specific formats (MCP, HTTP, WebSocket, JWT)

๐Ÿ—๏ธ Why CHUK Sessions?

  • Simple: One import, one line to start storing sessions
  • Fast: 1.8M ops/sec in memory, 20K ops/sec with Redis
  • Reliable: Automatic TTL, proper error handling, battle-tested
  • Flexible: Works for simple key-value storage or complex session management
  • Isolated: Multi-tenant by design with sandbox separation
  • Optional Dependencies: Install only what you need

Perfect for web frameworks, API servers, MCP implementations, or any Python app needing sessions.

๐Ÿ› ๏ธ Development

# Clone and install dependencies
git clone https://github.com/chrishayuk/chuk-sessions.git
cd chuk-sessions
make dev-install

# Run tests
make test

# Run tests with coverage (90%+ coverage)
make test-cov

# Run all checks (lint, typecheck, security, tests)
make check

# Format code
make format

# Build package
make build

๐Ÿš€ Release Process

# Bump version
make bump-patch  # 0.5 โ†’ 0.6
make bump-minor  # 0.5 โ†’ 1.0
make bump-major  # 0.5 โ†’ 1.0.0

# Create release (triggers GitHub Actions โ†’ PyPI)
make publish

Available Makefile Commands

  • make test - Run tests
  • make test-cov - Run tests with coverage report
  • make lint - Run code linters (ruff)
  • make format - Auto-format code
  • make typecheck - Run type checking (mypy)
  • make security - Run security checks (bandit)
  • make check - Run all checks
  • make clean - Clean build artifacts
  • make build - Build distribution packages
  • make publish - Create tag and trigger automated release

See make help for all available commands.

๐Ÿ“„ License

Apache 2.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chuk_sessions-0.6.2.tar.gz (44.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chuk_sessions-0.6.2-py3-none-any.whl (37.1 kB view details)

Uploaded Python 3

File details

Details for the file chuk_sessions-0.6.2.tar.gz.

File metadata

  • Download URL: chuk_sessions-0.6.2.tar.gz
  • Upload date:
  • Size: 44.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.11

File hashes

Hashes for chuk_sessions-0.6.2.tar.gz
Algorithm Hash digest
SHA256 8b41a59293023b9ea65a539b02e6f5860f91ca40cacf695ff1290a90f3a80b9d
MD5 55e137108613238f8ad3845afb0ee1e3
BLAKE2b-256 ef47ea4e1afbb969e6b8162fd1a7e04ccaba4d2a4bd803d21a348376c884cab0

See more details on using hashes here.

File details

Details for the file chuk_sessions-0.6.2-py3-none-any.whl.

File metadata

  • Download URL: chuk_sessions-0.6.2-py3-none-any.whl
  • Upload date:
  • Size: 37.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.11

File hashes

Hashes for chuk_sessions-0.6.2-py3-none-any.whl
Algorithm Hash digest
SHA256 1d33a17754d63b0966c4673058bb7cc50dbd2e48d81cbf93b3c7c51ff50d07f0
MD5 c39b60ff9c1d553e4d79c477b52a8612
BLAKE2b-256 c5cfcf13a453217bb01bc6151c6330ae949d31d8e211779a0d7b66c09ee4e3b8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page