Skip to content

Lesson 59 of 59Production

Wrap-Up: Python Backend

Tie the whole Python Backend course together: one realistic feature built from an empty repo to a watched production rollout, a mixed review, and where to go next.

15 min read0/6 questions

You started this course by setting up an editor and a uv project, before you had written a single route. Since then you have followed a request through Uvicorn and ASGI, built a FastAPI service with real data, background work, careful API design, identity, product features and tests, met the other frameworks and libraries a Python team uses, and shipped it all to production. On the job these pieces never arrive one lesson at a time. This lesson lines them up once more and then uses them together on one feature.

The path you took

Python Backend, unit by unit
  1. Unit 1

    Your Python toolbox

    An editor, uv, Ruff, a type checker and a debugger gave you a project that is reproducible and checked before you write any backend code.

  2. Unit 2

    How backends work

    Requests, ASGI, Uvicorn, path operations and Pydantic models gave you a working API, and the next step was making it a real one.

  3. Unit 3

    Building a real API

    CRUD design, Depends, settings, error handlers, middleware and JWT auth turned toy routes into a service that needs real storage.

  4. Unit 4

    Data and storage

    Postgres, SQLAlchemy, Alembic, Redis and transaction fixes gave the API durable data, and showed which work is too slow for a request.

  5. Unit 5

    Async and background work

    The event loop, asyncio, Celery and WebSockets moved slow work out of the request, which raised the question of what clients can rely on.

  6. Unit 6

    API design in depth

    Versioning, keyset pagination, Problem Details, idempotency keys and OpenAPI made the API safe to depend on, ready for many users.

  7. Unit 7

    Identity and access

    Sessions, OAuth and OIDC, authorization models and tenant isolation decided who may do what, so product features could be built on top.

  8. Unit 8

    Product features

    Uploads, email, rate limits, feature flags and scheduled jobs covered the work every SaaS backend ends up doing.

  9. Unit 9

    Libraries every Python developer knows

    httpx, Typer, Rich, NumPy, pandas, Polars and scraping widened your reach beyond the web layer.

  10. Unit 10

    Other frameworks

    Django, DRF and Flask showed the same ideas in other shapes, so you can join any Python team and choose a stack with reasons.

  11. Unit 11

    Testing

    TestClient, pytest and real Postgres in tests gave you proof that the service works, which is what a pipeline needs to trust.

  12. Unit 12

    Production

    Structure, observability, security, scaling, CI/CD and deployment turned the code into a service that runs, and that you can see.

How it fits together

The ticket: "Clinics on our SaaS want patients to book appointments online. A slot must never be double-booked. Send a confirmation email. Launch to a few clinics first." Here is how the course shows up, in the order you would really work.

Setting up. The service already exists, so you start by cloning it and running uv sync, as in uv for Real Projects. Ruff and pyright run on save and in pre-commit (Code Quality Tools), and you put a breakpoint in the existing appointments route to see how a request flows through it (Python Editors, Debugging Python). The new code goes in an appointments feature folder with its own router, service and repository, following Structuring a FastAPI Project.

Shaping the API. You design the resource first: POST /clinics/{clinic_id}/bookings returns 201, GET on the collection lists them, and cancelling is a PATCH to the status, as Designing a CRUD API taught. Separate BookingCreate and BookingRead models keep internal fields out of the response (Pydantic Models), and the path and query types reject bad input with a 422 before your code runs (Path and Query Parameters). The list endpoint uses keyset pagination on (starts_at, id) with a signed cursor, from List Endpoints That Scale.

Storing it. A bookings table gets an Alembic migration that you review by hand rather than trust blindly (Database Migrations with Alembic), with types and keys chosen as in PostgreSQL for Developers. The session comes from a yield dependency (Dependency Injection) and the queries use SQLAlchemy 2.0 with eager loading so the list view does not trigger N+1 queries (Databases with SQLAlchemy, Async Databases: SQLAlchemy AsyncSession, asyncpg and SQLModel).

Never double-booking. Two patients clicking the last slot at once is the bug from Transactions and Concurrency Bugs in Web Apps. A unique constraint on (clinic_id, slot_id) lets the database decide, and you turn the IntegrityError into a 409. Phones on bad networks retry the POST, so the endpoint accepts an Idempotency-Key and replays the first response (Safe Retries with Idempotency Keys). Every error leaves as Problem Details, so the mobile team can parse one shape (Error Responses Clients Can Rely On).

Who may book. Patients log in with Google through the existing OIDC flow (Log In with Google: OAuth 2 and OpenID Connect). The tenant comes from the token, every query filters by clinic_id, and Postgres Row-Level Security catches anything you forget (Multi-Tenant SaaS Backends). A patient asking for another clinic's booking gets a 404, not a 403, as in Authorization: Roles, Permissions and Ownership.

The slow parts. Sending the confirmation email inside the request would make booking as slow as the email provider. Instead, the booking and an outbox row commit together, and a Celery task sends the email with retries (Task Queues with Celery, Sending Email from a Backend). A scheduled job sends reminders the day before, computed in the clinic's time zone (Scheduled Jobs and Cron Done Right). The clinic calendar sync calls a partner API with httpx, a timeout and a shared client (Calling APIs with requests and httpx). A per-patient rate limit in Redis stops a script from grabbing every slot (Rate Limits, Quotas and Request Limits in FastAPI).

Launching to a few clinics. The whole feature sits behind a flag evaluated in a dependency, turned on for three clinics (Feature Flags and Safe Rollouts). Settings such as the email provider key come from pydantic-settings, never from git (Settings and Config).

