At the end of part 10, linkbox could answer requests but couldn't remember anything. Every new link got id 4, and it vanished as soon as the response was sent. The error messages were plain text in a different format for every kind of mistake. And there was no logging at all, so if something went wrong on a server, you'd have no idea what.
This part fixes all three. We'll give handlers shared state so links are actually stored, add middleware for logging, compression and timeouts, and build one AppError type so every failure turns into the same JSON shape. Along the way the code outgrows a single file, so we'll split it into modules the way part 6 described.
The storage is still in memory, so everything disappears when the server restarts. That's on purpose: it lets us get the structure right before adding a database in part 12, and when we do, the handlers barely change.
As usual, this ran on Rust 1.100.0, with Axum 0.8.9 and tower-http 0.7.1, and every response below is real.
The new layout
Here's how the project looks by the end of this part:
linkbox/
├── Cargo.toml
└── src/
├── main.rs starts the server and logging
├── lib.rs builds the router and middleware
├── error.rs AppError and the custom extractors
├── models.rs Link, NewLink, ListParams
├── state.rs AppState, the in-memory store
└── routes/
├── mod.rs
└── links.rs the /links handlers
The split follows the library and binary pattern from part 6. lib.rs has a public app() function that builds the whole application, and main.rs is a thin wrapper that sets up logging and calls it. That matters in part 14, when tests build the app from lib.rs without starting a server.
models.rs is the types from part 10, moved and made pub, plus an offset field on ListParams. Nothing new there.
The new dependencies:
cargo add axum --features macros
cargo add thiserror tracing
cargo add tower-http --features trace,timeout,compression-gzip
cargo add tracing-subscriber --features env-filter
Shared state
Handlers need somewhere to put links that outlives a single request, and every handler needs to see the same data. In Express, you'd put a Map at the top of the file and every route would use it. That works in Node because only one handler runs at a time.
In Axum, handlers run as Tokio tasks across several threads, as we saw in part 9. So the shared store needs the same tools as the hit counter there: an Arc so every handler can own a reference to it, and a lock so only one handler changes it at a time.
Here's state.rs:
use std::collections::BTreeMap;
use std::sync::{Arc, RwLock};
use crate::models::{Link, NewLink};
/// Everything the handlers share. Cloning it is cheap: it only clones the `Arc`.
#[derive(Clone, Default)]
pub struct AppState {
db: Arc<RwLock<Db>>,
}
#[derive(Default)]
struct Db {
links: BTreeMap<u64, Link>,
next_id: u64,
}
AppState is what Axum hands to handlers. It wraps everything in one Arc, so cloning the state for each request only bumps a reference count. Axum does clone it for each request, which is why it has to implement Clone.
Inside, Db holds the links in a BTreeMap, keyed by id. I chose it over a HashMap for the reason from part 8: it keeps keys in order, so listing links always returns them in the order they were created, without sorting. next_id is the counter for new ids.
The lock is a RwLock from the standard library, since reads (listing and fetching links) will be far more common than writes. Many handlers can read at once, and a write waits until it has the data to itself. I'm using the standard library lock, not Tokio's, following the advice from part 9: it's faster, and it's fine as long as no lock is held across an .await. None of the methods below await anything, so that can't happen by accident.
Rather than let handlers touch the lock directly, AppState has methods that do one job each:
impl AppState {
pub fn list(&self, tag: Option<&str>, offset: usize, limit: usize) -> Vec<Link> {
let db = self.db.read().unwrap();
db.links
.values()
.filter(|link| tag.is_none_or(|t| link.tags.iter().any(|lt| lt == t)))
.skip(offset)
.take(limit)
.cloned()
.collect()
}
pub fn get(&self, id: u64) -> Option<Link> {
self.db.read().unwrap().links.get(&id).cloned()
}
pub fn insert(&self, input: NewLink) -> Link {
let mut db = self.db.write().unwrap();
db.next_id += 1;
let link = Link {
id: db.next_id,
url: input.url,
title: input.title,
tags: input.tags,
};
db.links.insert(link.id, link.clone());
link
}
pub fn replace(&self, id: u64, input: NewLink) -> Option<Link> {
let mut db = self.db.write().unwrap();
let link = db.links.get_mut(&id)?;
link.url = input.url;
link.title = input.title;
link.tags = input.tags;
Some(link.clone())
}
pub fn remove(&self, id: u64) -> Option<Link> {
self.db.write().unwrap().links.remove(&id)
}
}
Each method takes the lock, does its work, and releases the lock when the guard goes out of scope at the end. Because every lock is taken and released inside one short function, there's no way to hold one too long or forget to release it.
tag.is_none_or(...) reads as "there's no tag filter, or the link has this tag". It's a method on Option that returns true for None and runs the closure for Some.
Methods return clones of links rather than references, because a reference into the map would keep the lock held. Cloning a small struct is cheap, and it means the lock is released before the handler builds its response.
This design has a nice side effect. The handlers will only see list, get, insert, replace and remove. In part 12, those methods will run SQL queries instead, and the handlers won't need to change.
Giving the state to handlers
The router gets the state with with_state, and handlers ask for it with the State extractor:
use axum::extract::State;
async fn show(
State(state): State<AppState>,
AppPath(id): AppPath<u64>,
) -> Result<AppJson<Link>, AppError> {
state.get(id).map(AppJson).ok_or(AppError::NotFound(id))
}
(AppPath, AppJson and AppError are coming up shortly. For now, read them as Path, Json and an error type.)
Like every extractor, State is just an argument. A handler that doesn't need the state doesn't ask for it.
State is typed. A router that needs state has the type Router<AppState>, meaning "a router still waiting for an AppState". Calling .with_state(state) supplies it and turns it into a Router<()>, which is what axum::serve accepts. If you forget with_state, the compiler stops you:
error[E0308]: mismatched types
--> src/lib.rs:42:5
|
41 | pub fn app(state: AppState) -> Router {
| ------ expected `Router` because of return type
42 | / Router::new()
43 | | .route("/health", get(health))
44 | | .nest("/links", routes::links::router())
...
| |__________________________________________^ expected `Router`, found `Router<AppState>`
|
= note: expected struct `Router<()>`
found struct `Router<AppState>`
In Express, forgetting to set up something a route depends on is a runtime crash on the first request that uses it. Here, the program doesn't compile until every route that needs state has it. And if a handler asks for a State<Something> that the router wasn't given, that's a compile error too.
Routes in their own module
The /links routes move to routes/links.rs, with their own small router:
use axum::{Router, extract::State, http::StatusCode, routing::get};
use crate::error::{AppError, AppJson, AppPath, AppQuery};
use crate::models::{Link, ListParams, NewLink};
use crate::state::AppState;
pub fn router() -> Router<AppState> {
Router::new()
.route("/", get(list).post(create))
.route("/{id}", get(show).put(replace).delete(remove))
}
Then in lib.rs, it's mounted under /links with nest, which is Express's app.use("/links", linksRouter):
.nest("/links", routes::links::router())
Inside the module, the paths are relative: "/" is /links and "/{id}" is /links/{id}. As the API grows, each resource gets its own file with its own router, and lib.rs just stitches them together.
This part also adds the two routes missing from part 10. PUT /links/{id} replaces a link, and DELETE /links/{id} removes one:
async fn replace(
State(state): State<AppState>,
AppPath(id): AppPath<u64>,
AppJson(input): AppJson<NewLink>,
) -> Result<AppJson<Link>, AppError> {
check(&input)?;
state
.replace(id, input)
.map(AppJson)
.ok_or(AppError::NotFound(id))
}
async fn remove(
State(state): State<AppState>,
AppPath(id): AppPath<u64>,
) -> Result<StatusCode, AppError> {
state.remove(id).ok_or(AppError::NotFound(id))?;
Ok(StatusCode::NO_CONTENT)
}
Notice the argument order in replace: state, then path, then the JSON body last, following the rule from part 10.
Trying it out
Now links are stored. Starting with an empty server:
curl http://127.0.0.1:3000/links
[]
Adding three links:
curl -X POST http://127.0.0.1:3000/links -H 'content-type: application/json' \
-d '{"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"]}'
curl -X POST http://127.0.0.1:3000/links -H 'content-type: application/json' \
-d '{"url":"https://tokio.rs","title":"Tokio","tags":["rust","async"]}'
curl -X POST http://127.0.0.1:3000/links -H 'content-type: application/json' \
-d '{"url":"https://developer.mozilla.org","title":"MDN","tags":["web"]}'
{"id":1,"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"]}
{"id":2,"url":"https://tokio.rs","title":"Tokio","tags":["rust","async"]}
{"id":3,"url":"https://developer.mozilla.org","title":"MDN","tags":["web"]}
Each one gets the next id. Filtering and paging work on the stored data:
curl "http://127.0.0.1:3000/links?tag=rust"
curl "http://127.0.0.1:3000/links?offset=1&limit=1"
[{"id":1,"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"]},{"id":2,"url":"https://tokio.rs","title":"Tokio","tags":["rust","async"]}]
[{"id":2,"url":"https://tokio.rs","title":"Tokio","tags":["rust","async"]}]
Replacing link 2 and deleting link 3:
curl -X PUT http://127.0.0.1:3000/links/2 -H 'content-type: application/json' \
-d '{"url":"https://tokio.rs/tokio/tutorial","title":"Tokio tutorial","tags":["rust","async"]}'
curl -i -X DELETE http://127.0.0.1:3000/links/3
{"id":2,"url":"https://tokio.rs/tokio/tutorial","title":"Tokio tutorial","tags":["rust","async"]}
HTTP/1.1 204 No Content
x-response-time: 0.05ms
(The x-response-time header comes from a middleware we'll write in a moment.) After adding one more link, the ids keep counting up, and deleted ids aren't reused:
[{"id":1,"url":"https://www.rust-lang.org","title":"Rust","tags":["rust"]},{"id":2,"url":"https://tokio.rs/tokio/tutorial","title":"Tokio tutorial","tags":["rust","async"]},{"id":4,"url":"https://serde.rs","title":"Serde","tags":[]}]
One error type for the whole app
In part 10, errors came from three places, each in its own format. Our handlers returned bare status codes with empty bodies. Axum's extractors returned plain text messages. And the fallback returned a string. A client would need three different ways to read an error.
A good API returns every error in the same shape, so client code can handle them all in one place. I'll use this:
{ "error": { "code": "not_found", "message": "link 3 not found" } }
code is a short, stable string that client code can match on. message is for humans and might change.
The AppError enum
In part 5, we built a wordfreq error type with thiserror. This is the same idea, applied to a web server:
use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection};
/// Every way a request can fail, in one place.
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("link {0} not found")]
NotFound(u64),
#[error("no route for {0}")]
NoRoute(String),
#[error("{0}")]
Validation(String),
#[error(transparent)]
Json(#[from] JsonRejection),
#[error(transparent)]
Path(#[from] PathRejection),
#[error(transparent)]
Query(#[from] QueryRejection),
}
The first three are our own errors. The last three wrap Axum's rejection types, the errors its extractors produce when a request is bad. #[from] generates a From conversion for each, so ? can turn a rejection into an AppError, and #[error(transparent)] reuses the rejection's own message.
Next, each variant needs a status code and an error code:
impl AppError {
fn status_and_code(&self) -> (StatusCode, &'static str) {
match self {
AppError::NotFound(_) | AppError::NoRoute(_) => (StatusCode::NOT_FOUND, "not_found"),
AppError::Validation(_) => (StatusCode::UNPROCESSABLE_ENTITY, "invalid_input"),
AppError::Json(rejection) => (rejection.status(), "invalid_json"),
AppError::Path(rejection) => (rejection.status(), "invalid_path"),
AppError::Query(rejection) => (rejection.status(), "invalid_query"),
}
}
}
For rejections, rejection.status() keeps the status Axum chose, so a broken JSON body is still a 400, a missing field is still a 422, and a missing content type is still a 415. We're only changing the format of the body, not the meaning.
The match has no wildcard arm. When I add a new variant later, this function won't compile until I decide its status code. That's exhaustive matching from part 4 doing its job.
Implementing IntoResponse
Here's the piece that ties it into Axum. In part 10 we saw that handlers can return anything that implements IntoResponse. So we implement it for AppError:
use axum::response::{IntoResponse, Response};
use serde_json::json;
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, code) = self.status_and_code();
let body = Json(json!({
"error": { "code": code, "message": self.to_string() }
}));
(status, body).into_response()
}
}
self.to_string() uses the Display implementation that thiserror generated from the #[error(...)] attributes. The status and JSON body become a response by reusing the tuple implementation from part 10.
Now any handler can return Result<Something, AppError>, and the error side is turned into the JSON format automatically. This is the trait pattern from part 7 at its most useful: Axum defines the trait, we implement it for our type, and our type plugs into every place Axum accepts a response.
Using it in handlers
Handlers now return AppError and use ? freely. Here's create, with a small validation check:
fn check(input: &NewLink) -> Result<(), AppError> {
if input.title.trim().is_empty() {
return Err(AppError::Validation("title must not be empty".into()));
}
if !input.url.starts_with("http://") && !input.url.starts_with("https://") {
return Err(AppError::Validation(
"url must start with http:// or https://".into(),
));
}
Ok(())
}
async fn create(
State(state): State<AppState>,
AppJson(input): AppJson<NewLink>,
) -> Result<(StatusCode, AppJson<Link>), AppError> {
check(&input)?;
let link = state.insert(input);
tracing::info!(id = link.id, url = %link.url, "link created");
Ok((StatusCode::CREATED, AppJson(link)))
}
check(&input)? returns early with the validation error if anything's wrong. It's a basic check, enough to reject an empty title or a URL with the wrong scheme. Part 13 replaces it with a proper validation library that reports every problem at once.
tracing::info! is logging, which is coming up below.
Custom extractors for rejections
There's one gap. The AppError enum can hold Axum's rejections, but the plain Json, Path and Query extractors still send their own plain text responses. They reject the request before our handler runs, so our handler never gets the chance to convert anything.
The fix is a wrapper extractor that works like Json but uses AppError as its rejection. Axum's macros feature can generate this:
use axum::extract::{FromRequest, FromRequestParts};
/// `Json`, but with our error format when the body is wrong.
#[derive(FromRequest)]
#[from_request(via(axum::Json), rejection(AppError))]
pub struct AppJson<T>(pub T);
impl<T: Serialize> IntoResponse for AppJson<T> {
fn into_response(self) -> Response {
axum::Json(self.0).into_response()
}
}
/// `Path`, but with our error format when a parameter doesn't parse.
#[derive(FromRequestParts)]
#[from_request(via(axum::extract::Path), rejection(AppError))]
pub struct AppPath<T>(pub T);
/// `Query`, but with our error format when the query string is wrong.
#[derive(FromRequestParts)]
#[from_request(via(axum::extract::Query), rejection(AppError))]
pub struct AppQuery<T>(pub T);
Read via(axum::Json), rejection(AppError) as "extract this using Json, and if that fails, convert the rejection into an AppError". That conversion is the From that #[from] generated. AppJson also implements IntoResponse, so it works as a return type too, and handlers only ever use one JSON type.
The derive names follow the rule from part 10. Json reads the body, so its wrapper derives FromRequest. Path and Query only read the head of the request, so theirs derive FromRequestParts.
The fallback for unknown paths returns an AppError too. Handlers can take a Uri extractor to see the requested path:
async fn not_found(uri: Uri) -> AppError {
AppError::NoRoute(uri.path().to_string())
}
Every error, one format
Now every way a request can fail gives the same shape. A link that doesn't exist:
HTTP/1.1 404 Not Found
content-type: application/json
{"error":{"code":"not_found","message":"link 3 not found"}}
A path that isn't a number:
HTTP/1.1 400 Bad Request
content-type: application/json
{"error":{"code":"invalid_path","message":"Cannot parse `abc` to a `u64`"}}
A bad query string, a missing field, broken JSON and a missing content type:
{"error":{"code":"invalid_query","message":"Failed to deserialize query string: limit: invalid digit found in string"}}
{"error":{"code":"invalid_json","message":"Failed to deserialize the JSON body into the target type: missing field `title` at line 1 column 26"}}
{"error":{"code":"invalid_json","message":"Failed to parse the request body as JSON: EOF while parsing a value at line 1 column 26"}}
{"error":{"code":"invalid_json","message":"Expected request with `Content-Type: application/json`"}}
Our validation:
{"error":{"code":"invalid_input","message":"title must not be empty"}}
{"error":{"code":"invalid_input","message":"url must start with http:// or https://"}}
And an unknown route:
HTTP/1.1 404 Not Found
content-type: application/json
{"error":{"code":"not_found","message":"no route for /nope"}}
A frontend can now handle every error with one function that reads error.code.
Middleware
Middleware is code that runs around every request: before the handler, after it, or both. It's the same idea as Express's app.use, but Axum doesn't have its own middleware system. It uses Tower, a library of reusable building blocks for network services. A Tower "layer" wraps a service and returns a new service with extra behaviour. Axum routers are Tower services, so any Tower layer works with Axum. The tower-http crate has a collection of ready-made layers for HTTP.
Here's the router in lib.rs with four layers:
use tower_http::{compression::CompressionLayer, timeout::TimeoutLayer, trace::TraceLayer};
pub fn app(state: AppState) -> Router {
Router::new()
.route("/health", get(health))
.nest("/links", routes::links::router())
.fallback(not_found)
.with_state(state)
.layer(middleware::from_fn(response_time))
.layer(CompressionLayer::new())
.layer(TimeoutLayer::with_status_code(
StatusCode::REQUEST_TIMEOUT,
Duration::from_secs(10),
))
.layer(TraceLayer::new_for_http())
}
Order matters, and it's the opposite of what you might expect. Each .layer wraps everything above it, so the last one added is the outermost and sees the request first. Here, a request passes through tracing, then the timeout, then compression, then the response-time middleware, and then reaches the router. The response travels back out in the reverse order. So TraceLayer sees the full time of every request, including the time spent compressing, and it logs requests that timed out.
In Express, middleware runs in the order you call app.use, top to bottom. If you think of Axum's layers as an onion being built from the inside out, the order makes sense.
Logging with tracing
Rust's standard for logging is the tracing crate. It's more than a logger: it records structured events with fields, and "spans" that group events, like everything that happened during one request. tracing-subscriber decides where the events go, and in main.rs we set it up to print them:
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env()
.unwrap_or_else(|_| EnvFilter::new("linkbox=debug,tower_http=debug")),
)
.init();
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
tracing::info!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app(AppState::default()))
.await
.unwrap();
}
The filter says what to show. By default, debug-level events from our own code and from tower-http. The RUST_LOG environment variable overrides it, so in production you could run with RUST_LOG=linkbox=info,tower_http=warn to log less, without rebuilding.
TraceLayer::new_for_http() creates a span for each request and logs when it starts and finishes. Here's the server's output for the DELETE and the GET that followed it:
2026-12-01T06:55:04.713843Z DEBUG request{method=DELETE uri=/links/3 version=HTTP/1.1}: tower_http::trace::on_request: started processing request
2026-12-01T06:55:04.714522Z DEBUG request{method=DELETE uri=/links/3 version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=204
2026-12-01T06:55:04.726700Z DEBUG request{method=GET uri=/links/3 version=HTTP/1.1}: tower_http::trace::on_request: started processing request
2026-12-01T06:55:04.727393Z DEBUG request{method=GET uri=/links/3 version=HTTP/1.1}: tower_http::trace::on_response: finished processing request latency=0 ms status=404
And here's the event from create, the tracing::info! line in the handler:
2026-12-01T06:55:04.623313Z INFO request{method=POST uri=/links version=HTTP/1.1}: linkbox::routes::links: link created id=1 url=https://www.rust-lang.org
Notice the request{method=POST uri=/links ...} prefix. We didn't pass any request information to tracing::info!. The event happened inside the request's span, so it was tagged automatically. When fifty requests are being handled at once and their logs are interleaved, that's how you tell them apart.
The fields are structured, too. id = link.id records a number, and url = %link.url records the URL using its Display format (the %). With a JSON formatter, which is one line of configuration on tracing_subscriber::fmt(), these become real JSON fields that a log service can search and filter on.
Compression
CompressionLayer compresses response bodies when the client says it accepts compression. I enabled only gzip, through the compression-gzip feature. To see the difference, I added 40 more links and fetched the list:
curl -s -o /dev/null -w "plain: %{size_download} bytes\n" "http://127.0.0.1:3000/links?limit=100"
curl -s -o /dev/null -H 'accept-encoding: gzip' -w "gzip: %{size_download} bytes\n" "http://127.0.0.1:3000/links?limit=100"
plain: 3930 bytes
gzip: 474 bytes
JSON is very repetitive, so it compresses well: 88% smaller here. Responses that are compressed get a content-encoding: gzip header, and responses with a body get vary: accept-encoding so caches know to store the two versions separately. In production, a reverse proxy in front of the app sometimes does this instead, in which case you'd leave this layer out.
Timeouts
TimeoutLayer gives every request a time limit, here 10 seconds. If a handler is still running when the time is up, the layer drops the handler's future (which, as we saw in part 9, cancels it) and responds with the status code we gave it, 408 Request Timeout. Without this, a handler stuck waiting on a slow database could hold a connection open forever.
with_status_code is new in recent versions of tower-http. Older tutorials use TimeoutLayer::new(duration), which is now deprecated because it didn't let you choose the status.
Writing your own middleware
For simple middleware, you don't need to learn Tower's traits. axum::middleware::from_fn turns an async function into a layer. Here's the one that adds the x-response-time header:
use axum::{extract::Request, middleware::Next, response::Response};
/// Adds an `x-response-time` header to every response.
async fn response_time(request: Request, next: Next) -> Response {
let start = Instant::now();
let mut response = next.run(request).await;
let ms = format!("{:.2}ms", start.elapsed().as_secs_f64() * 1000.0);
if let Ok(value) = HeaderValue::from_str(&ms) {
response.headers_mut().insert("x-response-time", value);
}
response
}
This is the closest thing to Express middleware: you get the request, call next.run(request).await to pass it on, and then you can change the response before returning it. Code before next.run runs on the way in, and code after it runs on the way out. Unlike Express, there's no way to forget to call next and leave a request hanging: the function has to return a Response, so it either calls next.run or builds a response itself.
A middleware function can also take extractors before the request argument, like State or HeaderMap. That's how you'd write an authentication check, which we'll do in part 13.
Express and Axum, part two
| Express | Axum |
|---|---|
A module-level Map or app.locals |
AppState with Arc and a lock, via with_state |
req.app.locals.db |
State(state): State<AppState> |
| Missing setup fails at runtime | Router<AppState> won't serve until state is given |
app.use("/links", linksRouter) |
.nest("/links", links::router()) |
Error-handling middleware (err, req, res, next) |
impl IntoResponse for AppError |
next(err) |
return Err(AppError::...) or ? |
app.use(middleware) |
.layer(...) |
| Runs top to bottom | Last layer added runs first |
morgan for logging |
TraceLayer with tracing |
compression() |
CompressionLayer |
connect-timeout |
TimeoutLayer |
(req, res, next) => { ...; next() } |
middleware::from_fn(f) with next.run(req).await |
Exercises
- Add a
GET /links/countroute that returns{"count": 3}. Where in the router does it need to go so it isn't caught by/links/{id}? Try it and see what Axum does. - Add an
AppError::Conflict(String)variant with status 409, and use it to reject creating a link whose URL is already saved. What did the compiler make you change when you added the variant? - Add a
RequestIdLayerfrom tower-http (featurerequest-id) that gives every request anx-request-idheader. Can you get the id into the trace span, so it appears in every log line? - Switch the log output to JSON with
.json()on the subscriber builder (you'll need thejsonfeature oftracing-subscriber). What does alink createdevent look like now? - Write a middleware with
from_fnthat rejects any request with a body larger than 64 KB. Then look at tower-http'sRequestBodyLimitLayer, and compare. Which would you use?
Next up: a real database with SQLx and PostgreSQL
linkbox is a working API now, with consistent errors, logging and middleware. But restart it, and every link is gone.
In part 12 we'll replace the in-memory map with PostgreSQL, using SQLx. SQLx checks your SQL queries against a real database at compile time, so a typo in a column name is a build error instead of a 500 in production. We'll set up Postgres in Docker, write migrations, use a connection pool in AppState, and see how database errors fit into AppError. Thanks to the methods on AppState, the handlers will barely change.