Skip to content

Module 07 · Lesson 7.2

Profiling and Reading the Evidence

45 minUpdated 19 Nov 2026Part of Performance and Reliability Investigation · Existing Project Engineering
On this page
  1. What you will learn
  2. Where does the time go? Evidence before opinion
  3. Worked scenario: counting the queries behind "My orders"
  4. Reading a Python profile: call counts, not guesses
  5. Logs, metrics and the tools that give you evidence
  6. Step-by-step workflow
  7. Using an AI assistant to read the evidence
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

A shop owner wants to know why the queue at the till is long. She could watch the staff and guess. Or she could count how many items each customer buys, how long each scan takes, and how often the till jams. The numbers point at the cause. Her guesses may not.

In this lesson you will do the same for the slow "My orders" page of the fictional Tidewell Wholesale service. You will count the database queries, read a profiler's report and add a log line to every request. You will also meet the tools teams use for this work. Everything is invented, and the code is simplified so you can run it.

What you will learn

  • Count the database queries behind one request and read the pattern.
  • Explain the N+1 query pattern in plain words.
  • Read call counts from a Python profiler and say what they show.
  • Add a structured log line per request, and name the tools used to find slow code.

Before you start

Where does the time go? Evidence before opinion

Your baseline says the page takes a median of 2.4 seconds for account TC7-0042. It does not say why. Time can go to the database, to Python code, to a slow outside service, or to waiting for a free worker. Each needs a different fix.

Evidence comes in a few kinds. You will use all of them in this lesson. Here they are in plain words.

Profiler
A tool that watches a program run and records which functions were called and how long they took. It is like a stopwatch on every station in a kitchen.
Query
One question sent to the database, such as 'give me the lines of order 50'. Each query has a cost, even a small one, because it is a round trip to another program.
N+1 query pattern
Code asks one query for a list of N items, then asks one more query for each item. That is 1 + N queries. Imagine asking a librarian for a list of 50 books, then walking back 50 times to ask for each book's author, instead of asking for both at once.
Log
A line of text the program writes about something that happened. A good log line says what, for whom and how long. It is a diary the system keeps.
Metric
A number tracked over time, such as requests per minute or the p95 time. Metrics show trends. Logs show single events.
Trace
The story of one request as it passes through several parts, with the time spent in each. It is like a parcel-tracking page.

Worked scenario: counting the queries behind "My orders"

You open order_history(customer_id, limit=50) in orders/selectors.py. In the real service it uses Django's database layer, and the loops hide the queries. Here is how it looks, as an excerpt. You do not need to run it.

Pythonorders/selectors.py (excerpt)
def order_history(customer_id, limit=50):
    orders = Order.objects.filter(customer_id=customer_id).order_by("-created_at")[:limit]
    history = []
    for order in orders:
        lines = []
        for line in order.lines.all():          # one query per order
            lines.append({"product": line.product.name,   # one query per line
                          "qty": line.qty,
                          "line_total_pence": line.qty * line.unit_price_pence})
        history.append({"order_id": order.id, "lines": lines})
    return history

The real service's shape, using Django models. An excerpt, not runnable on its own.

It reads nicely. But order.lines.all() asks the database for that order's lines. And line.product.name asks for the product. Each of these runs inside a loop. Django fetches related rows lazily, only when you touch them. So the loops quietly turn into many queries.

Do not trust the reading. Count. The rest of the lesson uses a simplified version of the service's code, so you can run it without Django. It uses SQLite, a small database built into Python. SQLite here, PostgreSQL in the service. The shape of the tables and the queries is the same. First, the practice data.

Pythonseed.py
import sqlite3
from datetime import date, timedelta

SCHEMA = """
CREATE TABLE products (id INTEGER PRIMARY KEY, sku TEXT, name TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id TEXT, created_at TEXT);
CREATE TABLE order_lines (
    id INTEGER PRIMARY KEY, order_id INTEGER, product_id INTEGER,
    qty INTEGER, unit_price_pence INTEGER
);
"""

