Module 07 · Lesson 7.5
Proving an Improvement
On this page
- What you will learn
- What counts as proof that a change made things faster
- Worked scenario: before and after for "My orders"
- Show that behaviour is unchanged
- Write down what you did not measure
- Step-by-step workflow
- Using an AI assistant to check your results
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Imagine you tell a friend you found a quicker route to work. They will ask how much quicker, and how you know. If you say "it felt faster", they will not be convinced. If you say "I drove both routes five times and the new one saved eight minutes", they will.
A performance fix needs the same kind of proof. In this lesson you will prove the fix for the slow "My orders" page of the fictional Tidewell Wholesale service. You will repeat your baseline with the same method, show that behaviour did not change, and write down what you did not measure. All data is invented.
What you will learn
- Compare before and after results using the same method as the baseline.
- Show that a faster version still returns the same results, with a test.
- Separate measured facts from the team's staging numbers, and from claims you cannot make.
- Write a results note that states what was and was not measured.
Before you start
- You finished Failure Modes, Timeouts and Retries, or you at least completed the first three lessons of this module.
- You have the files
measure.py,seed.py,history_slow.py,history_fast.pyandquery_counter.pyfrom the earlier lessons. - You can run pytest. See the pytest documentation (opens in a new tab) if you need setup help.
What counts as proof that a change made things faster
A change feels like an improvement because you worked hard on it. That is not evidence. Evidence is a comparison: the same measurement, taken the same way, before and after. If the way of measuring changes, the comparison means nothing.
- Before and after comparison
- Two measurements of the same thing with the same method. It is like weighing yourself on the same scale in the same clothes, a month apart.
- Same method
- The same request, account, environment, number of warm-up and timed runs, and the same statistics. Change one of them and you may be measuring the change in method, not in code.
- Noise
- Random variation between runs, such as a busy moment on a shared server. It can make a small difference look like an improvement or hide one. Repeat runs to see how large the noise is.
- Regression
- Something that worked before and is now broken or worse. A fix that is fast but returns different data has caused a regression.
- Regression guard
- A test that fails if the old problem comes back. For example, a test that fails if the history page uses more than two queries.
Proof has three parts. The change is faster (against the baseline). It is the same (behaviour unchanged). And it is honest (it says what was not checked). Missing any part makes the claim weaker.
Worked scenario: before and after for "My orders"
The fix has two changes: lines and products are fetched together (201 queries became 2), and the orders query has a new index. You made the baseline in Measuring Before Optimising. Now you repeat it, with the same method, on the same staging copy, at a similar quiet time.
Some of your evidence you can run yourself, and some belongs to the team's staging environment. Keep them apart.
| Measure | Before | After | Where it comes from |
|---|---|---|---|
| Queries for 50 orders (account TC7-0042) | 201 | 2 | Real: you can reproduce it with the lesson code. |
| Query plan for the orders query | Seq Scan + Sort; 18,182 rows removed by the filter | Index Scan; 50 rows read, none removed | Real: PostgreSQL plans from the earlier lesson. |
| Median time, TC7-0042 on staging | 2.4 s | 0.18 s | The team's staging measurements in this story. |
| p95 time, TC7-0042 on staging | 4.1 s | 0.31 s | The team's staging measurements in this story. |
| Target | p95 under 0.5 s | p95 under 0.5 s | Agreed before the work started. |
Counts and plans are the strongest evidence. They are the same on every run. Timings matter, because users feel time. But they depend on the machine, so they are the least repeatable. That is why the two kinds sit side by side.
The script below takes the two lists of 30 staging timings, one before and one after, and compares them with the same measure.py you used for the baseline. The lists are written into the script, so the answer repeats. They stand in for the team's two staging logs. Do not read them as your own measurements.
from measure import summarise
# The team's two staging runs, same method: 30 requests after 1 warm-up.
# Written out here so this script gives the same answer every time.
BEFORE = [
2.4, 3.2, 2.1, 2.5, 2.3, 4.6, 2.2, 2.7, 2.0, 2.4,
3.6, 2.3, 2.9, 2.4, 2.2, 4.1, 2.1, 2.5, 3.0, 2.3,
2.0, 2.8, 2.4, 3.4, 1.9, 2.2, 3.8, 2.3, 4.0, 2.6,
]
AFTER = [
0.18, 0.21, 0.16, 0.18, 0.17, 0.31, 0.19, 0.18, 0.15, 0.22,
0.18, 0.17, 0.25, 0.14, 0.18, 0.20, 0.16, 0.24, 0.17, 0.35,
0.18, 0.15, 0.27, 0.16, 0.19, 0.17, 0.26, 0.23, 0.29, 0.20,
]
TARGET_P95 = 0.5
before, after = summarise(BEFORE), summarise(AFTER)
print(f"{'':8}{'before':>9}{'after':>9}{'change':>9}")
for key in ("median", "p95"):
change = (after[key] - before[key]) / before[key] * 100
print(f"{key:8}{before[key]:>8.2f}s{after[key]:>8.2f}s{change:>8.0f}%")
print("target p95 under 0.50 s:")
print(" before:", "met" if before["p95"] < TARGET_P95 else "NOT met")
print(" after: ", "met" if after["p95"] < TARGET_P95 else "NOT met")Uses measure.py from the first lesson to compare the two runs.
before after change
median 2.40s 0.18s -92%
p95 4.10s 0.31s -92%
target p95 under 0.50 s:
before: NOT met
after: metMedian and p95 both fall by about 92 percent, which is roughly 13 times faster. The p95 of 0.31 s is under the 0.5 s target. This is the part the user cares about, because it shows the slow visits are fixed too, not just the typical one.
Show that behaviour is unchanged
Speed is worth nothing if the answer is wrong. A "My orders" page that loads in 0.2 seconds but shows missing lines or the wrong totals is a worse page. Compare the new output with the old one. This is the same idea as the characterization tests of What Characterization Tests Are: record what the code does now, and check it still does it.
The tests below run the old function and the new function on the same data and compare the results. They also pin an edge case (an account with no orders), the limit, and the query count. The last one is a regression guard.
import pytest
import history_fast
import history_slow
from query_counter import QueryCounter
from seed import seeded_connection
@pytest.fixture
def conn():
return seeded_connection()
@pytest.mark.parametrize("customer", ["TC7-0042", "TC7-0100", "TC7-9999"])
def test_new_history_matches_old_history(conn, customer):
old = history_slow.order_history(conn, customer)
new = history_fast.order_history(conn, customer)
assert new == old # same orders, same lines, same totals, same order
def test_limit_still_returns_the_latest_orders(conn):
ids = [o["order_id"] for o in history_fast.order_history(conn, "TC7-0042", limit=3)]
assert ids == [50, 49, 48]
def test_history_stays_within_two_queries(conn):
with QueryCounter(conn) as counter:
history_fast.order_history(conn, "TC7-0042")
assert counter.count <= 2Five checks. The first three compare old and new output, including an account that has no orders.
What each part does
@pytest.fixturebuilds a fresh small database for each test.@pytest.mark.parametrizeruns the same test for three accounts: the big one, a small one and one that does not exist.assert new == oldcompares everything: orders, lines, product names, totals and their order.- The limit test checks that the latest orders still come back newest first.
- The last test fails if the history ever needs more than two queries again. In Django,
assertNumQueriesor pytest-django'sdjango_assert_max_num_queriesdoes this.
============================= test session starts =============================
collecting ... collected 5 items
test_history_unchanged.py::test_new_history_matches_old_history[TC7-0042] PASSED [ 20%]
test_history_unchanged.py::test_new_history_matches_old_history[TC7-0100] PASSED [ 40%]
test_history_unchanged.py::test_new_history_matches_old_history[TC7-9999] PASSED [ 60%]
test_history_unchanged.py::test_limit_still_returns_the_latest_orders PASSED [ 80%]
test_history_unchanged.py::test_history_stays_within_two_queries PASSED [100%]
============================== 5 passed in 0.02s ==============================All five pass. A second run gave the same results. Only the time at the bottom changes.
Write down what you did not measure
Every measurement has limits. Saying so makes your result more trusted, not less. It also stops a reader from taking your number into a place it does not apply, such as production at peak time.
| Not measured | Why it matters |
|---|---|
| Production load | Staging has one tester. Production has many users at once, which shares the database. |
| Cold caches | Your runs came after a warm-up. A first visit after a restart may be slower. |
| Other endpoints | Only GET /api/orders/ was checked. Order detail and statements were not. |
| The index's cost on order writes | Every new order now updates one more index. Placing orders was not timed. |
| Accounts bigger than 1,800 orders | The biggest tested account has about 1,800 orders. Larger ones may behave differently. |
Put this list in the results note, next to the numbers. It also becomes your follow-up list. If order writes matter, time them. If production is the target, ask the platform team lead for a safe way to measure there. Here is the note.
# My orders: results (after the change)
## Change
- order_history loads lines and products together (201 queries -> 2).
- New index orders_customer_created_idx on orders (customer_id, created_at DESC).
## Method (same as the baseline)
- GET /api/orders/ as account TC7-0042 (about 1,800 orders), staging.
- 1 warm-up request, then 30 requests, one at a time, quiet time.
- Statistics: median and p95, using measure.py. Run twice; the runs agree.
## Results
| Measure | Before | After |
| Queries (50 orders) | 201 | 2 |
| Orders query plan | Seq Scan + Sort | Index Scan |
| Median (staging) | 2.4 s | 0.18 s |
| p95 (staging) | 4.1 s | 0.31 s |
Target p95 under 0.5 s: met on staging.
## Behaviour
- test_history_unchanged.py: old and new output identical for 3 accounts.
- Regression guard: history stays within 2 queries.
## Not measured
- Production load and cold caches.
- Other endpoints (order detail, statements).
- The index's cost on order writes.
- Accounts with more than 1,800 orders.
## Rollback
- Revert the code change. Drop the index with DROP INDEX if it causes trouble.The results note. Committed with the change, beside the baseline note.
Step-by-step workflow
Step 1: Re-read the baseline and the target
Open your baseline note. Copy the method exactly: request, account, environment, number of runs and statistics.
What you should see: The method, ready to repeat.
Step 2: Repeat the measurement the same way
Take the 'after' baseline on the same kind of environment at a similar time. Run it twice. Compare the two runs for noise.
What you should see: Two 'after' runs that agree.
Step 3: Compare counts and plans first
Record the query count and the query plans before and after. These are steady, so they are your strongest evidence.
What you should see: A before and after table of counts and plans.
Step 4: Prove the behaviour is unchanged
Compare old and new output for several inputs, including an empty one and an edge. Add a regression guard for the thing you fixed.
What you should see: Passing tests, with their output saved.
Step 5: List what you did not measure
Write each limit: load, caches, other paths, side effects such as write cost, and size beyond what you tested.
What you should see: A 'not measured' list that doubles as follow-ups.
Step 6: Write the results note and link it in the pull request
Put the note with the code. Link it from the pull request description, as in Writing a Reviewable Pull Request. Add a rollback line.
What you should see: A reviewable change with proof and a way back.
- Same method
As the baseline
- Repeat twice
Check noise
- Counts and plans
Steady evidence
- Behaviour tests
Old equals new
- Not measured
Honest limits
- Results note
Linked in the pull request
Faster, the same, and honest: the three parts of proof.
Using an AI assistant to check your results
An assistant makes a good sceptical reader of your results note. It can spot a claim that is stronger than the evidence. It is also happy to write a flattering summary, and this is where care is needed.
- Give it: your results note and the method. Remove real customer data.
- Ask it for: claims that go beyond the evidence, missing limits and noise questions. Ask it to mark each statement as measured, scenario or claimed.
- Watch for: 'about 13 times faster in production'. You did not measure production, so that sentence must go.
- Do not: let it round up, or write timings you never recorded.
Conclusion and your next step
You can now prove a performance fix. You repeated the baseline with the same method, compared counts and plans, showed that behaviour did not change, and wrote down what was not measured. That is what makes a result worth trusting.
Your next step: performance is one way a system can go wrong. Security is another. Continue with the module Security Review and Hardening and review the same service for risks, starting with a focused list of findings.
For more, read Load Testing with AI: Generating Realistic Performance Test Scenarios and the module overview Performance and Reliability Investigation.
Reusable prompt
Results note reviewer
Asks an assistant to challenge a performance results note: which claims are measured, which are scenario numbers, and which go beyond the evidence.
Below is a results note for a performance fix in a service called tidewell-orders (fictional). Act as a sceptical reviewer. Use ONLY this note. Do not add numbers.
Results note:
- Change: order_history loads lines and products together (201 queries -> 2). New index on orders (customer_id, created_at DESC).
- Method: GET /api/orders/ as account TC7-0042 (about 1,800 orders), staging, 1 warm-up then 30 requests, run twice.
- Results: median 2.4 s -> 0.18 s; p95 4.1 s -> 0.31 s; target p95 under 0.5 s.
- Query plan: Seq Scan + Sort -> Index Scan.
- Behaviour: old and new output identical for 3 accounts (pytest).
- Draft summary line: "The orders page is now 13 times faster for all customers in production."
Please give me:
1. For each statement in the note, label it: measured by a repeatable method, scenario number, or claim.
2. Claims that go beyond the evidence, and a corrected wording for each.
3. Things that are missing, such as limits and side effects.
4. Questions a reviewer would ask about noise and repeatability.
Mark any guess as (unverified).Show the reusable template
Replace each {{placeholder}} with your own details.
Below is a results note for a performance fix in {{system_description}}. Act as a sceptical reviewer. Use ONLY this note. Do not add numbers.
Results note:
{{results_note}}
Please give me:
1. For each statement in the note, label it: measured by a repeatable method, scenario number, or claim.
2. Claims that go beyond the evidence, and a corrected wording for each.
3. Things that are missing, such as limits and side effects.
4. Questions a reviewer would ask about noise and repeatability.
Mark any guess as (unverified).Expected output and limitations
A labelled list of statements, a short list of overclaims with safer wording, a list of missing limits and a few reviewer questions. It should not invent new numbers.
1. Labels
- 201 -> 2 queries: measured (repeatable count)
- Seq Scan + Sort -> Index Scan: measured (plan)
- median 2.4 -> 0.18 s, p95 4.1 -> 0.31 s: staging measurements; label them as such
- identical output for 3 accounts: measured (tests)
- "13 times faster for all customers in production": claim
2. Overclaims
- "in production": not measured. Say "on staging, for account TC7-0042".
- "for all customers": only one large and one small account were compared. Say "for the accounts tested".
3. Missing
- Production load, cold caches, other endpoints
- Cost of the new index on order writes
- Accounts bigger than about 1,800 orders
4. Reviewer questions
- How far apart were the two "after" runs?
- Was staging idle during both runs?
- (unverified) Does the 0.18 s include the time to render the page, or only the API?Limitations to keep in mind
- The assistant reviews wording. It cannot re-run your measurements or confirm them.
- It may soften or strengthen claims to sound balanced. Check each corrected line against your own numbers.
- It may add its own figures when asked to improve the note. Delete any that you did not measure.
- It cannot know what your target means to the business. That is a decision for people.
Common errors and how to fix them
Comparing measurements taken different ways
Why it happens: The 'after' run used a different account, environment or number of requests, often by accident.
Fix: Copy the method from the baseline note word for word, and record any difference.
Claiming speed without checking the output
Why it happens: The page got faster, so nobody looked at what it returned.
Fix: Compare old and new output for several inputs, including an empty one. Add a test so the comparison stays.
Presenting a staging number as a production fact
Why it happens: The number is exciting and the note does not say where it came from.
Fix: Label each number with its environment and method, and list production under 'not measured'.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Prove one improvement in your own repository
Take a performance change you made in this module, or a small one you make now, in a repository or sample application you may change. Write a results note that proves it.
You will need
- Your baseline note from the first lesson, with its method.
- The changed code and the old version, or a recorded output of the old version.
- A way to take the same measurement again, and a test runner.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- If you have no old code to compare, record its output in a file before you change anything.
- If your timings are noisy, take more runs and compare the median and the p95, not one run.
- If you use an assistant, ask it to label each claim as measured or claimed.
Show a model answer
A strong answer reads like the results note in this lesson. It repeats the baseline method, shows counts, plans and timings side by side and labels where each came from. It proves the output is unchanged with a test and keeps a guard. It says plainly what was not measured. A weak answer reports a single 'after' time, uses a different method and never mentions limits.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. A comparison needs the same method on both sides. With a different number of runs and no warm-up, the difference may come from the method. Swapping the median for the mean does not fix that.
Show the answer and explanation
Answer: B. Speed has value only if the answer is still right. A fast but wrong page is worse than a slow correct one. Speed matters, and comparing output does not need to be slow.
Show the answer and explanation
Answer: B. A result belongs to the conditions it was measured in. 'Probably similar' is a guess, not a measurement. Hiding the limits makes the note less trustworthy, not more.
Frequently asked questions
How do I prove my code change made something faster?
Measure the same thing the same way before and after. Use a warm-up and enough runs, and compare the median and the p95. Back it up with steady evidence such as query counts and query plans, and show that the output did not change.
What is a regression test?
It is a test that fails if something that used to work, or used to be fast, breaks again. For performance, a common kind is a query budget: a test that fails if a page makes more queries than allowed.
Why do I need to say what I did not measure?
Every result holds only for the conditions you tested. Listing the gaps, such as production load or write speed, stops people trusting the number where it does not apply. It also gives you a ready list of follow-up checks.
Why is a count of queries better evidence than a timing?
A count is the same on every run, so anyone can repeat it and get the same answer. Timings change with the machine and the moment. Use both: counts as steady proof and timings to show what users feel.
- 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.
- statistics — Mathematical statistics functions(opens in a new tab)
Python Software Foundation · Official documentation · The standard-library module behind the median and the mean.
- Using EXPLAIN(opens in a new tab)
PostgreSQL Global Development Group · Official documentation · How to read the before and after query plans.
- Monitoring Distributed Systems(opens in a new tab)
Google · Why percentiles matter when you report speed.
- pytest documentation(opens in a new tab)
pytest-dev · Official documentation
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.