smartyfy.mrindigi.com

Databases & SQL Master Course — 157. Observability and Slow Queries

Lesson 157 Observability and Slow Queries

Prerequisites and objectives

Complete restore verification and basic aggregation. You will choose metrics that distinguish workload cost, tail latency, errors, and connection waiting; analyze a fictional diagnostic sample; and explain what a query plan can and cannot prove without exposing sensitive SQL parameter values.

Measure a defined boundary

A user-visible request can spend time waiting for a pool slot, executing database work, fetching results, transforming rows, and sending a response. A single duration labeled query time is ambiguous unless its start and end points are documented. Compare like boundaries before deciding that a changed number means the database became slower.

The table below contains invented diagnostic observations for teaching, not measurements from a running application. For simplicity, each elapsed duration equals database time plus pool wait. Real instrumentation may include additional stages or overlapping work. The SQLite queries analyzing this sample were executed; the sample durations themselves are deliberately fictional.

Use stable query identifiers that represent reviewed templates. Routine metrics need not contain raw SQL with private values. A query key, outcome category, duration, row count, and correlation identifier can support investigation while reducing unnecessary data exposure. Even normalized SQL or error messages may contain sensitive context, so review the actual logging configuration.

CREATE TABLE lab_metric157(id INTEGER PRIMARY KEY,query_key TEXT NOT NULL,elapsed_ms INTEGER NOT NULL,db_ms INTEGER NOT NULL,pool_ms INTEGER NOT NULL,outcome TEXT NOT NULL);
INSERT INTO lab_metric157 VALUES(1,'lookup',5,3,2,'ok'),(2,'lookup',5,3,2,'ok'),(3,'lookup',90,10,80,'busy'),(4,'report',100,90,10,'ok'),(5,'report',200,180,20,'ok'),(6,'lookup',10,8,2,'ok');
Fictional diagnostic dimensions
Metric Question answered Caution
Calls and total time Where is aggregate workload cost concentrated? High frequency can matter more than one slow call
Tail duration How bad are slower experiences? Small samples give unstable percentiles
Error rate How often does an operation fail? Define the denominator and categories
Pool versus database time Where did waiting occur? Do not assign all elapsed time to SQL execution

Worked practice

Exercise 1

Compare call counts, total elapsed time, and mean duration by query template.

Worked solution
-- Connection A
SELECT query_key,COUNT(*),SUM(elapsed_ms),AVG(elapsed_ms) FROM lab_metric157 GROUP BY query_key ORDER BY query_key;

The report template contributes three hundred milliseconds across two sample calls, while lookup contributes one hundred ten across four. The average answers a different question from total workload cost. A rare slow query and a frequent moderately expensive query can deserve different priorities depending on service impact and resource pressure.

Exercise 2

Separate pool waiting from database execution in the slow lookup.

Worked solution
-- Connection A
SELECT elapsed_ms,db_ms,pool_ms FROM lab_metric157 WHERE id=3;
-- Connection A
SELECT SUM(elapsed_ms),SUM(db_ms),SUM(pool_ms) FROM lab_metric157;

The ninety-millisecond lookup spent eighty milliseconds in the modeled pool wait and ten in database work. Rewriting its SELECT alone may not address the main delay. Investigate connection ownership, pool limits, transaction length, and server capacity before assuming an index is the missing solution.

Exercise 3

Calculate a clearly defined sample error rate.

Worked solution
-- Connection A
SELECT SUM(CASE WHEN outcome<>'ok' THEN 1 ELSE 0 END),COUNT(*),ROUND(100.0*SUM(CASE WHEN outcome<>'ok' THEN 1 ELSE 0 END)/COUNT(*),2) FROM lab_metric157;
-- Connection A
SELECT query_key,COUNT(*) FROM lab_metric157 WHERE outcome<>'ok' GROUP BY query_key ORDER BY query_key;

One of six recorded attempts is non-successful, giving 16.67 percent after rounding. This is an attempt-based sample rate, not necessarily a user-request failure rate: retries can produce several attempts for one request. Keep those denominators separate and classify expected business rejections separately when the service contract requires it.

Exercise 4