PRODUCTS = ["Napkins 100", "Paper cups 8oz", "Coffee beans 1kg", "Oat milk 1L",
            "Stirrers 500", "Napkin dispenser", "Lids 8oz", "Sugar sachets 1000"]


def seeded_connection():
    """SQLite here, PostgreSQL in the service. Same shape, tiny data."""
    conn = sqlite3.connect(":memory:")
    conn.executescript(SCHEMA)
    for i, name in enumerate(PRODUCTS, start=1):
        conn.execute("INSERT INTO products VALUES (?, ?, ?)", (i, f"SKU-{i:03}", name))
    order_id = 0
    for customer, count in [("TC7-0042", 50), ("TC7-0100", 10)]:
        for day in range(count):
            order_id += 1
            created = (date(2026, 1, 1) + timedelta(days=day)).isoformat()
            conn.execute("INSERT INTO orders VALUES (?, ?, ?)", (order_id, customer, created))
            for k in range(3):  # three lines on every order
                product_id = (order_id + k) % len(PRODUCTS) + 1
                conn.execute(
                    "INSERT INTO order_lines (order_id, product_id, qty, unit_price_pence) "
                    "VALUES (?, ?, ?, ?)",
                    (order_id, product_id, order_id % 5 + 1, 100 + 25 * product_id),
                )
    conn.commit()
    return conn

Builds a tiny database: 8 products, 50 orders for TC7-0042 with 3 lines each, and 10 orders for another account.

Now the simplified order_history. It does what the Django version does: one query for the orders, one per order for its lines, and one per line for the product name.

Pythonhistory_slow.py
def order_history(conn, customer_id, limit=50):
    orders = conn.execute(
        "SELECT id, created_at FROM orders "
        "WHERE customer_id = ? ORDER BY created_at DESC LIMIT ?",
        (customer_id, limit),
    ).fetchall()
    history = []
    for order_id, created_at in orders:
        rows = conn.execute(
            "SELECT product_id, qty, unit_price_pence FROM order_lines "
            "WHERE order_id = ? ORDER BY id",
            (order_id,),
        ).fetchall()
        lines = []
        for product_id, qty, price in rows:
            name = conn.execute(
                "SELECT name FROM products WHERE id = ?", (product_id,)
            ).fetchone()[0]
            lines.append({"product": name, "qty": qty, "line_total_pence": qty * price})
        total = sum(line["line_total_pence"] for line in lines)
        history.append({"order_id": order_id, "created_at": created_at,
                        "lines": lines, "total_pence": total})
    return history

A simplified version of the service's order_history, so you can run it without Django.

A query counter

SQLite lets you register a function that is called for every statement it runs. The small class below collects them. Think of it as a counter clicker at a door.

Pythonquery_counter.py
class QueryCounter:
    """Counts every SQL statement a connection runs while the block is open."""

    def __init__(self, conn):
        self.conn = conn
        self.statements = []

    def __enter__(self):
        self.conn.set_trace_callback(self.statements.append)
        return self

    def __exit__(self, *exc):
        self.conn.set_trace_callback(None)

    @property
    def count(self):
        return len(self.statements)

Counts every SQL statement run while the 'with' block is open.

What each part does

  • set_trace_callback(self.statements.append) tells SQLite to hand every statement it runs to our list.
  • __enter__ and __exit__ make the class work with with. Counting starts at the top of the block and stops at the end.
  • count is the number of statements collected.
  • In Django, the equivalent is the test helper assertNumQueries, or the SQL panel of django-debug-toolbar.
Pythoncount_queries.py
from history_slow import order_history
from query_counter import QueryCounter
from seed import seeded_connection

conn = seeded_connection()
with QueryCounter(conn) as counter:
    history = order_history(conn, "TC7-0042", limit=50)