Proving it works. Tests run against a real Postgres with one transaction per test, including two concurrent bookings for the same slot that must end with exactly one success (Testing with Real Databases). Auth is swapped with dependency_overrides (Testing FastAPI), and parametrized cases cover every status code (pytest in Depth). A snapshot of the OpenAPI schema fails CI if a field is renamed by accident (OpenAPI, Generated Clients and Contract-First APIs).

Shipping and watching. The pipeline lints, type checks, tests, builds the image and deploys main (CI/CD for Python). The migration runs as a release step before the new code, and the rollout waits on readiness checks (Deploying FastAPI). Structured logs carry the request id from your middleware (Errors and Middleware, Logging and Observability), and you watch the 409 rate and p95 latency for the three clinics before widening the flag.

Notice that no lesson worked alone. The constraint made the race safe, the idempotency key made retries safe, the outbox made email reliable, and the real-database test proved all three together. That is backend work.

Check yourself

Quick check
A route is declared as @app.get('/bookings/{booking_id}') with booking_id: int. A client requests /bookings/abc. What happens?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

What does this print?

import asyncio
import time

async def handler(name):
  time.sleep(0.1)
  return name

async def main():
  start = time.perf_counter()
  names = await asyncio.gather(handler("a"), handler("b"), handler("c"))
  print(names, round(time.perf_counter() - start, 1))

asyncio.run(main())
Need a nudge? Hints walk you through it.
Match the pairs0/6 matched

Match each problem to the tool that fixes it.

Choose an item, then its match on the other side.
Put it in order6 steps

Put these steps of handling one request in the order they happen.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Each worker has a database pool of 20. You run 4 workers per machine on 3 machines. Postgres allows 100 connections. What goes wrong first when traffic rises?
Need a nudge? A hint rules out a wrong answer.
Quick check
A new internal tool needs a staff admin for editing records, server-rendered pages and user accounts, and the team has two weeks. Which choice fits best?
Need a nudge? A hint rules out a wrong answer.

What you can do now

  • Build a typed FastAPI service with Pydantic models, dependencies, settings, consistent errors and middleware.
  • Store data in Postgres through SQLAlchemy, manage schema changes with Alembic, and fix race conditions with constraints, locks or version columns.
  • Move slow work to background tasks or Celery, and avoid blocking the event loop.
  • Design list, error, retry and versioning behaviour that clients can depend on.
  • Add login, authorization checks and tenant isolation without leaking data between customers.
  • Write tests against a real database, and ship through a CI pipeline to a containerised deployment with logs, metrics and health checks.
  • Read and contribute to a Django, DRF or Flask codebase.

That is a solid mid-level backend skill set. What you do not have yet is experience running a busy system for months: the incidents, the slow migrations on huge tables and the trade-offs that only show up at scale. That comes from real systems and from the courses below.

Mistakes that still catch people

  • Blocking the event loop. A sync library call inside async def freezes every request on that worker. Revisit Background Tasks and Async and Asyncio in Depth.
  • Read, then write. Checking that a slot is free and then inserting is a race, however fast the code is. Revisit Transactions and Concurrency Bugs in Web Apps and Safe Retries with Idempotency Keys.
  • Trusting autogenerate. Alembic can drop and recreate a renamed column, deleting its data, or lock a big table during deploy. Revisit Database Migrations with Alembic.
  • Checking login but not ownership. A valid token does not mean this user may read this object. Revisit Authorization: Roles, Permissions and Ownership and API Security.
  • Mocking the database. Mocks pass while the real query, constraint or migration fails. Revisit Testing with Real Databases.
  • Scaling into the connection limit. More workers and machines multiply pool sizes until Postgres refuses connections. Revisit Performance and Scaling and Async Databases: SQLAlchemy AsyncSession, asyncpg and SQLModel.

Where to go next

The natural next course is HTML & CSS, then JavaScript & TypeScript and React: the clients of your API are mostly web frontends, and knowing their side makes you better at designing the contract. If you want to go deeper on the server instead, Docker and AWS cover the containers and cloud this course deployed to, and System Design scales the single service you built into many.

Real practice matters as much as the next course:

  • Finish and extend Project: A Warehouse Stock API. Its "Make it yours" list moves it to Postgres, adds auth and ships it.
  • Build more on your own machine. The Project Lab has guided FastAPI builds, from a layered service to a Redis leaderboard and WebSocket chat rooms.
  • Build and deploy a small SaaS backend. Pick a domain you know, add auth, a background job and a real Postgres, and keep it running with CI and monitoring for a few months.
  • Contribute to an open-source Python web project. FastAPI, Starlette, SQLAlchemy and Django all label beginner issues. Reading their code teaches you how the tools you used really work.
  • Read the official docs end to end. The FastAPI tutorial and advanced guide, the SQLAlchemy 2.0 unified tutorial and the PostgreSQL manual chapters on indexes and concurrency will answer questions for years.
Key terms
ASGI
The interface between an async Python web server like Uvicorn and an app like FastAPI: one async callable per connection.
dependency injection
Declaring what a route needs, such as a session or the current user, with Depends, so FastAPI provides it and tests can swap it.
migration
A versioned, reviewed script that changes the database schema the same way in every environment.
idempotency
The property that repeating a request has the same effect as sending it once, which makes retries safe.
outbox
A table written in the same transaction as your data, from which a worker reliably sends messages or emails later.
tenant isolation
Guaranteeing one customer can never read or change another customer's data, in code and in the database.
readiness check
An endpoint the platform polls to decide whether an instance should receive traffic yet.