Guides

Slow queries and list performance audit

Ranked list of the slowest database queries and list endpoints in pack app-campus.site.2, with exact file locations, the pattern found in each one, and a ready to ship fix for the worst offender. Use the replacement SQL below together with Query 1, Query 2, Query 3A and Query 3B in Owner dashboard metrics and SQL. The median in that guide is Query 3A and Query 3B, not an unbounded Query 4.

Ranked slowest queries

Rank 1 is the worst offender and the fix below replaces it. Ranks 2 to 5 are shipped as notes in the same replacement section, so a builder fixes the worst path first and the next scans in the same change. Call chain for Rank 1 and Rank 2: Reports owner dashboard for one college workspace loops one week at a time, per week it prepares the combined count query, the helpful rate query, the median count query and the median middle-rows fetch, each filtered by tenant_id, is_test and created_at range, and reads the covering index range for that week. Before the fix the same dashboard loop prepared 6 queries per week. After the fix it prepares 4 per week.

Ranked slow queries by payload, scans per request, and unbounded rows
RankQuery and exact file locationPatternFix in this page
1Former Query 4 time to first answer median, now Query 3A and Query 3B in public/guides/owner-dashboard-metrics.html, Query 3A and Query 3B sectionsUnbounded result set in the former form. The former query returned created_at and first_answer_at for every answered question in the week, then code sorted every row in JavaScript to take the median. Rows transferred grew with answered count and the query ran once per week in the range.Replacement in the next section. One count query in Query 3A, then a fetch of at most 2 middle rows with LIMIT and OFFSET in Query 3B. Payload falls from N rows to 2 rows plus 1 count per week.
2Owner dashboard Query 1, questions, outcomes, active users, and follow-ups in one scan, and Query 2, in public/guides/owner-dashboard-metrics.html, Query 1 and Query 2 sectionsRepeated queries on the same workspace data in the former form. Separate scans of questions for the same tenant_id, is_test and created_at range returned questions asked, answered counts, distinct signed in users and follow-up counts, and a separate answers scan returned helpful counts for the same range.Combined query in the next section. One questions scan per week returns questions asked, answered, not answered, handed off, weekly active users and follow-up counts together, and one answers scan returns helpful and not helpful counts, both on the covering index. Query 2 stays separate because ratings live on the answers table.
3Sample list in APPKIT.md, function list, count query and items query with instr(lower(title), lower(?2))Repeated full scan. The count query and the items query each scan the same filtered rows, and lower on the column prevents index use for the text match. The pattern is a sample shape, so every module copied from it inherits the double scan.Keep the count plus page shape for total and hasMore, keep tenant_id in both queries, and do not copy the lower instr pattern for a new endpoint. Use the token rule in List pagination, sorting, and filtering and the covering index in the next section.
4System view Query 2, per-workspace counts behind answers per workspace, in public/reports.html, Ready-to-ship queries for system view sectionUnbounded group by. SELECT tenant_id with COUNT and GROUP BY tenant_id and ORDER BY questions DESC has no LIMIT and no tenant_id filter, so it scans every non-test question in the week across all colleges.Bounded grouped query in the next section. Run only in the system governance reporting path, use idx_questions_test_created_tenant, and add LIMIT 200 to the grouped query. The row count is workspaces, not questions, so a limit of 200 does not cut a college.
5Owner dashboard Query 4, asker retention cohort and later, in public/guides/owner-dashboard-metrics.html, Query 4 sectionRepeated distinct scans. Two SELECT DISTINCT user_id scans of the same table cover the cohort week and the later week, with the same tenant_id, is_test and user_id filters.Keep the CTE shape, it already returns only cohort and retained counts, and use idx_questions_tenant_test_created_cover, which covers tenant_id, is_test, created_at and user_id. Do not expand it to return user rows.
6Client lists in public/my-answers.html, public/guides/index.html and public/site.js terminology filterNo N+1 pattern found. Each list reads one browser-local store or one page corpus, renders rows in the browser, and sends no per-row request. No database query runs per row.No change. Keep the 120 millisecond pause and the count status already stated in List pagination, sorting, and filtering.

No missing index was found for the ranked workspace queries. The covering indexes are already listed in Owner dashboard metrics and SQL under Indexes required for these queries. The fix below uses idx_questions_tenant_test_created_cover, so Query 1, Query 3A, Query 3B and Query 4 answer from the index range for tenant_id, is_test and created_at, and the count and the middle-rows fetch answer from the index range for tenant_id, is_test and created_at. Single-purpose indexes named in earlier drafts of this page, idx_questions_tenant_test_created_first_answer, idx_questions_tenant_test_created_outcome and idx_questions_tenant_test_created_user, are dropped in that same migration and must not be created or referenced. Do not add idx_questions_tenant_test_created_first_answer, idx_questions_tenant_test_created_outcome or idx_questions_tenant_test_created_user as separate indexes. Those single purpose indexes are dropped in the same migration in Owner dashboard metrics and SQL. Do not use a separate first_answer index, because that index is dropped in the same migration in Owner dashboard metrics and SQL.

