Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

Axum Practice and Review

Review the Axum course with a production checklist, common mistakes, and hands-on exercises such as idempotency keys and a retry policy, with runnable Rust stand-ins and solutions.

You have now seen the whole path from Router::new() to a deployed, tested, authenticated service. This final lesson pulls it together: a mental model of a request, a checklist to review any Axum service, the mistakes that catch almost everyone, and exercises to practice with.

The real framework cannot run on this site, so the exercises use runnable Rust stand-ins for the logic; each one maps directly onto code you would write in a handler or layer.

The life of a request

flowchart TB
    N["TCP connection (Tokio + hyper)"] --> L["Layers: trace, timeout, CORS, auth"]
    L --> R["Router: match method and path"]
    R --> E["Extractors: Path, Query, Json, State"]
    E --> H["Handler (async fn)"]
    H --> I["IntoResponse"]
    I --> L2["Layers on the way out"]
    L2 --> N

Errors can leave at any step. Extractor failures and your own AppError both become responses through IntoResponse.

A production review checklist

Use this when reviewing a service, yours or someone else's.

Correctness

  • Does every error path return a deliberate status code and a JSON error body, with no unwrap() on user-influenced data?
  • Are all inputs validated (length, range, format) before they reach the database?
  • Is authorization checked on every route that needs it, ideally inside the query?

Robustness

  • Do blocking or CPU-heavy tasks use spawn_blocking instead of stalling the async runtime?
  • Are there timeouts for requests and for outbound calls?
  • Is a database pool configured with a sensible size and acquire timeout?
  • Does the server shut down gracefully on SIGTERM?

Operations

  • Structured logs with a request ID? Metrics for rate, errors and latency?
  • Configuration from the environment, validated at startup, with no secrets in logs?
  • Backward-compatible migrations, a readiness check, a non-root container?

Tests

  • oneshot tests for the routes, a real database for the SQL, and cases for 401, 403/404 and 422.

Common mistakes

  1. Holding a std::sync::Mutex guard across an .await. The future stops being Send (compile error) or, with an async mutex, serializes your requests. Lock, copy what you need, drop the guard, then await.
  2. Blocking inside async code: std::thread::sleep, heavy hashing, or synchronous file reads on a runtime thread. Use tokio::time::sleep and spawn_blocking.
  3. Extractor order: the body extractor (Json, String, Bytes) must be the last argument because it consumes the request.
  4. Unbounded everything: body sizes, page limits, retries, queue lengths.
  5. Leaking internals: returning sqlx::Error text to clients. Log it, return a generic 500.
  6. Using 403 where 404 is safer, or 500 where the client's input was at fault (use 400 or 422).
  7. Cloning the whole state: wrap heavy shared data in Arc; pools and clients are already cheap to clone.

Exercise 1: idempotency keys

Clients retry after network failures. If POST /payments runs twice, the customer is charged twice. An idempotency key header lets the server recognize a repeat and return the original result instead of repeating the work. The stand-in below does it with a map; in production the keys live in a table with a unique constraint.

Rust Idempotent POST handling (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Your turn: what should happen if the same key is reused with a different amount? A good answer is 422 with a message, because the key now describes a different request. Store a hash of the body with the key and compare.

Exercise 2: a retry policy with backoff

When your handler calls another service, a transient failure should be retried a few times with growing waits (exponential backoff), then give up. This stand-in uses a fake flaky dependency and simulated delays.

Rust Retry with exponential backoff (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Your turn: add random jitter to each wait so many clients do not retry in lockstep, and retry only errors that are safe to repeat (never a non-idempotent POST without an idempotency key).

More practice

  1. Add GET /healthz and GET /readyz to the notes API from the projects, with a readiness check that queries the database.
  2. Add a tags table and GET /notes?tag=rust. Which index do you need?
  3. Add ETag headers to GET /notes/{id} and answer 304 Not Modified when If-None-Match matches.
  4. Write a middleware that rejects requests without Content-Type: application/json on POST routes with 415.
  5. Review the URL shortener against the checklist above. What would you change before launch?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where must a body extractor such as Json<T> appear in a handler's arguments?

    Only one extractor can consume the body, and Axum requires it to be the final argument.
  2. 2. What problem does an idempotency key solve?

    The server recognizes the repeated key and returns the stored result instead of redoing the work.
  3. 3. Why add jitter to exponential backoff?

    Random variation spreads retries out and prevents synchronized load spikes.
  4. 4. What is wrong with calling std::thread::sleep inside an async handler?

    Use tokio::time::sleep, which yields to the runtime while waiting.
  5. 5. Which is a safer response when the client sends bad JSON?

    Bad input is the client's fault, so use a 4xx and a clear, safe message.

Summary

  • A request passes layers, routing, extractors, the handler and IntoResponse; errors can exit at any step.
  • Review services on correctness, robustness, operations and tests.
  • Avoid the classic mistakes: guards across awaits, blocking calls, body extractor order, unbounded inputs and leaked internals.
  • Idempotency keys make retried writes safe; backoff with jitter makes retries polite.
  • Keep practicing by extending the projects with health checks, tags, ETags and middleware.

Next: Back to the Axum track