Compute a nearest-rank ninety-fifth percentile and state its sample limitation.

Worked solution
-- Connection A
WITH ranked AS (SELECT elapsed_ms,ROW_NUMBER() OVER(ORDER BY elapsed_ms,id) AS rn,COUNT(*) OVER() AS n FROM lab_metric157) SELECT elapsed_ms,n FROM ranked WHERE rn=(95*n+99)/100;

The nearest-rank position is the ceiling of 0.95 times six, which is six, so the result is two hundred milliseconds. Integer arithmetic implements that ceiling for this positive sample size. With only six values, this percentile is effectively the maximum and is not a reliable production service-level estimate. State the percentile definition and observation window.

Use plans as structural evidence

SQLite EXPLAIN QUERY PLAN describes choices such as scans, index searches, covering access, and temporary sorting. It does not execute a realistic end-to-end application request or supply observed production latency. Its human-readable output can change between releases, so avoid treating the exact text as a stable application API.

For a slow operation, first reproduce the correct result with representative parameters. Compare plans, row cardinalities, data distribution, and measured execution boundaries. A plan that looks elegant can still be expensive when it returns many rows or waits on resources outside the plan’s scope.

Server engines offer additional statistics and logging facilities. PostgreSQL activity and cumulative statistics can help distinguish active work, waits, and aggregate behavior, while logging thresholds have their own overhead and exposure tradeoffs. No PostgreSQL monitoring command or configuration change was executed in this SQLite lesson.

Make alerts actionable

An alert should identify the affected service behavior, the observation window, a meaningful threshold or baseline comparison, and a next diagnostic step. Alerting on every isolated slow call can create noise, while a rising failure rate or sustained pool saturation may need attention even when average query duration looks acceptable.

Record when counters reset and whether data is sampled. A difference between cumulative counters is meaningful only over a known interval with compatible reset history. Missing observations should not be silently treated as zero failures or zero latency.

Protect diagnostic access and retention. Avoid dumping all bound values to investigate a slow template, and do not attach an unrestricted query log to a public incident record. Start with redacted identifiers and aggregate evidence, then use the minimum authorized detail needed to diagnose the issue.

Pitfalls and summary

Do not confuse synthetic examples with measured performance, total time with mean time, attempts with requests, or plans with latency. Define metric boundaries and units, inspect tail behavior and error categories, and separate database work from surrounding waits before choosing a repair.

Knowledge check

Question 1

What is the status of the durations in this lesson’s metric table?

  1. Measured production latency from the user’s database
  2. Fictional teaching observations whose analysis queries were executed
  3. Measured timings of the previous lesson’s backup API calls
  4. Server statistics retrieved from PostgreSQL
Answer and explanation

B. The sample data and the executed analysis have different evidence status.

Question 2

Why might an index change fail to fix the slow lookup sample?

  1. Indexes are irrelevant whenever the query returns only one row
  2. Pool waiting is fully determined by the query plan’s scan type
  3. A failed attempt has no meaningful elapsed time to diagnose
  4. Most of its modeled elapsed time was waiting for a pool connection
Answer and explanation

D. Diagnose the dominant stage before optimizing a different one.

Question 3

What denominator produced the 16.67 percent rate?

  1. Six recorded database attempts
  2. Six unique authenticated users
  3. Only the successful report calls
  4. The number of distinct query templates
Answer and explanation

A. Attempt-level and request-level rates must not be conflated.

Question 4

Why is the sample ninety-fifth percentile weak production evidence?

  1. Nearest-rank percentiles require interpolating between the fifth and sixth observations here
  2. The maximum is representative whenever it exceeds the sample mean
  3. Only six observations make this nearest-rank percentile equal the maximum
  4. A percentile automatically removes sampling uncertainty
Answer and explanation

C. A mathematically correct statistic can still be unrepresentative.

Question 5

What does SQLite EXPLAIN QUERY PLAN fail to measure by itself?

  1. Whether a plan uses a table scan
  2. End-to-end request latency and surrounding waits
  3. Whether a covering access path appears
  4. Whether a temporary sorting structure is described
Answer and explanation

B. A structural plan is not an application timing measurement.

Execution scope

These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.

Primary references