# Asyncio quick start

This tutorial uses the process-local `CacheManager`. For sharing across workers, see [choose a manager](<https://alessio-locatelli.github.io/client-query-cache/stable/getting-started/choose-a-manager/index.md>) and the [shared FastAPI example](<https://alessio-locatelli.github.io/client-query-cache/stable/examples/fastapi-shared/index.md>).

This program uses the asyncio manager from `client_query_cache.asynchronous` to write and read a document on your local MongoDB replica set. Await writes and single-result reads. Consume multi-document cursors with async iteration or `to_list()`.

```
import asyncio

from pymongo import AsyncMongoClient

from client_query_cache.asynchronous import CacheCoreConfig, CacheManager


async def main() -> None:
    async with (
        AsyncMongoClient("mongodb://localhost:27017") as client,
        CacheManager(
            client, cache_config=CacheCoreConfig(enable_telemetry=True)
        ) as cache_manager,
    ):
        collection = client["client_query_cache_tutorial"]["items"]
        cached_collection = cache_manager.get_cached_collection(collection)

        await collection.replace_one(
            {"_id": "example"}, {"_id": "example", "value": 42}, upsert=True
        )

        first = await cached_collection.find_one({"_id": "example"})
        repeated = await cached_collection.find_one({"_id": "example"})
        print(first, repeated)
        print("Cache hits:", cache_manager.snapshot().hits)

        items = await cached_collection.find({"value": 42}).to_list()
        print(items)


asyncio.run(main())
```

Save the program as `quick_start_async.py` and run `python quick_start_async.py` in the environment where you installed the library. On an eligible deployment with a healthy stream, repeated reads can hit the cache. If caching is unavailable, reads bypass to PyMongo. Startup and concurrent changes can affect the observed hit count; inspect [bypass reasons and stream health](<https://alessio-locatelli.github.io/client-query-cache/stable/operations/monitoring/index.md#bypass-reasons-and-stream-health>) for diagnostics.

Use the PyMongo collection for writes. `find()` returns an async cursor immediately: use `async for document in cached_collection.find(...)` to iterate it. Await `aggregate()` to receive its async command cursor, then iterate it or await `cursor.to_list()`. Use `.raw` when a read must execute against MongoDB. See [cached reads](<https://alessio-locatelli.github.io/client-query-cache/stable/usage/cached-reads/index.md>).

The `async with` block closes the manager before the client. Outside a context manager, call `await cache_manager.close()` before `await client.close()`. The manager owns its background streams and cached data, and you own the client. Keep both alive across application requests; see [deployment](<https://alessio-locatelli.github.io/client-query-cache/stable/operations/deployment/index.md>).

Awaiting a cached read does not wait for a preceding write's invalidation. Use a direct PyMongo read with suitable session and concerns for freshness requirements; see [consistency](<https://alessio-locatelli.github.io/client-query-cache/stable/usage/consistency/index.md>). Eligible cache misses read from the primary with `majority` read concern even though this program leaves read concern unspecified, so they can differ from a direct read that uses the deployment's default, normally `local`; see [bypass conditions](<https://alessio-locatelli.github.io/client-query-cache/stable/reference/api/index.md#bypass-conditions>).

## Optional uvloop

Consider [uvloop](<https://github.com/MagicStack/uvloop>) for process-local workloads dominated by cache misses on `_id` lookups. Matched measurements with 4 KiB documents found lower miss latency with four worker processes, each awaiting one read at a time. This evidence does not establish a speedup for cache hits, shared caching or concurrent requests on one loop. Measure your application's workload before choosing a loop.

If your application installs uvloop, replace the example's final line with:

```
import uvloop

asyncio.run(main(), loop_factory=uvloop.new_event_loop)
```

The library does not require, install or configure uvloop. Standard asyncio remains supported.