print("orders returned:", len(history))
print("queries run:", counter.count)
print()
for statement in counter.statements[:4]:
    print(statement)
print("...")
print(counter.statements[-1])
print()
for table in ("FROM orders", "FROM order_lines", "FROM products"):
    n = sum(1 for s in counter.statements if table in s)
    print(f"{n:>4}  {table}")

Runs the slow history for TC7-0042 and prints the count, the first statements and a tally.

Real output (run twice, identical)Captured from a real run
orders returned: 50
queries run: 201

SELECT id, created_at FROM orders WHERE customer_id = 'TC7-0042' ORDER BY created_at DESC LIMIT 50
SELECT product_id, qty, unit_price_pence FROM order_lines WHERE order_id = 50 ORDER BY id
SELECT name FROM products WHERE id = 3
SELECT name FROM products WHERE id = 4
...
SELECT name FROM products WHERE id = 4

   1  FROM orders
  50  FROM order_lines
 150  FROM products

There it is. One request for 50 orders runs 201 queries: 1 for the orders, 50 for their lines and 150 for the product names. That is 1 + 50 + 150. Look at the middle statements. They are the same question over and over, with a different number each time.

This also explains the symptom. A small account with 5 orders would run 1 + 5 + 15 = 21 queries. The cost grows with the number of orders. That matches what you saw in the baseline: small accounts are fast, the big one is slow.

Reading a Python profile: call counts, not guesses

Python ships with a profiler called cProfile. It records every function call while your code runs. A full report shows times too. Times differ between runs, so this lesson prints only the call counts, which never change.

Pythonprofile_calls.py
import cProfile
import pstats

from history_slow import order_history
from seed import seeded_connection

conn = seeded_connection()
profiler = cProfile.Profile()
profiler.runcall(order_history, conn, "TC7-0042", 50)

rows = []
for (filename, line, name), (cc, nc, tt, ct, callers) in pstats.Stats(profiler).stats.items():
    if name == "order_history" or "sqlite3" in name:
        rows.append((nc, name))

for calls, name in sorted(rows, reverse=True):
    print(f"{calls:>5} calls  {name}")

Profiles one call of the slow history and prints how many times each relevant function ran.

What each part does

  • profiler.runcall(...) runs order_history once while the profiler watches.
  • pstats.Stats(profiler).stats is a table with one row per function. The second number in each row (nc) is how many times it was called.
  • The if keeps only our function and the database functions, so the output is short.
  • The rows are sorted from most calls to fewest.
Real output (run twice, identical)Captured from a real run
201 calls  <method 'execute' of 'sqlite3.Connection' objects>
150 calls  <method 'fetchone' of 'sqlite3.Cursor' objects>
 51 calls  <method 'fetchall' of 'sqlite3.Cursor' objects>
  1 calls  order_history

Read it from the top. The database's execute ran 201 times. That agrees with the query counter, which is a good sign: two tools give the same answer. fetchone ran 150 times, once per product name. And order_history itself ran once.

A real profile also reports the time each function took. That is useful, but it needs care. Profiling slows the program, and the numbers differ between machines. Use times to compare parts of one run. Do not quote them as facts.

Sampling profilers for a running service

cProfile watches every call. For a live service, teams often use a sampling profiler. It looks at what the program is doing every few milliseconds, like taking a photo of a busy kitchen ten times a second. The station that shows up in the most photos is where the time goes. py-spy (opens in a new tab) does this for Python programs without changing their code.

Logs, metrics and the tools that give you evidence

You can run a script on your laptop. But the slow page happens on a server, for real customers. For that you need the system to leave evidence by itself. The cheapest start is one structured log line per request. 'Structured' means a fixed shape, such as JSON, so a tool can search and count it.

Pythonlog_request.py
import json

from history_slow import order_history
from query_counter import QueryCounter
from seed import seeded_connection


