Cursor rule for asyncio code covering TaskGroup, asyncio.timeout, safe cancellation, Semaphore concurrency caps, async context managers and blocking-call checks.
.cursor/rules/python-async-programming.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for asyncio code covering TaskGroup, asyncio.timeout, safe cancellation, Semaphore concurrency caps, async context managers and blocking-call checks."
globs: "**/*"
alwaysApply: false
---
# Python Async Programming (asyncio)
Applies to: Python code that uses `async def`, `await` or `asyncio` for I/O-bound work (HTTP clients, database drivers, sockets, queues).
Version baseline: checked against the Python 3.15 docs (Python 3.11+ is needed for `asyncio.TaskGroup` and `asyncio.timeout`). Read `requires-python` in `pyproject.toml` before using newer APIs. If the project supports Python 3.10 or older, use `asyncio.gather` and `asyncio.wait_for` and say so.
## When to use async
- Use asyncio for concurrent I/O. It does not speed up CPU-bound code. Send CPU work to a process pool (`loop.run_in_executor` with `ProcessPoolExecutor`).
- Never call blocking functions inside a coroutine. That includes `time.sleep`, `requests`, sync DB drivers and large file reads. Use the async library or `await asyncio.to_thread(blocking_fn, ...)`.
- Do not mix event loops. Call `asyncio.run(main())` once at the program entry point. Frameworks such as FastAPI already own the loop.
## Run independent work concurrently with TaskGroup
Prefer `asyncio.TaskGroup` (3.11+). If one task fails, the group cancels the others and raises an `ExceptionGroup`. Use `except*` to handle specific errors.
```python
import asyncio
async def fetch(name: str, delay: float) -> str:
await asyncio.sleep(delay) # stands in for a real network call
return name
async def load_dashboard() -> dict[str, str]:
async with asyncio.TaskGroup() as tg:
user = tg.create_task(fetch("user", 0.01))
stats = tg.create_task(fetch("stats", 0.02))
return {"user": user.result(), "stats": stats.result()}
```
Use `asyncio.gather(..., return_exceptions=True)` only when you want every result, including failures, and you will inspect each one. A plain `gather` does not cancel siblings when one task fails.
## Timeouts and cancellation
- Put a deadline on every network-bound await with `async with asyncio.timeout(seconds):` (3.11+). On older versions use `asyncio.wait_for`.
- Cancellation arrives as `asyncio.CancelledError`. Clean up in `finally` or an `except` block, then re-raise. Never swallow it, and never catch it with a bare `except Exception` and continue. `CancelledError` derives from `BaseException`, so `except Exception` does not catch it. Keep it that way.
```python
async def worker(queue: asyncio.Queue[str]) -> None:
try:
while True:
item = await queue.get()
try:
await handle(item)
finally:
queue.task_done()
except asyncio.CancelledError:
await flush_buffers() # project-specific cleanup
raise
```
- Keep a reference to every task created with `asyncio.create_task`, or use a TaskGroup. The event loop holds only weak references, so an unreferenced task can be garbage-collected before it finishes.
## Limit concurrency with a Semaphore
`asyncio.Semaphore(n)` caps how many coroutines run a section at once. It does not limit requests per second. If an API has a rate limit such as "10 requests/second", add a token bucket or the client library's rate limiter as well.
```python
async def fetch_all(urls: list[str], limit: int = 5) -> list[str]:
sem = asyncio.Semaphore(limit)
async def one(url: str) -> str:
async with sem:
return await download(url) # project HTTP call with its own timeout
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(one(u)) for u in urls]
return [t.result() for t in tasks]
```
## Async context managers and generators
- Wrap resources that need async setup and teardown in `@contextlib.asynccontextmanager`, or implement `__aenter__`/`__aexit__`.
- An async generator that holds a resource must be closed. Wrap it in `contextlib.aclosing(...)` so `aclose()` runs even if the consumer stops early.
```python
import contextlib
@contextlib.asynccontextmanager
async def open_session(dsn: str):
conn = await connect(dsn) # project driver
try:
yield conn
finally:
await conn.close()
```
## Testing async code
- Use the project's async test plugin (`pytest-asyncio` or `anyio`). Plain pytest does not run `async def` tests.
- Test the failure paths: a timeout firing, one TaskGroup child raising (assert on `ExceptionGroup`), and cancellation leaving no tasks pending.
- During development, run with `PYTHONASYNCIODEBUG=1` or `asyncio.run(main(), debug=True)`. It reports slow callbacks and coroutines that were never awaited.
## Verify before finishing
- Run the project's tests and type checker (for example `pytest` and `mypy`/`pyright`) when available.
- Search the changed code for blocking calls inside `async def`: `time.sleep(`, `requests.`, sync DB sessions, `open(` on large files.
- Confirm that every `create_task` result is kept or owned by a TaskGroup, and that every `except asyncio.CancelledError` re-raises.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Python 3.11+ service fetches several upstream APIs with an async HTTP client, and the developer asks Cursor to add concurrency without overloading the upstream.
Refactor sync_prices() in prices/sync.py so it fetches 200 product URLs concurrently with httpx.AsyncClient. The upstream allows at most 5 concurrent connections. Each call should time out after 3 seconds, and one failing URL should not leave other tasks running. requires-python = ">=3.12".
Illustrative; not a recorded model run. A diff that uses asyncio.TaskGroup to start the fetches, an asyncio.Semaphore(5) around each request, and asyncio.timeout(3) (or the client timeout) per call. Results are collected from the task objects after the group exits. CancelledError is re-raised if it is caught. The diff includes a short note that the Semaphore caps concurrency but is not a requests-per-second limiter. It adds no time.sleep or requests calls inside async def, and adds tests for the timeout and partial-failure paths.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/python-async-programming.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Python Async Programming: TaskGroup, Timeouts, Cancellation and Concurrency Limits project conventions"
globs: "**/*"
alwaysApply: false
---
# Python Async Programming (asyncio)
Applies to: Python code that uses `async def`, `await` or `asyncio` for I/O-bound work (HTTP clients, database drivers, sockets, queues).
Version baseline: checked against the Python 3.15 docs (Python 3.11+ is needed for `asyncio.TaskGroup` and `asyncio.timeout`). Read `requires-python` in `pyproject.toml` before using newer APIs. If the project supports Python 3.10 or older, use `asyncio.gather` and `asyncio.wait_for` and say so.
## When to use async
- Use asyncio for concurrent I/O. It does not speed up CPU-bound code. Send CPU work to a process pool (`loop.run_in_executor` with `ProcessPoolExecutor`).
- Never call blocking functions inside a coroutine. That includes `time.sleep`, `requests`, sync DB drivers and large file reads. Use the async library or `await asyncio.to_thread(blocking_fn, ...)`.
- Do not mix event loops. Call `asyncio.run(main())` once at the program entry point. Frameworks such as FastAPI already own the loop.
## Run independent work concurrently with TaskGroup
Prefer `asyncio.TaskGroup` (3.11+). If one task fails, the group cancels the others and raises an `ExceptionGroup`. Use `except*` to handle specific errors.
```python
import asyncio
async def fetch(name: str, delay: float) -> str:
await asyncio.sleep(delay) # stands in for a real network call
return name
async def load_dashboard() -> dict[str, str]:
async with asyncio.TaskGroup() as tg:
user = tg.create_task(fetch("user", 0.01))
stats = tg.create_task(fetch("stats", 0.02))
return {"user": user.result(), "stats": stats.result()}
```
Use `asyncio.gather(..., return_exceptions=True)` only when you want every result, including failures, and you will inspect each one. A plain `gather` does not cancel siblings when one task fails.
## Timeouts and cancellation
- Put a deadline on every network-bound await with `async with asyncio.timeout(seconds):` (3.11+). On older versions use `asyncio.wait_for`.
- Cancellation arrives as `asyncio.CancelledError`. Clean up in `finally` or an `except` block, then re-raise. Never swallow it, and never catch it with a bare `except Exception` and continue. `CancelledError` derives from `BaseException`, so `except Exception` does not catch it. Keep it that way.
```python
async def worker(queue: asyncio.Queue[str]) -> None:
try:
while True:
item = await queue.get()
try:
await handle(item)
finally:
queue.task_done()
except asyncio.CancelledError:
await flush_buffers() # project-specific cleanup
raise
```
- Keep a reference to every task created with `asyncio.create_task`, or use a TaskGroup. The event loop holds only weak references, so an unreferenced task can be garbage-collected before it finishes.
## Limit concurrency with a Semaphore
`asyncio.Semaphore(n)` caps how many coroutines run a section at once. It does not limit requests per second. If an API has a rate limit such as "10 requests/second", add a token bucket or the client library's rate limiter as well.
```python
async def fetch_all(urls: list[str], limit: int = 5) -> list[str]:
sem = asyncio.Semaphore(limit)
async def one(url: str) -> str:
async with sem:
return await download(url) # project HTTP call with its own timeout
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(one(u)) for u in urls]
return [t.result() for t in tasks]
```
## Async context managers and generators
- Wrap resources that need async setup and teardown in `@contextlib.asynccontextmanager`, or implement `__aenter__`/`__aexit__`.
- An async generator that holds a resource must be closed. Wrap it in `contextlib.aclosing(...)` so `aclose()` runs even if the consumer stops early.
```python
import contextlib
@contextlib.asynccontextmanager
async def open_session(dsn: str):
conn = await connect(dsn) # project driver
try:
yield conn
finally:
await conn.close()
```
## Testing async code
- Use the project's async test plugin (`pytest-asyncio` or `anyio`). Plain pytest does not run `async def` tests.
- Test the failure paths: a timeout firing, one TaskGroup child raising (assert on `ExceptionGroup`), and cancellation leaving no tasks pending.
- During development, run with `PYTHONASYNCIODEBUG=1` or `asyncio.run(main(), debug=True)`. It reports slow callbacks and coroutines that were never awaited.
## Verify before finishing
- Run the project's tests and type checker (for example `pytest` and `mypy`/`pyright`) when available.
- Search the changed code for blocking calls inside `async def`: `time.sleep(`, `requests.`, sync DB sessions, `open(` on large files.
- Confirm that every `create_task` result is kept or owned by a TaskGroup, and that every `except asyncio.CancelledError` re-raises.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.