Async GraphQL API with Strawberry and FastAPI: Solving N+1 Queries with DataLoader & Real-Time Subscriptions

Programming tutorial - IT technology blog
Programming tutorial - IT technology blog

Problem Statement: Why GraphQL APIs Slow Down in Production

Everything looks fast when you test a new GraphQL endpoint against five rows in a local database. Then you ship to production. A client requests 50 blog posts with their authors, and your database logs suddenly show 51 separate queries for one HTTP request. At just 5 ms per round-trip, that single request spends 255 ms waiting on the network. That is the N+1 query problem.

Requirements soon shift again: users want live updates when new posts land. Polling every 2 seconds across 1,000 open browser tabs generates 500 requests per second, mostly returning empty responses. Solving both N+1 queries and real-time delivery early prevents painful rewrites later. Here are the patterns I rely on when building async GraphQL services with Strawberry and FastAPI.

Core Concepts: Strawberry, DataLoader, and Subscriptions

Why Strawberry and FastAPI Pair Well

Strawberry defines GraphQL schemas using standard Python type hints and dataclasses. Your IDE autocomplete and static type checkers like mypy or Pyright work right away. Because both libraries run on ASGI and Python’s asyncio, database calls, HTTP requests, and WebSocket streams share a single event loop without blocking.

One rule saves headaches down the road: never expose SQLAlchemy or ORM models directly as Strawberry types. Keep your GraphQL types as a thin presentation layer. That way, internal database refactors will not break your public API contract.

How DataLoader Solves the N+1 Query Problem

A DataLoader collects individual key lookups from a single event loop tick and merges them into one batch call. Instead of running SELECT * FROM authors WHERE id = ? 50 times, your batch function runs one SELECT * FROM authors WHERE id IN (...). Fifty-one queries drop to two.

Never instantiate a DataLoader globally at module level. DataLoader caches results in memory for the lifetime of the instance, so sharing one across requests leaks stale data between users. Create a fresh DataLoader per request inside your GraphQL context instead.

Real-Time Updates with GraphQL Subscriptions

GraphQL subscriptions hold a persistent WebSocket connection open between the client and FastAPI. In Strawberry, a subscription resolver is an AsyncGenerator that yields payloads whenever an event fires.

Keep subscription resolvers lightweight. Rather than polling the database inside a while True loop, push events through an in-memory asyncio.Queue for single-process apps. When you scale to multiple Uvicorn workers, swap that queue for Redis Pub/Sub so every worker receives the broadcast.

Hands-On Practice: Building the Async GraphQL API

Step 1: Install the Required Packages

Set up a clean virtual environment and install FastAPI, Uvicorn, and Strawberry with its FastAPI extras:

python -m venv .venv
source .venv/bin/activate
pip install "strawberry-graphql[fastapi]" fastapi uvicorn

Step 2: Create a Per-Request DataLoader

Create a file named main.py. Start by simulating an async data source and writing a batch loader. Keep one strict DataLoader rule in mind: the returned list must match the exact length and order of the incoming keys list.

import asyncio
from typing import AsyncGenerator, Dict, List, Optional

import strawberry
from fastapi import FastAPI
from strawberry.dataloader import DataLoader
from strawberry.fastapi import GraphQLRouter

# Simulated async database tables
AUTHORS_DB: Dict[int, dict] = {
    1: {"id": 1, "name": "Alice Nguyen"},
    2: {"id": 2, "name": "Marcus Chen"},
}

POSTS_DB: List[dict] = [
    {"id": 101, "title": "Async Python Tips", "author_id": 1},
    {"id": 102, "title": "FastAPI Best Practices", "author_id": 2},
    {"id": 103, "title": "Scaling GraphQL", "author_id": 1},
]


async def load_authors(keys: List[int]) -> List[Optional[dict]]:
    # In production, replace this with a single batched SQL query: WHERE id IN (...)
    print(f"[DB] Batch loading authors for keys: {keys}")
    await asyncio.sleep(0.01)
    return [AUTHORS_DB.get(key) for key in keys]


async def get_context() -> dict:
    return {
        "author_loader": DataLoader(load_fn=load_authors),
    }

That print call inside load_authors is a quick sanity check during development. It lets you see immediately whether three separate author lookups collapse into one batch.

Step 3: Define Types, Queries, Mutations, and Subscriptions

With the loader ready, define the Author and Post types. On Post, the author field calls info.context["author_loader"].load(self.author_id) instead of querying the database directly. A shared list of asyncio.Queue instances lets mutations broadcast new posts to connected subscribers.

@strawberry.type
class Author:
    id: int
    name: str


@strawberry.type
class Post:
    id: int
    title: str
    author_id: strawberry.Private[int]

    @strawberry.field
    async def author(self, info: strawberry.Info) -> Optional[Author]:
        loader: DataLoader = info.context["author_loader"]
        data = await loader.load(self.author_id)
        if not data:
            return None
        return Author(id=data["id"], name=data["name"])


# Simple in-memory pub/sub channel for subscriptions
subscribers: List[asyncio.Queue] = []


@strawberry.type
class Query:
    @strawberry.field
    async def posts(self) -> List[Post]:
        return [
            Post(id=p["id"], title=p["title"], author_id=p["author_id"])
            for p in POSTS_DB
        ]


@strawberry.type
class Mutation:
    @strawberry.mutation
    async def create_post(self, title: str, author_id: int) -> Post:
        new_id = len(POSTS_DB) + 101
        record = {"id": new_id, "title": title, "author_id": author_id}
        POSTS_DB.append(record)
        post = Post(id=record["id"], title=record["title"], author_id=record["author_id"])

        for queue in subscribers:
            await queue.put(post)
        return post


@strawberry.type
class Subscription:
    @strawberry.subscription
    async def post_added(self) -> AsyncGenerator[Post, None]:
        queue: asyncio.Queue = asyncio.Queue()
        subscribers.append(queue)
        try:
            while True:
                post = await queue.get()
                yield post
        finally:
            subscribers.remove(queue)

Marking author_id with strawberry.Private[int] keeps it accessible to Python resolvers while hiding it from the public GraphQL schema. Wrapping the subscription loop in try...finally also ensures disconnected clients are removed from subscribers, preventing memory leaks over long-running deployments.

Step 4: Mount Strawberry on FastAPI and Test

Wire the schema and context getter into GraphQLRouter, then mount it on your FastAPI app:

schema = strawberry.Schema(
    query=Query,
    mutation=Mutation,
    subscription=Subscription,
)

graphql_app = GraphQLRouter(schema, context_getter=get_context)

app = FastAPI(title="Async GraphQL API")
app.include_router(graphql_app, prefix="/graphql")

Start the development server with Uvicorn:

uvicorn main:app --reload

Visit http://127.0.0.1:8000/graphql in your browser to open GraphiQL and fetch all posts with their authors:

query {
  posts {
    id
    title
    author {
      name
    }
  }
}

Watch your terminal output. Even though three posts come back (two by Alice and one by Marcus), you will see a single log line: [DB] Batch loading authors for keys: [1, 2]. DataLoader deduplicated key 1 automatically. To test subscriptions, open a second GraphiQL tab, start the postAdded subscription, and run createPost in the first tab—the new post appears over WebSockets right away.

Conclusion: Practical Habits to Keep Your API Healthy

Fast async GraphQL APIs come down to three consistent habits. Create DataLoader instances per request so user data stays isolated. Return batch results in the exact order of the requested keys. Finally, clean up subscription queues inside a finally block whenever a client disconnects.

Build these patterns into your starter template from day one. Adding nested relationships or live features later becomes routine, and your database load stays flat even as traffic grows.

Share: