Profiling a Slow Endpoint
Pinpoint performance bottlenecks in live backend services using sampling profilers (py-spy) versus deterministic tracers (cProfile), detecting N+1 queries, pool starvation, and CPU hotspots.
Contentsand lesson path
On this page
- The problem: where does the time go?
- Sampling profilers (py-spy) and tracing profilers (cProfile)
- Counting queries to catch an N+1 pattern
- Check your understanding
- Apply it
- Review prompt
Lessons of API Performance & Profiling
- Percentiles, Throughput and Little's Law Concept · 20 min
- Lab: A Reproducible Load Test Lab · 30 min
- Profiling a Slow Endpoint Worked example · 25 min
- Targeted Fixes and Overload Guards Concept · 25 min
- Lab: Prove the Fix, Then Push Past Capacity Lab · 30 min
- Check: Diagnose from the Numbers Knowledge check · 8 questions
What you will learn
- Locate a bottleneck with a profiler, database query timings and pool or worker saturation metrics instead of guessing.
01. The problem: where does the time go?
Here is the situation this lesson works through. Under load, the p95 of GET /orders rises from 120 ms to 900 ms. It is tempting to start changing things at once: add a cache, add replicas, raise the number of worker threads. Each of those costs time, and without evidence none of them is likely to hit the real cause. The first job is to find out what the request is waiting for.
Start with three cheap signals that you probably already collect: CPU use of the API processes, query times in the database, and the state of the connection pool. Together they point to one of four usual causes.
- CPU-bound code. API CPU is close to 100%, so requests queue for the processor. Typical causes are serialising very large JSON payloads, expensive regular expressions or hashing inside a loop. A CPU profiler shows where that time goes.
- Slow queries. API CPU is low, but the database's slow-query log shows queries taking hundreds of milliseconds. A missing index or lock waits are the usual suspects, and
EXPLAIN ANALYZE(next lesson) confirms which. - Pool starvation. API CPU is low and every query finishes in a few milliseconds, yet p95 is near a second. The time is spent waiting to get a connection from a pool where all connections are taken. That wait is part of the request time but does not appear in the database's own query timings, so only pool metrics reveal it.
- Memory and garbage collection. p50 stays fast while p99 shows periodic stalls. In Python, a run of the cyclic garbage collector holds up the whole process while it lasts, not just the thread that triggered it, and with many live objects those pauses reach the tail.
Knowing which case you are in tells you which tool to use next.
02. Sampling profilers (py-spy) and tracing profilers (cProfile)
Python has two kinds of profiler, and they suit different situations.
A deterministic (tracing) profiler such as cProfile registers a callback that runs on every function call and return (through sys.monitoring since Python 3.12, sys.setprofile before that). It counts every call exactly, but the hook itself costs time, so code that makes many small calls can run several times slower under it, and the cheapest functions look more expensive than they are. Its output for asyncio code is also hard to read, because time is attributed to the event loop machinery. It is a good tool for a single slow script on your machine, not for a service under real traffic.
A sampling profiler such as py-spy works from outside the process. About 100 times per second by default (change it with --rate), it reads the Python call stack of the running process through Linux system calls (process_vm_readv or ptrace). By default it pauses the target briefly for each sample so the stack is consistent; --nonblocking avoids that pause at the cost of occasional bad samples. It needs no code changes and no restart, and its overhead is low enough for staging and careful production use. Inside a container it needs the SYS_PTRACE capability, which you usually grant ahead of time. Python 3.15 added a sampling profiler of the same kind to the standard library, profiling.sampling (and made cProfile an alias of profiling.tracing); the ideas below apply to both, and this lesson uses py-spy because it also works on older Pythons.
py-spy record can write a flame graph. Each box is a function; boxes stacked on top of it are the functions it called. The width of a box is the share of samples in which that function was on the stack, so wide boxes are where the time went. The left-to-right order is not time order. A wide plateau at the top of a tower is a function that was itself doing the work.
A CPU flame graph shows only time spent running. py-spy leaves out threads that it sees as idle, so if your threads spend most of their time waiting for database sockets, locks or other services, the graph looks nearly empty even though requests are slow. That is a finding, not a failed run: use py-spy dump to see what each thread is waiting on, py-spy record --idle to include waiting stacks, or off-CPU tools such as offcputime from the bcc project.
03. Counting queries to catch an N+1 pattern
Many slow listings are not one slow query but many fast ones. An ORM with lazy loading runs one query for the list, then one more for each row the moment you touch a related object: N rows cost N + 1 queries. Each query takes a few milliseconds, so none shows up as slow in the database log, but the round trips add up and grow with the page size.
You can measure this directly. SQLAlchemy fires a before_cursor_execute event for every statement it sends, so a listener that appends to a list counts them. The script below uses an in-memory SQLite database, so it needs only SQLAlchemy (pip install "sqlalchemy==2.1.9").
"""Count the SQL statements behind one listing: N+1 versus selectinload."""
from sqlalchemy import ForeignKey, create_engine, event, select
from sqlalchemy.orm import (DeclarativeBase, Mapped, Session, mapped_column,
relationship, selectinload)
class Base(DeclarativeBase):
pass
class Customer(Base):
__tablename__ = "customers"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id"))
customer: Mapped[Customer] = relationship() # lazy="select" by default
engine = create_engine("sqlite://") # in-memory database
Base.metadata.create_all(engine)
with Session(engine) as s: # 200 orders, each for a different customer
s.add_all(Customer(id=i, name=f"c{i}") for i in range(1, 201))
s.add_all(Order(id=i, customer_id=i) for i in range(1, 201))
s.commit()
statements = []
@event.listens_for(engine, "before_cursor_execute")
def count(conn, cursor, statement, parameters, context, executemany):
statements.append(statement) # runs once for every SQL statement sent
def listing(stmt) -> int:
statements.clear()
with Session(engine) as s:
rows = [(o.id, o.customer.name) for o in s.scalars(stmt)]
assert len(rows) == 200
return len(statements)
print("lazy loading:", listing(select(Order)), "statements")
print("selectinload:", listing(select(Order).options(selectinload(Order.customer))),
"statements")python n_plus_one.pylazy loading: 201 statements
selectinload: 2 statementsThe lazy version sends one SELECT for the orders and then one per order for its customer: 201 statements. With selectinload, SQLAlchemy loads all the customers in a second query with an IN list: 2 statements, whatever the page size. An index cannot remove the extra round trips, because each of the 200 queries is already fast. The same listener, placed in a test, turns this into a regression check: assert that the listing sends no more than two statements.
Back to GET /orders: when API CPU is low, the slow-query log is empty and the statement count grows with the number of orders on the page, N+1 queries are the likely cause. Fix them with selectinload, then rerun the load test from lesson 2 and compare p95 with the 900 ms you started from.
04. Check your understanding
05. Apply it
Use these on the slowest endpoint from your load test in the skill project:
- Profile one worker, not the master: find the worker PIDs with
pgrep -f uvicornorps --ppid <master-pid>, then runpy-spy record -o profile.svg --pid <worker-pid> --duration 30while the load test runs. To cover every worker at once, usepy-spy record --subprocesses -o profile.svg --pid <master-pid> --duration 30. - In Docker or Kubernetes, grant
SYS_PTRACEto the staging container (securityContext.capabilities.add: ["SYS_PTRACE"]) before you need it. - Export connection pool metrics. With SQLAlchemy's default
QueuePool,pool.checkedout()andpool.overflow()show how many connections are in use, and a steady count at the maximum with waiting requests means starvation. - Add a query-count test for every listing endpoint, with a
before_cursor_executelistener as above, or in Django withassertNumQueries(pytest-django: thedjango_assert_num_queriesfixture). - Do not hold a database connection while waiting for an outside service (payments, storage, email): take the connection just before the query and release it straight after.
The next lesson covers the targeted fixes: indexes checked with EXPLAIN ANALYZE, and overload guards.
06. Review prompt
Without looking back, explain which three signals tell CPU-bound code, slow queries and pool starvation apart. Compare how cProfile and py-spy collect data and why that matters on a live service. Describe what a nearly empty CPU flame graph of a slow endpoint means, and how you would show with a test that a listing no longer has an N+1 pattern.
References
- py-spy: Sampling profiler for Python programs
- Python documentation: profiling (profiling.sampling and profiling.tracing)
- SQLAlchemy documentation: Relationship Loading Techniques
- SQLAlchemy documentation: Core Events (before_cursor_execute)
- pytest-django documentation: django_assert_num_queries
- Brendan Gregg: Flame Graphs
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.