def handle_request(conn, customer_id, clock):
    """One structured log line per request: who, how long, how many queries."""
    start = clock()
    with QueryCounter(conn) as counter:
        history = order_history(conn, customer_id)
    line = {
        "path": "/api/orders/",
        "customer": customer_id,
        "status": 200,
        "orders": len(history),
        "queries": counter.count,
        "duration_ms": round((clock() - start) * 1000),
    }
    print(json.dumps(line))


ticks = iter([0.0, 2.412])  # a fake clock, so the output never changes
handle_request(seeded_connection(), "TC7-0042", lambda: next(ticks))

Wraps one request and prints a log line with who, what, how many queries and how long. A fake clock keeps the output the same each time.

Real output (run twice, identical)Captured from a real run
{"path": "/api/orders/", "customer": "TC7-0042", "status": 200, "orders": 50, "queries": 201, "duration_ms": 2412}

The duration here comes from the fake clock, so it is a stand-in for the 2.4 s of the story. In the real service the same line would carry the real time. Now every request says how many queries it made. A search of the logs for queries > 100 finds every slow page in one go. No guessing needed.

Tools you will meet

ToolWhat it showsPlain-words picture
django-debug-toolbar (opens in a new tab)In a development copy of a Django site, the queries behind each page, with repeated ones flagged.A receipt that lists every question your page asked the database.
PostgreSQL pg_stat_statements (opens in a new tab)An extension that records how often each kind of query ran and how long it took in total. The database administrator must switch it on.A tally sheet at the database's door.
py-spy (opens in a new tab)Where a running Python process spends its time, by sampling.A photo of the kitchen every few milliseconds.
APM tools (application performance monitoring)Traces of real requests across services, plus metrics. Several commercial and open-source products exist.Parcel tracking for every request.
Four kinds of evidence tool. Pick by what you can install and what your team already uses.

Here is one query you might run against pg_stat_statements. It lists the query shapes that ran most often. You run it as a database user with permission, on a system where the extension is on. This is an excerpt without output, since results depend on your database.

SQL
SELECT calls, round(total_exec_time::numeric) AS total_ms, left(query, 60) AS query
FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 5;

The most-called query shapes. Column names are from current PostgreSQL versions; check the documentation for yours.

If our N+1 problem were live, the lines query and the products query would sit at the top with thousands of calls each.

A checklist for where to look: the USE method

Sometimes you do not yet know which part is slow at all. Performance engineer Brendan Gregg describes the USE method (opens in a new tab). For each resource (CPU, memory, disk, network, database connections), ask three questions: how Used is it, is work Saturated (waiting in a queue), and are there Errors? It is a checklist that stops you from skipping a resource. Think of walking through a house and checking every tap for water, pressure and leaks.

Step-by-step workflow

  1. Step 1: Start from the baseline and the symptom

    Re-read your statement. Pick the one request you will investigate, such as GET /api/orders/ for TC7-0042.

    What you should see: One request, one account, one target.

  2. Step 2: Read the code path with suspicion

    Find the loops. Note every line inside a loop that touches the database or another service. These are candidates, not conclusions.

    What you should see: A list of suspect lines.

  3. Step 3: Count before you time

    Wrap the request in a query counter. Record the number, and the number for a small account too. Counts are steady, so they are good first evidence.

    What you should see: A query count for a big and a small account.

  4. Step 4: Profile one request

    Run a profiler on one call. Read the call counts first. Look at times only to compare parts of the same run.

    What you should see: A short table of the functions called most often.

  5. Step 5: Add a log line so the evidence outlives your laptop

    Log the path, the account, the status, the duration and the query count for each request. Keep personal data out.

    What you should see: A searchable record from the real system.

  6. Step 6: State what you found and what you did not

    Write: 'The request makes 201 queries (1 + 50 + 150). Not yet shown: how much of the 2.4 s these queries account for.' Then choose the next test.

    What you should see: A short evidence note with a clear gap.

