Skip to content

Commit 4c1ca8f

Browse files
committed
Add documentation about concurrent asyncio tasks
1 parent 37e8abe commit 4c1ca8f

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

docs/lifecycle.md

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,18 @@ database access is potentially anticipated.
2020
The repository starts a `Session` for each _operation_, in order to maintain isolation.
2121
This means you can create a repository object almost whenever you want.
2222

23-
/// details | The only exception is creating repositories in global variables!
23+
/// details | There two exceptions: creating repositories in global variables or concurrent asyncio tasks
2424
type: warning
25-
The repository creates a session object, which is not thread safe, to avoid
25+
The repository creates and maintain the lifecycle of a session object to avoid
2626
emitting unnecessary queries to refresh the model state on new session.
2727

28-
Being the session object not thread safe, the repository is not thread safe as well.
28+
The session is not thread safe, therefore the repository is not thread safe as well.
2929

3030
Check the [Notes on multithreaded applications](/manager/session/#note-on-multithreaded-applications)
31+
32+
The `AsyncSession` [is not safe on concurrent asyncio tasks](https://docs.sqlalchemy.org/en/20/orm/session_basics.html#is-the-session-thread-safe-is-asyncsession-safe-to-share-in-concurrent-tasks),
33+
therefore the same repository instance can't be used in multiple asyncio tasks like
34+
when using `asyncio.gather()`
3135
///
3236

3337
Even using multiple repository instances will work fine, however as they will have completely
@@ -67,7 +71,7 @@ update_my_model()
6771
```
6872
///
6973

70-
The recommendation is of course to use the same repository instance where possible,
74+
The recommendation is of course to use the same repository instance, where possible,
7175
and structure your code in a way to match the single repository instance approach.
7276

7377
For example a strategy similar to this would be optimal, if possible:
@@ -77,6 +81,10 @@ For example a strategy similar to this would be optimal, if possible:
7781
* Do the changes you need, as per business logic
7882
* Save all the changed models as needed
7983

84+
/// tip | Using multiple repository instances is the only way to safely use concurrent asyncio tasks
85+
86+
///
87+
8088
### Unit of work
8189

8290
The Unit of Work session management follows the **same exact rules as the repository**,

0 commit comments

Comments
 (0)