Skip to content
Aabha AI Academy

Module 5 of 9 · Lesson 14 of 26

Give concurrent tasks separate sessions

Work through give concurrent tasks separate sessions using a runnable reference, a focused regression check and a local extension.

Read in any order. All lessons stay open, including after an unanswered or incorrect check.

In this lesson you will give concurrent tasks separate sessions. Work with the Equipment Rental API in the downloadable lab. The reference is a complete solution with separate lesson checks, so you can inspect the answer, make a deliberate local change and verify its behavior.
An AsyncSession is mutable transaction state, so concurrent tasks must not share it. independent_reads creates a fresh session inside each read coroutine, then gathers the results. The caller shares the factory, not the session. Each task closes its own resource even if a lookup fails.

A single session cannot reliably service overlapping I/O while one task starts, commits or rolls back work another task believes it owns. Separate sessions also mean separate transactions: gather does not make a set of writes atomic. If a business operation needs all writes to succeed together, perform the operation sequentially inside one transaction instead of distributing it across unrelated task sessions. Keep the concurrency bounded when the input can grow; gathering a million ids would overwhelm the connection pool even with correct session isolation. The two-read example demonstrates ownership, not a general batch system. Pass identifiers and immutable values into tasks, rather than ORM objects carrying hidden session links.
Worked source: equipment/services.py, independent_reads.

The lesson14 check requests the same item through two concurrent tasks, verifies distinct live session identities and compares their returned names. Follow where the factory is called and where each context exits. The sessions are independent even though both tasks read the same row.
pythonCopyable
async def independent_reads(factory, identifiers):
    import asyncio

    async def read(identifier):
        async with factory() as session:
            item = await session.get(Equipment, identifier)
            return id(session), item.name if item else None

    return await asyncio.gather(*(read(identifier) for identifier in identifiers))
TerminalPython 3.13 virtual environment; Docker running; extracted lab directory
python run_checks.py -k lesson14

Expected result The selected lesson test passes against a new temporary PostgreSQL database; the container is removed afterward.

Keep for reference

Equipment Rental lab and lesson checks

ZIP containing Python source, real Alembic migrations, 26 lesson checks, a dependency lock and text instructions. Extract it before following the local exercise.

Download Equipment Rental lab and lesson checks

Practise locally

Add a third lookup for a missing item and assert its None result does not corrupt the two valid reads. Then wrap a larger set of reads with a small semaphore and track peak active tasks. Explain why limiting concurrency protects the pool but does not combine the tasks into one transaction. Save the peak count and test output.

The lesson check verifies the reference behavior. Add your own assertions for your change. Local practice is not uploaded or scored by this learning release.

Pause and reflect

What failure does this lesson prevent, and which assertion in lesson14 would expose it?

Use a concrete input, expected result and limitation from your local work. Saving a reflection does not certify the project.

Optional knowledge check

What should independent concurrent database tasks receive?

One AsyncSession so all tasks can modify it at once.

Try another answer. AsyncSession is mutable and is not safe to share across concurrent tasks.

Separate task sessions make all gathered writes one atomic transaction.

Try another answer. Independent sessions own independent transactions; gather does not combine them.

A shared factory from which each task creates its own session.

Correct. Each task needs independent transaction state and cleanup.

This practice does not assess your project or award a certificate.

Your reading progress

Progress is saved in this browser when storage is available.

Sign in to save across devices · Create an optional account