From a slow request to located evidence
  1. Baseline

    Median, p95

  2. Read the loops

    Suspect lines

  3. Count queries

    Big and small account

  4. Profile one call

    Call counts

  5. Add a log line

    Evidence from live traffic

  6. Evidence note

    Found and not found

Counts first, because they are the same every run. Times come later, to compare parts.

Using an AI assistant to read the evidence

An assistant is good at reading a pile of output and naming a pattern. It is the second pair of eyes that says 'those 150 identical lookups look like an N+1 pattern'. It cannot run your code, so it must work from the evidence you provide.

  • Give it: the function source, the query count output with the first and last statements, and the call counts. Remove secrets and personal data first.
  • Ask it for: the pattern it sees, other explanations that fit the same evidence, and the cheapest test that would tell them apart.
  • Do not ask it: to guess timings. It will invent them. Ask what to measure instead.
  • Then check: each claim against your own output. If it says 'the database is slow', ask which number shows that.

Conclusion and your next step

You can now put numbers on what a request does. You counted 201 queries for one page, learned the N+1 pattern, read a profiler's call counts, and added a log line that records the evidence in the live system.

Your next step: fix what the evidence shows. Continue with Database and Query Problems, where you cut 201 queries to 2 and check a database query plan.

For more, read Debugging Deadlocks and Race Conditions with AI and the module overview Performance and Reliability Investigation.

Reusable prompt

Evidence reader for a slow request

Asks an assistant to name the pattern in your query counts and profile output, to list other explanations, and to suggest the cheapest next test, without inventing timings.

Below is evidence I collected for one slow endpoint in a Python and Django service called tidewell-orders (fictional). Use ONLY this evidence. Do not guess timings and do not propose a fix yet.

Symptom: GET /api/orders/ for account TC7-0042 has median 2.4 s and p95 4.1 s on staging. Small accounts take about 0.2 s.

Code (simplified):
- order_history runs one query for the 50 latest orders.
- For each order it runs one query for the order lines.
- For each line it runs one query for the product name.

Query counter output for TC7-0042:
queries run: 201
   1  FROM orders
  50  FROM order_lines
 150  FROM products

Profiler call counts:
  201 calls  execute
  150 calls  fetchone
   51 calls  fetchall
    1 calls  order_history

Please give me:
1. The pattern you see, in plain words, and the lines of evidence that show it.
2. Two other explanations that would fit the same evidence, if any.
3. The cheapest test that would tell the explanations apart.
4. What this evidence does NOT show.
Mark any guess as (unverified).
Show the reusable template

Replace each {{placeholder}} with your own details.

Below is evidence I collected for one slow endpoint in {{system_description}}. Use ONLY this evidence. Do not guess timings and do not propose a fix yet.

Symptom: {{symptom_statement_with_numbers}}

Code (simplified):
{{code_summary_or_source}}

Query counter output:
{{query_count_output}}

Profiler call counts:
{{profiler_call_counts}}

Please give me:
1. The pattern you see, in plain words, and the lines of evidence that show it.
2. Two other explanations that would fit the same evidence, if any.
3. The cheapest test that would tell the explanations apart.
4. What this evidence does NOT show.
Mark any guess as (unverified).

Expected output and limitations

A named pattern with pointers to your lines, two alternative explanations, one cheap test, and a short list of gaps. It should not contain invented timings or a rewrite.

Sample responseIllustrative — your output will differ
1. Pattern: an N+1 query pattern. One query loads the orders, then one query per order loads its lines (50), then one query per line loads the product (150). 1 + 50 + 150 = 201, which matches the counter and the 201 execute calls.

2. Other explanations that fit the same evidence:
- The database round trips are slow on staging for another reason, such as network distance (unverified).
- Python code outside the queries also takes time, for example building the response (unverified; the profile shows few calls there).

