Build and Operate HTTP APIs
Design, test, deploy, and operate an HTTP API that another engineer can use.
Counters, gauges and histograms, a rate from a counter, a percentile from buckets, a dashboard panel and an alert rule that fires on a sustained condition.
Why does an increasing counter need a rate before you turn it into an alert?
A counter records events over its lifetime. Compare changes over a defined time window to estimate event rate, accommodating process restarts in the measurement.
An error counter rises from 120 to 150 in one minute
Measure 30 new errors over 60 seconds
The average rate is 0.5 errors per second
An error counter rises from 120 to 150 in one minute
Measure 30 new errors over 60 seconds
The average rate is 0.5 errors per second
Given An error counter rises from 120 to 150 in one minute and The average rate is 0.5 errors per second, write down the missing step that connects them.
Measure 30 new errors over 60 seconds
Now take Measure 30 new errors over 60 seconds and the result above. Write an input and an implementation that could produce this trace.
An error counter rises from 120 to 150 in one minute. Check that your implementation produces the result shown above.
How could you tell whether 0.5 errors per second is unusual during a traffic spike?
Compare it to the request rate from the same window. The ratio estimates the share of requests failing.
The API returns successful responses, but the queue age rises and imported reports stop reaching complete. What observation could separate a frontend problem from a worker problem?
Follow a known job ID from API acceptance to worker claim and storage. If claim or completion events stop while requests keep queuing, inspect the worker and queue path.
Check this when debugging. Watching a counter's value when its rate is what matters
A service that is up can still be failing: slow, erroring on one route, or running out of memory. Nobody can watch a log of a million lines, so the service keeps a few numbers instead and a system reads them every 15 seconds. This lesson builds those numbers from scratch: the three kinds of metric, a rate from a counter, a percentile from buckets, and an alert rule. The tools that do it for real, Prometheus and its query language, come after you have built the parts.
10
The counter rose by 3,000 over 300 seconds: 10 a second.
A metric is a number a service keeps about itself, with a name and a few labels, such as http_requests_total{route="/score", status="200"}. A separate system scrapes it, which means it reads every metric on a fixed schedule, say every 15 seconds, and stores each reading with its time. There are three types, and each answers a different kind of question.
A counter's value is rarely interesting. A service that has served four million requests since Tuesday tells you nothing about this minute. What matters is its rate: the increase between two readings, divided by the seconds between them. The picture shows it.
A counter never goes down, so its value tells you little. Its slope, the rate, is the number you watch.
import math def percentile(values, p): ordered = sorted(values) return ordered[math.ceil(p / 100 * len(ordered)) - 1] ms = [9, 8, 9, 10, 8, 9, 120, 9, 8, 10] print(percentile(ms, 50), percentile(ms, 95), sum(ms) / len(ms))
9 120 20.0
The median of the ten latencies is 9, the 95th percentile is the slowest value, 120, and the mean is pulled up to 20.0 by that one slow request.
samples = [(0, 100), (60, 700), (120, 1300)] (t0, v0), (t1, v1) = samples[0], samples[-1] print((v1 - v0) / (t1 - t0))
10.0
The counter rose by 1,200 over 120 seconds: 10.0 a second.
Write a sentence or two, then compare it with a good answer in the lesson.
Everything below uses the Counter, Gauge, Histogram and quantile classes in the setup. They are about 40 lines in all, which is what makes the big libraries less mysterious: a counter is an integer, a gauge is a number, and a histogram is a list of integers.
The cell runs a thousand requests through them. Each request adds one to the counter, 1.2% of requests are errors, and each latency goes into the histogram's buckets: up to 0.1, 0.25, 0.5 and 1.0 seconds.
The lesson runs this once, before its first cell, and every cell, drill and example starts with what it defines. A cell that changes a setup object changes it for the cells after it, until the page reloads.
import math import random class Counter: def __init__(self): self.value = 0 def inc(self, n=1): self.value += n class Gauge: def __init__(self): self.value = 0 def set(self, value): self.value = value class Histogram: def __init__(self, bounds): self.bounds = bounds self.counts = [0] * (len(bounds) + 1) def observe(self, x): for i, bound in enumerate(self.bounds): if x <= bound: self.counts[i] += 1 return self.counts[-1] += 1 def cumulative(self): out, total = [], 0 for c in self.counts: total += c out.append(total) return list(zip(self.bounds + [float("inf")], out)) def quantile(buckets, q): """The q-th quantile from cumulative buckets, as Prometheus estimates it.""" total = buckets[-1][1] rank = q * total lower, below = 0.0, 0 for bound, count in buckets: if count >= rank: if bound == float("inf"): return lower return lower + (bound - lower) * (rank - below) / (count - below) lower, below = bound, count
rng = random.Random(0) requests, errors, inflight = Counter(), Counter(), Gauge() latency = Histogram([0.1, 0.25, 0.5, 1.0]) for i in range(1000): requests.inc() if rng.random() < 0.012: errors.inc() latency.observe(rng.lognormvariate(-1.6, 0.7)) inflight.set(7) print(requests.value, errors.value, inflight.value) print(latency.cumulative()) print( round(quantile(latency.cumulative(), 0.5), 3), round(quantile(latency.cumulative(), 0.95), 3), )
The counter shows 1,000 requests and 16 errors, an error ratio of 0.016. The histogram is stored as cumulative counts: 157 requests took 0.1 s or less, 615 took 0.25 s or less, 892 took 0.5 s or less, 983 took 1.0 s or less, and all 1,000 are counted in the last bucket. The median comes out near 0.212 s and the 95th percentile near 0.819 s.
The percentile is an estimate. The histogram knows that the 950th request fell between 0.5 s and 1.0 s, and the function assumes the requests in a bucket are spread evenly across it. A coarse bucket gives a coarse answer, so put bucket boundaries around the number you care about, such as your latency target.
errors, requests = 16, 1000 print(errors / requests)
0.016
16 / 1,000 is 0.016, an error ratio of 1.6%.
The one up to 0.5 s
The cumulative count reaches 900 at 0.25 s, which is short of 950, and 980 at 0.5 s, which passes it. So the 950th request is in the bucket from 0.25 to 0.5 s.
Write rate(samples). samples is a list of (seconds, value) readings of one counter, in time order. Return the increase divided by the seconds from the first reading to the last. Between two readings, if the value went down, the counter restarted: count the new reading as the increase for that step.
Uses the setup above, 51 lines.
def rate(samples): return 0.0 print(rate([(0, 100), (60, 700), (120, 1300)])) print(rate([(0, 9800), (60, 9900), (120, 150), (180, 750)]))
Write bucket_quantile(buckets, q). buckets is a list of (upper_bound, cumulative_count) in order, ending with (float('inf'), total). Find the first bucket whose cumulative count is at least q * total, and return lower + (bound - lower) * (rank - below) / (count - below), where lower and below are the previous bucket's bound and count (0 and 0 for the first). If the rank falls in the infinite bucket, return the last finite bound.
Uses the setup above, 51 lines.
def bucket_quantile(buckets, q): return 0.0 print(bucket_quantile([(0.1, 600), (0.25, 900), (0.5, 980), (float('inf'), 1000)], 0.9))
A rule that fires the moment one reading is high would page someone for every blip. A good rule needs the condition to hold for several scrapes in a row. This one fires when the error ratio is over 5% for three scrapes running.
Uses the setup above, 51 lines.
ratios = [0.004, 0.006, 0.06, 0.07, 0.08, 0.02] threshold, needed = 0.05, 3 streak, fired_at = 0, None for scrape, ratio in enumerate(ratios): streak = streak + 1 if ratio > threshold else 0 print("scrape", scrape, "| ratio", ratio, "| streak", streak) if streak == needed and fired_at is None: fired_at = scrape print("alert fired at scrape", fired_at)
The ratio first passes 5% at scrape 2, but the rule waits. It has been over for 1, then 2, then 3 scrapes in a row at scrape 4, so the alert fires there. A single high reading would have reset to 0 on the next low one. The wait costs two scrapes of delay and saves a page for every blip, which is the trade the duration in an alert rule sets.
A dashboard panel is one of these series drawn over time. This one shows the 95th percentile per minute, with a target line at 0.9 s, from ten minutes of simulated traffic that gets slower from minute 6:
Uses the setup above, 51 lines.
import matplotlib.pyplot as plt rng = random.Random(1) p95s = [] for minute in range(10): hist = Histogram([0.1, 0.25, 0.5, 1.0, 2.0]) shift = 0.5 if minute >= 6 else 0.0 for _ in range(300): hist.observe(rng.lognormvariate(-1.6 + shift, 0.7)) p95s.append(round(quantile(hist.cumulative(), 0.95), 3)) plt.plot(range(10), p95s, marker="o") plt.axhline(0.9, linestyle=":", color="gray") plt.xlabel("minute") plt.ylabel("p95 latency (s)") plt.show() print(p95s)
The series stays under the line until minute 6 and then crosses it and stays there. That crossing is what an alert on the percentile would catch.
Minute 6
The p95 is 0.986 s at minute 6 and above 0.9 s for every minute after it. Minute 4 is 0.818 s, under the line.
Write a sentence or two, then compare it with a good answer in the lesson.
In a real service these classes come from a client library, and a server called Prometheus scrapes them. Your service exposes its metrics as plain text at a path, usually /metrics: one line per series, with its labels and its current value, and a # TYPE line saying whether it is a counter, a gauge or a histogram. Prometheus reads that page on a schedule and stores each value with its time. A dashboard tool such as Grafana then draws queries over what it stored.
You are on call and the p95 panel for the scoring service has climbed. You ask three questions of the metrics: is the request rate up (a traffic change), is the error ratio up (a failure), and which bucket moved (a slow dependency or the model)? Then you open the alert rule behind the page and check that its threshold and its for: duration match what the team agreed, because a rule that is too twitchy or too slow is a bug in the monitoring, not in the service.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Which metric type is right for "how many requests are being handled right now"?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write