Chapter 13. Production

If builders built buildings the way programmers wrote programs, the first woodpecker that came along would destroy civilization.

Gerald Weinberg, computer scientist

Preview

You have an application running on your local machine, and now you’d like to share it. This chapter presents many scenarios on how to move your application to production, and keep it running correctly and efficiently. Because some of the details can be very detailed, in some cases I’ll refer to helpful external documents rather than stuffing them in here.

Deployment

All the code examples in this book so far have used a single instance of uvicorn running on localhost, port 8000. To handle lots of traffic, you want multiple servers, running on the multiple cores that modern hardware provides. You’ll also need something above these servers to do the following:

  • Keep them running (a supervisor)

  • Gather and feed external requests (a reverse proxy)

  • Return responses

  • Provide HTTPS termination (SSL decryption)

Multiple Workers

You’ve probably seen another Python server called Gunicorn. This can supervise multiple workers, but it’s a WSGI server, and FastAPI is based on ASGI. Luckily, there’s a special Uvicorn worker class that can be managed by Gunicorn.

Example 13-1 sets up these Uvicorn workers on localhost, port 8000 (this is adapted from the official documentation). The quotes protect the shell from any special interpretation.

Example 13-1. Use Gunicorn with Uvicorn workers ...

Get FastAPI now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.