3. Cheapest test: run the same request for an account with 5 orders and for one with 500. If the query count and the time both grow with orders, the pattern explains the growth.

4. Not shown by this evidence: how much of the 2.4 s is spent in the queries, whether staging matches production, and whether the orders query itself is slow.

Limitations to keep in mind

  • The assistant sees only what you pasted. It has not opened the repository.
  • It may say the database is 'under-powered' or the network is 'slow'. Nothing in the evidence shows that, so mark it unverified.
  • It may suggest a fix anyway. That is for the next lesson, after you have checked the evidence.
  • It cannot confirm that the queries are the slow part. Only a before-and-after measurement can.

Common errors and how to fix them

Trusting timings from a profile

Why it happens: A profile prints seconds, so the numbers look exact.

Fix: Profiling slows the program, and times change between runs. Quote call counts and relative shares, and take real timings with the baseline method.

Missing the loop that hides the queries

Why it happens: Framework code fetches related rows only when touched, so the line that costs a query looks harmless, such as line.product.name.

Fix: Count queries in a test. Do not rely on reading the code. A count of 201 for 50 orders cannot hide.

Logging too much, including personal data

Why it happens: It feels safer to log the whole request.

Fix: Log the fields you will search on: path, account code, status, duration and query count. Leave out names, emails and addresses.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Count the queries behind one request in your own repository

Pick one slow request in a repository or sample application you may study. Count its database calls, profile it, and write a short evidence note.

You will need

  • A repository you are allowed to run, with a test database or a development copy.
  • Your baseline note from the previous lesson, or a new one.
  • A query counter for your stack, such as assertNumQueries in Django or the logging option of your database library.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • If you have no database, count calls to any slow dependency, such as an HTTP client.
  • If the counts are the same for big and small inputs, the cost is not in a loop over the input.
  • If you use an assistant, paste only counts and code, and ask for other explanations.
Show a model answer

A strong answer reads like the lesson. It gives a count for a big and a small input, such as 201 and 21, and shows the pattern as 1 + N + 3N. It quotes call counts and calls them evidence. It says what is still unknown, such as how much of the total time the queries take. A weak answer says 'it makes a lot of queries', has no numbers and goes straight to a fix.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.A page loads 40 orders. The code makes 1 query for the orders and 1 query per order for its lines. How many queries run?
    Show the answer and explanation

    Answer: B. It is 1 for the list plus 40 for the lines, which is 41. That is the N+1 pattern. Saying 2 assumes the lines are fetched together, which this code does not do.

  2. 2.Why does this lesson print call counts from the profiler instead of times?
    Show the answer and explanation

    Answer: A. Counts repeat exactly, so they make steady evidence you can compare. Profilers can measure time, but the numbers vary and the profiler itself adds cost. Neither kind is always more important. They answer different questions.

  3. 3.An assistant reads your evidence and says the database server is under-powered. Nothing in your output shows that. What do you do?
    Show the answer and explanation

    Answer: B. A claim with no evidence is a guess, however fluent. Asking for hardware spends money on an unproven idea. The 201 queries are a more specific, checkable explanation.

Frequently asked questions

What is an N+1 query problem?

It is when code asks the database for a list of N items and then sends one more query for each item. That makes N+1 queries where one or two would do. It often hides inside a loop and gets slower as the list grows.

What is profiling?

Profiling means watching a program run to see which parts are called most or take the most time. A profiler is the tool that records this. It replaces guessing about what is slow with a report.

Why count queries instead of just timing the page?

Timings change every run, but the number of queries is the same each time. A count also points straight at the cause. A page that makes 201 queries for 50 orders tells you where to look.

Do I need an expensive monitoring tool?

No. A query counter in a test and one structured log line per request already give you strong evidence. Tools such as django-debug-toolbar, pg_stat_statements and py-spy help when you need more. Monitoring products add traces and dashboards, but start with what you have.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.