Engineering notes

Scaling Django and FastAPI Applications

Scale Python applications by profiling queries, choosing the right concurrency model and budgeting workers, memory and database connections together.

Bitcave4 min readUpdated

Changing a framework is rarely the first scaling step. A Django or FastAPI application may be limited by query shape, database contention, blocking I/O, CPU work or an external dependency. Identify which one limits the user operation before changing concurrency. Django-specific examples here use the 5.2 documentation baseline; check the matching documentation for your deployed version.

Profile an endpoint with representative data

Trace the full request and separate application execution, SQL time, connection waiting, serialization and external calls. Record query count and inspect the execution plan for expensive queries. Test with realistic row counts and distributions; a development database with a handful of records will not expose the same costs.

In Django, select_related can join suitable single-valued relationships, while prefetch_related handles collections through additional queries. Use only the relations the response actually needs. Fetching every relationship can create large result sets and memory pressure. Verify output correctness after changing joins, annotations or aggregation, especially when several one-to-many relations can multiply rows.

Python application workers feeding a connection pool and database beside a background processing lane

Conceptual illustration of the topic; not an implementation diagram.

Fix data access before multiplying workers

Bound result size, choose stable pagination and add indexes based on observed filtering and ordering. An index trades storage and write overhead for faster access; inspect the plan rather than assuming every indexed query improves. Avoid loading a full table just to count or export it. Large exports may need iteration, batching and an asynchronous job.

The following Django example is illustrative: adapt relation names, authorization and pagination to the real model. select_related addresses the customer lookup and prefetch_related addresses line-item products. It does not prove that the whole endpoint is efficient; check query count, returned rows and memory with the actual response serializer.

orders = (
    Order.objects.filter(tenant_id=request.user.tenant_id)
    .select_related("customer")
    .prefetch_related("items__product")
    .order_by("-created_at", "-id")[:50]
)

Choose async for the actual waiting pattern

Async is useful when handlers spend time awaiting compatible network or database operations. Calling a blocking client inside async def blocks that event loop. CPU-heavy computation also remains expensive; move suitable work to separately managed processes or durable workers instead of assuming await creates parallel CPU execution.

Django 5.2 supports async views and an ASGI request stack, but synchronous middleware and sync-only operations affect the execution model. Its transaction guidance requires transactional work to be kept in a synchronous function and adapted appropriately. FastAPI similarly needs compatible async dependencies inside async handlers; ordinary def handlers use a thread-pool execution path. Choose based on measured work and library behavior.

Budget process memory and database connections

A worker is a process with its own memory and often its own connection pools. Multiplying workers multiplies those budgets. A large model or cache loaded in each process can exhaust memory before CPU reaches its limit. Estimate aggregate pools across replicas and workers, then reserve capacity for jobs, migrations and operational access.

There is no universal worker-count formula that replaces a load test. Increase workers while tracking successful throughput, tail latency, memory and pool wait. In an orchestrated container deployment, replication may be handled through containers rather than several workers inside each container. Keep the chosen process model observable and avoid accidentally scaling both dimensions without accounting for the multiplication.

Move durable work off the interactive path

Sending a response and then running a small best-effort action is different from accepting a durable business job. FastAPI BackgroundTasks and in-process tasks do not by themselves provide persisted delivery, cross-host scheduling or crash recovery. Exports, billing workflows and critical notifications often need a durable job store and worker system.

Persist the acceptance record, make handlers duplicate-safe and define retry, timeout and failure visibility. If creating a job must be atomic with a business write, use an outbox or another explicit consistency mechanism. Separate worker and API resource budgets so the batch path cannot starve interactive traffic.

Validate changes as a controlled experiment

Change one dominant factor at a time and replay a representative workload. Compare p95/p99, errors, successful throughput, SQL time, pool wait, memory and cost. Include a slow dependency, a cold cache and a worker restart. Check that accepted jobs recover and that permission filters still constrain the returned data.

Common mistakes are async handlers with blocking clients, increasing workers on a saturated database, caching tenant data without scope and optimizing queries by changing their meaning. Keep the framework choice unless evidence identifies a constraint it cannot reasonably meet. Often the first useful gain comes from fewer rows, shorter transactions and bounded concurrency.

References and further reading

Django 5.2: database access optimization

Django 5.2: asynchronous support

FastAPI: deployment concepts

FastAPI: async execution

FastAPI: background tasks

Related content

Backend Development, APIs and System Design

Backend systems, databases and APIs that connect your interfaces, apply business rules and keep information moving between the tools your team uses.

Software Modernisation and Performance Optimisation

Architecture review, database tuning and focused software improvements for applications that have become slow, fragile or difficult to change.

Scalable Software Engineering: Principles and Patterns

How stateless services, caching, queues, backpressure and load testing work together—and the conditions that make each pattern useful or dangerous.

Apply these decisions to your product

Describe the workload, current constraint and product goal to define the scope of a technical discussion.

Discuss your project