Ready to ship fix for Rank 1: time to first answer median

Use Query 3A and Query 3B in Owner dashboard metrics and SQL with the two queries below, in that order, for one week at a time. Keep tenant_id = ?1, is_test = 0, has_citation = 1 and the week bounds. Write each query as one plain string per prepare call and bind values with ?1, ?2 and so on.

Query 3A: count first

SELECT COUNT(*) AS n FROM questions WHERE tenant_id = ?1 AND is_test = 0 AND has_citation = 1 AND first_answer_at IS NOT NULL AND created_at >= ?2 AND created_at < ?3;

Bind ?1 to the workspace, ?2 to week start and ?3 to week end in the stored time form. When n is 0, show no answered questions in this range for the median and run no second query. When n is greater than 0, compute offset in code as the integer part of (n minus 1) divided by 2, and bind that offset as ?4 in Query 3B.

Query 3B: fetch only the middle rows

SELECT created_at, first_answer_at FROM questions WHERE tenant_id = ?1 AND is_test = 0 AND has_citation = 1 AND first_answer_at IS NOT NULL AND created_at >= ?2 AND created_at < ?3 ORDER BY (julianday(first_answer_at) - julianday(created_at)) ASC, id ASC LIMIT 2 OFFSET ?4;

When n is odd, Query 3B returns 1 row and the median is elapsed minutes for that row. When n is even, Query 3B returns 2 rows and the median is the average of elapsed minutes for the 2 rows. Elapsed minutes for a row is first_answer_at minus created_at, computed in code from the 2 returned timestamps. Show n beside the median, as the guide already requires. The id ascending tie break keeps a page boundary stable, as in List pagination, sorting, and filtering.

  • Payload per week falls from n rows to at most 2 rows plus 1 count. No JavaScript sort of every row runs.
  • Result matches the former unbounded median, the old Query 3 result, for the same week, workspace, assistant and channel filters, because the order is elapsed time ascending and the offset selects the middle of that order.
  • Exclusions stay the same. Test sessions, not-known messages, handoffs with no sourced answer and questions with a missing time stay out, and the excluded count is shown where the screen can count it.
  • Confirm the table name and every column name once in migrations/0002_app.sql in the shipped build, as the guide already states, then use those names in both queries. Field logic does not change when a name is confirmed.
  • Use idx_questions_tenant_test_created_cover from the index list in Owner dashboard metrics and SQL. That covering index already includes has_citation, first_answer_at and created_at after tenant_id and is_test, so the count and the middle-rows fetch answer from the index range for tenant_id, is_test and created_at, with only the answered rows in the week sorted for the median. Add that covering index in a new migrations/01NN file in the app build and drop the five redundant single purpose questions indexes in that same migration with IF EXISTS, after the covering index is created, including idx_questions_tenant_test_created_first_answer. Add no single-purpose first_answer index, because Owner dashboard metrics and SQL drops idx_questions_tenant_test_created_first_answer in the same migrations/01NN file after the covering index is created, and do not edit migrations/0002_app.sql or migrations/0001_core.sql. Do not create a separate first_answer index.

Combined query for Rank 2, same change

Use combined Query 1 for questions counts and Query 2 for helpful counts for one week. Query 1 already combines questions asked, answered, not answered, handed off, weekly active users and follow-up counts in one scan. Query 1 is one scan per week. Query 2 stays separate because ratings live on the answers table. Retention Query 4 stays separate because it reads two different weeks. Do not add a second scan for distinct signed in users.

SELECT COUNT(*) AS questions_asked, SUM(CASE WHEN has_citation = 1 THEN 1 ELSE 0 END) AS answered, SUM(CASE WHEN outcome = 'not_answered' THEN 1 ELSE 0 END) AS not_answered, SUM(CASE WHEN outcome = 'handed_off' THEN 1 ELSE 0 END) AS handed_off, COUNT(DISTINCT CASE WHEN user_id IS NOT NULL THEN user_id END) AS weekly_active_users, SUM(CASE WHEN turn_index >= 2 THEN 1 ELSE 0 END) AS followup_questions FROM questions WHERE tenant_id = ?1 AND is_test = 0 AND created_at >= ?2 AND created_at < ?3;

