Trace a request through the booking service, map what each part is responsible for, and make a slow availability lookup fast without changing a single answer.
Outcome: Trace behaviour, identify responsibilities and explain a relevant algorithm or complexity trade-off.
Note
Reading as a visitor
Everything in this lesson is free to read. Sign in and enrol to answer the questions and record your progress.
Trace an HTTP request from the server entry point through routing, data access and domain logic to the response.
Describe what each module of the booking service is responsible for, and find where a given rule lives.
Explain the time complexity of the availability calculation and why sorted input allows a single pass.
Use an AI coding agent to explore code while checking its claims against the source.
Make a performance change that keeps every existing result the same, and show it with tests.
Prerequisites
Reading TypeScript or modern JavaScript, including async and await.
Basic SQL: SELECT with WHERE and ORDER BY, and what an index is for.
Running commands in a terminal and calling an HTTP API with curl.
Big-O notation at the level of O(n), O(n log n) and O(n²).
Concepts
Read with a question in mind
An unfamiliar codebase is easier to understand when you follow one behaviour from end to end than when you read files in directory order. Pick a request, find where it enters, and at every step ask two questions: what does this code receive, and what does it hand on? The answers give you a call path and, almost for free, a map of responsibilities.
In the booking service, the path for GET /resources/:id/availability is short:
Step
File
Responsibility
Start-up
src/server.ts
Creates the connection pool, applies migrations, starts listening
App assembly
src/app.ts
Sets the error format and registers the route modules
Route handler
src/routes/resources.ts
Validates from, to and , loads the resource and its bookings
Worked example
This walk-through applies the technique to a different part of the booking service: how POST /bookings decides that a new booking clashes with an existing one, and what that check costs as a resource builds up history. It uses the same code you have in the lab, so you can repeat every step.
1. Start with a precise question
"How does the booking code work?" is too broad to answer well, by you or by an agent. A better question is: when two people ask for overlapping times on the same resource, which code refuses the second request, and how much work does that refusal take when the resource has years of bookings?
A prompt to an agent might be:
Trace POST /bookings from src/server.ts to the INSERT. For each step, give the file, the function
and the line range, and say what that step is responsible for. Do not suggest changes yet.
Suppose the answer says that the overlap check happens in assertBookable in src/rules.ts. That is a plausible guess, because rules.ts holds the booking rules, but open the file and it is not there: assertBookable checks the period, the slot boundaries and the opening hours, and never touches the database. The overlap check is a SQL query in the route handler. Correcting a claim like this early is the point of asking for file and line references.
2. Write down the path and the responsibilities
Step
Concept questions
Sign in and enrol to answer and save your progress.
Exercise
The situation
Your workspace holds the booking service described in README.md. Users of a busy resource report that checking its availability for the next year or two takes so long that the whole service stops responding. The answers are correct; they are just slow. Nobody on the team wrote this code, and the person who did has moved on.
Your job is to understand how GET /resources/:id/availability works, then make it fast for long ranges and large booking histories without changing any result.
Steps
Trace before you touch anything. Follow the request from src/server.ts to the response. For each step, note the file, the function and what it is responsible for. Work out how many times each booking is examined for one request. The reflection at the end of the lesson asks you to describe this path.
Set up data and measure. Reset the database and start the service in one terminal:
npm run db:reset
npm start
Then load a resource with a long booking history. Save this as /tmp/load.sql; it creates a resource with 5-minute slots and 20,000 bookings, leaving a 150-minute gap after every 1,000 slots:
WITH r AS (
INSERT INTO resources (name, timezone, open_minute, close_minute, slot_minutes, price_cents_per_hour)
VALUES ('Load-test workstation', 'UTC', 0, 1440, 5, 1200)
RETURNING id
)
INSERT INTO bookings (resource_id, user_id, starts_at, ends_at, price_cents)
SELECT r.id, 1,
timestamptz '2027-01-04 00:00Z' + n * interval '5 minutes',
timestamptz '2027-01-04 00:00Z' + (n + 1) * interval '5 minutes',
100
FROM r, generate_series(0, 19999) AS n
WHERE n % 1000 >= 30;
Reflection
Recorded for you to look back on. It is not graded and does not by itself show understanding.
Prompt: Describe the path a GET /resources/:id/availability request takes through the code, from the moment Fastify receives it to the JSON response: which files and functions it passes through, what each is responsible for, and where the time went before your change. If you used an agent to explore, which of its explanations did you have to check or correct?
Notice what is not on the path. src/rules.ts (opening hours, slot boundaries, pricing) is used when a booking is made, not when availability is calculated, and the comment on freeWindows says so. Free windows are the gaps between bookings, not a list of bookable slots. Facts like this, written down with the file and line where you found them, are the most useful output of a reading session.
What the calculation does
Free time is the complement of busy time inside the range from from to to. Given the confirmed bookings that overlap the range, the free windows are the gaps between them, plus the gap before the first and after the last, keeping only gaps of at least min_minutes. Bookings are half-open intervals: a booking from 09:00 to 10:00 and another from 10:00 to 11:00 leave no gap, which is also why back-to-back bookings are allowed.
There are two broad ways to compute this.
Search at every step. Start a cursor at from. At each step, look through every booking for any that covers the cursor (jump to the latest end among them) or, if none does, for the earliest booking that starts after the cursor (the time up to it is free). Each step costs O(n) for n bookings, and the number of steps grows with n, so the total is O(n²). It needs no assumption about order, which is what makes it tempting to write.
Sort, then sweep once. If the bookings are sorted by start time, every booking you have already passed lies behind the cursor, so the next one in the list is the only candidate. One pass is enough: for each booking, if it starts after the cursor, the gap is free; then move the cursor to the later of its current position and the booking's end. Taking the later of the two, rather than simply the booking's end, keeps the sweep correct even if one period sits inside another. Sorting costs O(n log n) and the sweep O(n).
The difference is not academic. At 20,000 bookings, n² is 400 million comparisons; at 200,000 it is 40 billion, while n log n is about 3.5 million. Doubling the data roughly quadruples the time of the first approach and roughly doubles the second.
Let the database do the ordering
Where the sorting happens matters as well. The schema in db/migrations/001_init.sql has an index bookings_resource_time on (resource_id, starts_at). A B-tree index keeps its entries in order, so for a query with WHERE resource_id = $1 and ORDER BY starts_at, PostgreSQL can read the index in order and return the rows already sorted, with no separate sort step. The same index lets it skip bookings that start after to. Filtering in SQL also means the application receives only the bookings that can affect the answer, instead of years of history that it then has to discard. With rows arriving in order, the application's share of the work is one O(n) pass over the relevant rows.
Check this rather than assume it. EXPLAIN ANALYZE shows the plan PostgreSQL actually chose: an index scan, a bitmap scan followed by a sort, or a sequential scan. The planner decides from table statistics, so a plan that looks right for ten rows can change at a hundred thousand.
Why one slow endpoint hurts every endpoint
The service is a single Node.js process, and your JavaScript runs on one thread. A synchronous loop that takes forty seconds blocks the event loop for forty seconds: no other request is handled, not even GET /health. A quadratic loop in one endpoint becomes an outage for all of them.
Working with an agent
AI coding agents are good at the first pass of exploration: listing entry points, summarising modules, drafting a call path. They are less reliable on the details that decide correctness. Typical failures are a confident description of a function the agent has not opened, a complexity estimate that misses a loop nested inside another loop, and an "optimisation" that quietly changes results, such as dropping the comparison when moving the cursor or reporting back-to-back bookings as a zero-length gap.
Ask for claims you can check: "Trace GET /resources/:id/availability and cite the file and line for each step", or "How many times is each booking examined, and why?". Then open the cited lines yourself. Before changing anything, ask the agent to write tests that pin down the current results, including the awkward cases, and run them against the unchanged code. Only then optimise, keeping those tests green. A read-only planning mode, such as plan mode in Claude Code or the Plan agent in OpenCode, suits the exploration stage, because nothing is edited while you read.
Where
Responsibility
Body validation
Fastify schema on the route in src/routes/bookings.ts
Rejects unknown fields and malformed times; src/app.ts turns the failure into 400 VALIDATION_FAILED
Authentication
requireUser in src/auth.ts
Resolves the bearer token to a user, or 401 UNAUTHENTICATED
Transaction
transaction in src/db.ts
One connection, BEGIN … COMMIT, rollback on any error
Resource lock
SELECT … FOR UPDATE in the handler
Makes concurrent requests for the same resource take turns
Rule checks
assertBookable in src/rules.ts
Period, slot boundaries, opening hours in the resource's time zone
Overlap check
SQL query in the handler
409 SLOT_UNAVAILABLE if a confirmed booking overlaps
Insert and response
Handler, then bookingView
Prices the booking with priceCents, inserts it, returns 201
Two things stand out once the table exists. Validation happens before authentication, because Fastify validates the body before the handler runs, so a malformed request without a token gets 400 rather than 401. And the resource lock is what makes the overlap check safe under concurrency, which is a separate responsibility from the check itself.
3. Understand the algorithm
The overlap query is:
SELECT 1 FROM bookings
WHERE resource_id = $1 AND status = 'CONFIRMED' AND starts_at < $3 AND ends_at > $2
LIMIT 1
with $2 and $3 the new booking's start and end. Two half-open intervals overlap exactly when each starts before the other ends. A booking that ends at 10:00 does not overlap one that starts at 10:00, because ends_at > $2 is false, which is why back-to-back bookings succeed. Cancelled bookings are excluded by the status filter.
4. Measure the cost instead of guessing
An agent, or a colleague, might say: "There is an index on (resource_id, starts_at), so this check is a quick index lookup." Test the claim. On a copy of the database with about 200,000 five-minute bookings on one resource and some 34,000 on others, asking about an hour after all of them, with the values written in (timings and cost figures vary by machine; costs are omitted here):
EXPLAIN ANALYZE SELECT 1 FROM bookings
WHERE resource_id = 7 AND status = 'CONFIRMED'
AND starts_at < '2029-02-01T10:00Z' AND ends_at > '2029-02-01T09:00Z' LIMIT 1;
Limit (actual time=8.098..8.099 rows=0 loops=1)
-> Seq Scan on bookings (actual time=8.097..8.098 rows=0 loops=1)
Filter: ((starts_at < ...) AND (ends_at > ...) AND (resource_id = 7) AND (status = 'CONFIRMED'::text))
Rows Removed by Filter: 233353
PostgreSQL read every row in the table. The reason is in the index: it is ordered by starts_at, so the condition starts_at < end only bounds the scan from above. Every earlier booking of the resource, its whole history, also starts before the new end and has to be examined, because ends_at is not in the index. For a slot after all existing bookings, which is the normal case, the planner judged a sequential scan cheaper than reading most of the index. The cost of each new booking grows with the history of the resource.
5. Look for a property that bounds the work
The rules supply one. MAX_BOOKING_MS in src/rules.ts limits a booking to 12 hours, so any booking that overlaps the new one must start less than 12 hours before the new start. Adding that lower bound gives the index both ends of a range:
AND starts_at > timestamptz '2029-02-01T09:00Z' - interval '12 hours'
Limit (actual time=0.008..0.008 rows=0 loops=1)
-> Index Scan using bookings_resource_time on bookings (actual time=0.007..0.007 rows=0 loops=1)
Index Cond: ((resource_id = 7) AND (starts_at < ...) AND (starts_at > (... - '12:00:00'::interval)))
Filter: ((ends_at > ...) AND (status = 'CONFIRMED'::text))
From 8 ms to 0.008 ms, and the cost no longer depends on how much history the resource has.
6. Weigh the trade-off before changing anything
The faster query now depends on a rule enforced in application code. If the 12-hour limit were raised, or rows were inserted without going through assertBookable, the bounded query would silently miss overlaps, and the service would accept double bookings. A more robust option is a database-level guarantee, such as an exclusion constraint on a time range, at the cost of a migration and a less familiar feature. At today's volumes, 8 ms is acceptable. Understanding the code does not oblige you to change it: the outcome of this investigation is a note recording the cost, why it grows, and the two ways to bound it.
The same habits carry over to the exercise: trace with file and line, state the algorithm in a sentence, measure with real data, and treat "it uses the index" as a claim to check.
Run it with psql "$DATABASE_URL" -f /tmp/load.sql, or, if psql is not available, with Node and the pg package the project already has:
Load a second resource with generate_series(0, 39999) and time it the same way (it gets id 5). Compare the two timings with what each complexity class predicts. Do not try 200,000 bookings against the starter: the request would hold the server for minutes.
Pin down the current behaviour with tests. Before optimising, add tests under test/ that record what the endpoint returns today. Cover at least: a booking that starts before from and one that ends after to, back-to-back bookings, a cancelled booking (ignored; this starter has no cancel endpoint, so set its status with SQL through db() from useTestApp()), a min_minutes that filters out short gaps, and a range with no bookings at all. test/resources.test.ts shows how to create bookings and call the endpoint with app().inject(). Run them against the unchanged code: they should pass now and keep passing after your change.
Make it fast. Change the code so that the work grows roughly linearly with the bookings in the requested range. Keep the response format, the validation and every result exactly as they are.
Verify. Run npm run verify (type check and tests). Restart the service, repeat the timing requests, and compare the answers with the ones you saved, for example with diff /tmp/before-20k.json /tmp/after-20k.json. Then load 200,000 bookings with generate_series(0, 199999) and n % 10000 >= 30, and check that the request returns quickly and the windows look right.
Constraints
Do not change package.json or package-lock.json, and do not add dependencies. The assessment runs your code with the project's original dependencies and does not start a submission whose lockfile differs.
Do not edit db/migrations/001_init.sql or any other applied migration: start-up fails if an applied migration changes. You should not need a schema change; if you add one, put it in a new migration file.
Keep the service startable with node src/server.ts, keep GET /health, and keep reading DATABASE_URL and PORT.
Results must reflect the bookings in the database at the moment of the request. Caching answers between requests is not a fix.
What Check work assesses
Check work takes a snapshot of your workspace's source files and assesses it outside the lab. The platform starts your service with node src/server.ts against its own fresh database, loads its own data (not your seed data or the bookings you loaded) and calls the API over HTTP. Nothing your code prints and nothing in your own tests is trusted, so printing PASS or editing tests changes nothing.
AC1 compares availability answers with the expected windows in the cases listed in step 3.
AC2 checks that creating, listing and reading bookings and resources still behave as documented.
AC3 loads 200,000 bookings with 5-minute slots and a few known long gaps, asks for windows of at least 120 minutes over the whole range, and requires the correct answer within 10 seconds. It runs last.
The checks do not assess the style of your code, your own tests or your reflection; the lesson lists what is not assessed. Your reflection is recorded but not graded.
Tools
You can do this exercise with Claude Code, OpenCode or OpenHands in the lab. Whichever you use, ask it to explain and cite before it edits, and run the measurements yourself.
Acceptance criteria
AC1Availability results are unchanged, including bookings that span the range edges, back-to-back and cancelled bookings, min_minutes and ranges with no bookingsVerified behaviour
AC2Booking and resource endpoints still workVerified behaviour
AC3Availability over 200,000 bookings answers correctly within 10 secondsVerified behaviour
Verified behaviour is checked by running your submitted work from outside the lab. A structure check confirms that something is present and in the expected format; it does not prove it is correct.
Not assessed
The readability, structure and style of your code.
Your own tests: the assessment does not run them or measure what they cover.
The performance of endpoints other than availability, and memory use.
Your account of the request path: the reflection is recorded, not graded.
Hints
Try the exercise first. Each hint gives away a little more than the one before.
Check your work
Submit your work from the lab's Check work panel. Hidden checks run your submitted code from outside the lab; your own test output is never taken as a result. You can revise and resubmit.