Multiple sessions
The Python SDK supports creating multiple isolated sessions within a single WebSocket connection. Each session maintains its own namespace, database, and authentication state, allowing you to perform independent operations without opening additional connections.
This page covers how to create sessions, isolate their scope, authenticate independently, and close them when no longer needed.
Note
API References
| Method | Description |
|---|---|
db.new_session() | Creates a new isolated session on the current connection |
session.close_session() | Closes the session and detaches it from the connection |
session.use(namespace, database) | Switches the session to a specific namespace and database |
Creating a session
Call .new_session() on an existing connection to create a new session. The async variant returns an AsyncSurrealSession and the sync variant returns a BlockingSurrealSession. Each session operates independently from the parent connection and other sessions.
A newly created session does not inherit the namespace, database, or authentication state of the parent connection. You must configure these explicitly on the session.
Isolating namespace and database
Each session can target a different namespace and database by calling .use(). Changes to one session's scope do not affect the parent connection or any other session.
In the example above, session_a reads from the docs database while session_b reads from staging, both over the same underlying WebSocket connection.
Independent authentication
Each session can authenticate as a different user. This is useful when you need to perform operations on behalf of multiple users without managing separate connections.
In the example above, session_admin has root-level access while session_user is authenticated as a record user. Each session's permissions are enforced independently.
Closing a session
When a session is no longer needed, call .close_session() to detach it from the connection and release its resources. The parent connection and other sessions remain active.
Closing the parent connection automatically closes all sessions associated with it.
Learn more
SurrealSession API reference for session method signatures
Transactions for transaction support within sessions
Authentication for signing in within sessions
Connecting to SurrealDB for WebSocket connection setup