Answered share is answered divided by questions_asked, unanswered rate is not_answered divided by questions_asked, handoff rate is handed_off divided by questions_asked, and follow-up share is followup_questions divided by questions_asked, with each numerator and denominator shown. Weekly active users is weekly_active_users, and questions per active user uses that count from this same scan with both counts shown. Use idx_questions_tenant_test_created_cover, which already includes outcome, has_citation and turn_index after tenant_id, is_test and created_at, and covers has_citation, outcome, user_id, turn_index and first_answer_at. Do not add idx_questions_tenant_test_created_outcome, because Owner dashboard metrics and SQL drops that single-purpose index in the same migrations/01NN file, and add turn_index to the covering index only when turn_index is stored and follow-up share is shipped, as that guide states. Do not create a separate outcome index or a second scan for distinct signed in users. When turn_index is not stored, remove only that one term from the SELECT list and do not run a second questions query to replace it.

Bounded grouped query for Rank 4, same change

Replace the unbounded system-view group-by with the query below. Run it only in the system governance reporting path. Bind ?1 to week start and ?2 to week end in the stored time form. This query has no tenant_id filter by design and returns counts grouped by tenant_id only, with no question text, so it must never be run in a workspace path that is scoped to one college.

SELECT tenant_id, COUNT(*) AS questions_asked FROM questions WHERE is_test = 0 AND created_at >= ?1 AND created_at < ?2 GROUP BY tenant_id ORDER BY questions_asked DESC LIMIT 200;

Use idx_questions_test_created_tenant, which covers is_test, created_at and tenant_id for this group-by without a tenant_id filter. The LIMIT bounds the grouped result to workspace rows rather than question rows, so the payload no longer grows with the number of questions in the week. Keep the same week bounds, test exclusion and college-local week rule as the workspace queries above, and show the week start, week end and time basis beside the counts.

Before and after: query counts and rows transferred

Before and after for the main dashboard cards, excluding retention Query 4 which reads two different weeks and is unchanged
Measure, per week, N rows in the weekBeforeAfter
Prepares for the main cards6 prepares: old Queries 1, 2, 3, 4, 5, and 74 prepares: Queries 1, 2, 3A, and 3B
Questions index entries readAbout 5 times N: four full week scans plus the median scanAbout 2 times N: one combined scan plus the bounded median count and middle-rows fetch over answered rows only
Rows transferred for the medianN answered rows per week, sorted in JavaScriptAt most 2 rows plus 1 count per week, ordered in the database with no JavaScript sort
Example, N = 1000, 13 weeksAbout 65000 index entries and 78 preparesAbout 26000 index entries and 52 prepares. Saving about 39000 index entries, or 60 percent, and 26 prepares per 13 week trend. Median rows transferred fall from about 13000 answered rows to 26 rows, a 99.8 percent reduction.

Example only. The arithmetic uses example row counts to show the method. It does not state a measured size for a college workspace in production.

Checks before you ship the fix

Run each check in a test college workspace. If a check fails, fix it before you publish.

  • For a week with 0 answered questions, Query 3A returns 0, Query 3B does not run, and the screen shows no answered questions in this range for the median, not zero minutes.
  • For a week with an odd answered count, Query 3B returns 1 row. For an even count, Query 3B returns 2 rows. The median from those rows matches the median from the former unbounded rows, the old Query 3 rows, for the same week, workspace, assistant and channel filters.
  • Bytes transferred per week fall from n rows to at most 2 rows plus 1 count for the median, and prepares per week fall from 6 to 4 for the main cards. Scans per week fall from 3 to 1 for Queries 1, 2 and 7 combined. Questions index entries read fall from about 5 times N to about 2 times N per week. For N equals 1000 for 13 weeks, index entries fall from about 65000 to about 26000, saving about 39000 entries or 60 percent, and median rows transferred fall from about 13000 rows to 26 rows, a 99.8 percent reduction. Example only. The count and middle-rows fetch keep tenant_id in the index range and run no JavaScript sort of every row.
  • Every workspace query filters by tenant_id, test sessions are excluded and labeled as excluded, and a record from another college never appears in items or in total.
  • Every index named in the shipped SQL is present after the migrations/01NN file runs, the covering index idx_questions_tenant_test_created_cover is used for workspace queries, idx_questions_test_created_tenant is used only for the system-view group-by, and no dropped single-purpose index is created or referenced.
  • The Rank 4 grouped query returns at most 200 workspace rows for the week and no question text, and the same counts are shown when the list behind a rate is opened for one workspace.
  • Each card opens the filtered list behind it with the same workspace, assistant, channel and date range, as stated in Read reports.

Follow Owner dashboard metrics and SQL for the full metric definitions, List pagination, sorting, and filtering for the list contract, and Reports for the list behind any number.

Ship the bounded median first

Replace Query 3 with the Query 3A count plus Query 3B middle-rows fetch, use combined Query 1 with weekly_active_users, bound the system-view group-by, and confirm the median and the counts still match.