Litestar Database and Server Sessions#
This guide covers two distinct session layers in Litestar:
Database sessions: Per-request SQLAlchemy
SessionorAsyncSessioninstances used by repositories and services.Server-side HTTP sessions and key-value stores: Persisting Litestar server-side session payloads and store entries in a SQL table instead of Redis.
Per-Request Database Sessions#
When SQLAlchemyPlugin is registered, Litestar injects a database session under the db_session parameter name. Control transaction commits by setting before_send_handler on your config:
"autocommit"commits automatically when a route returns a2xxresponse and rolls back on errors."autocommit_include_redirects"also commits when a route returns a3xxredirect (such as after HTML form submissions).
Outside an HTTP request (such as in a startup hook or background task), open a session directly with async with config.get_session() as db_session:.
Connecting Multiple Databases#
To configure multiple databases in one Litestar application, pass a list of configs with unique session_dependency_key, engine_dependency_key, and bind_key names:
from advanced_alchemy.extensions.litestar import SQLAlchemyAsyncConfig, SQLAlchemyPlugin
primary_config = SQLAlchemyAsyncConfig(
connection_string="sqlite+aiosqlite:///:memory:",
session_dependency_key="primary_session",
engine_dependency_key="primary_engine",
bind_key="primary",
)
analytics_config = SQLAlchemyAsyncConfig(
connection_string="sqlite+aiosqlite:///:memory:",
session_dependency_key="analytics_session",
engine_dependency_key="analytics_engine",
bind_key="analytics",
)
plugin = SQLAlchemyPlugin(config=[primary_config, analytics_config])
Storing User Sessions in Your Database#
Persist server-side session payloads, rate-limit counters, or general key-value entries in SQL using SQLAlchemyStore or SQLAlchemyAsyncSessionBackend:
class AppStoreModel(StoreModelMixin):
"""Database table backing Litestar's server-side session store."""
__tablename__ = "litestar_app_store"
@post(path="/session/{key:str}/{value:str}")
async def set_session_value(
key: FromPath[str],
value: FromPath[str],
request: Request[Any, Any, Any],
) -> dict[str, str]:
"""Store a key-value pair in the server-side session."""
request.session[key] = value
return {"key": key, "value": value}
@get(path="/session/{key:str}")
async def get_session_value(
key: FromPath[str],
request: Request[Any, Any, Any],
) -> dict[str, Optional[str]]:
"""Read a key-value pair from the server-side session."""
return {"key": key, "value": request.session.get(key)}
def create_app(db_path: Path, storage_dir: Path) -> Litestar:
"""Create a Litestar application configured with SQLAlchemyStore and StoredObject."""
storages.register_backend(f"file://{storage_dir}", key="litestar_docs_fs")
alchemy_config = SQLAlchemyAsyncConfig(
connection_string=f"sqlite+aiosqlite:///{db_path}",
create_all=True,
)
session_store = SQLAlchemyStore(config=alchemy_config, model=AppStoreModel)
session_config = ServerSideSessionConfig(store="sessions")
return Litestar(
route_handlers=[set_session_value, get_session_value, upload_attachment],
plugins=[SQLAlchemyPlugin(config=alchemy_config)],
middleware=[session_config.middleware],
stores=StoreRegistry(stores={"sessions": session_store}),
)
from advanced_alchemy.extensions.litestar.session import (
SQLAlchemyAsyncSessionBackend,
SessionModelMixin,
)
class UserSessionModel(SessionModelMixin):
__tablename__ = "litestar_user_sessions"
assert issubclass(UserSessionModel, SessionModelMixin)
assert SQLAlchemyAsyncSessionBackend is not None
Both backends use native database upserts and expose delete_expired() for removing expired rows from scheduled jobs or lifecycle hooks.