Python / Uvicorn Fundamentals Interview Questions
1. What is Uvicorn and what problem does it solve for Python web development?
Uvicorn is a lightning-fast ASGI (Asynchronous Server Gateway Interface) web server for Python. It is the production-grade server that runs modern async Python frameworks like FastAPI and Starlette, bridging the gap between the network and the application code. Before ASGI, Python web servers use...
2. What is ASGI and how does it differ from WSGI?
WSGI (Web Server Gateway Interface) is the original Python standard for web servers and applications. It is synchronous - each request is handled sequentially, blocking while waiting for I/O. This makes it unsuitable for WebSockets, server-sent events, or highly concurrent async applications. ASG...
3. How do you install Uvicorn and what is the difference between the minimal and standard installations?
Uvicorn is available on PyPI and can be installed with pip. There are two installation variants targeting different use cases. Installation variants Variant Command What it includes Minimal (pure Python) pip install uvicorn h11 HTTP parser, asyncio event loop only - no Cython deps Standard (recom...
4. How do you run a basic Uvicorn server from the command line?
Uvicorn is started from the command line by specifying the application in module:attribute format. The module is the Python file (without .py ), and the attribute is the ASGI application object inside it. # File: main.py async def app (scope, receive, send): assert scope[ 'type' ] == 'http' await...
5. What are Uvicorn's default host, port, and log level settings?
Uvicorn's defaults are chosen to be safe for local development - binding only to localhost prevents accidental external exposure, while the info log level provides useful startup and access log output without being overwhelming. Uvicorn defaults Setting Default value Notes --host 127.0.0.1 Loopba...
6. What is uvloop and how does it improve Uvicorn's performance?
uvloop is a high-performance, drop-in replacement for Python's built-in asyncio event loop. It is implemented in Cython on top of libuv - the same C library used by Node.js - making it significantly faster than the standard asyncio loop for network I/O operations. asyncio vs uvloop Aspect asyncio...
7. What are httptools and h11, and when would you choose each?
Uvicorn supports two HTTP parser implementations, selectable via the --http flag. The default auto setting picks httptools if installed (via the standard extras) or falls back to h11 . h11 vs httptools Feature h11 httptools Implementation Pure Python (h11 library) Cython bindings to llhttp (C par...
8. How does Uvicorn's --reload flag work and what does it require?
The --reload flag enables automatic server restart when Python source files change. It is designed for development workflows, saving you from manually restarting the server after every code change. # Basic auto-reload (restarts when any .py file changes) uvicorn main:app --reload # Watch specific...
9. How do you run Uvicorn programmatically using uvicorn.run() and uvicorn.Config/Server?
Beyond the CLI, Uvicorn can be configured and launched entirely from Python code. This is useful when you need to customise server startup, integrate it into a larger application, or run it from within an existing async event loop. import uvicorn # Method 1: uvicorn.run() - simplest programmatic ...
10. What are Uvicorn workers and how do you configure multi-process deployments?
By default Uvicorn runs as a single process with a single event loop. To utilise multiple CPU cores and handle more concurrent requests, you can run multiple worker processes using the --workers flag. # Run 4 worker processes uvicorn main : app -- workers 4 # Workers can also be set via environme...
11. How do you deploy Uvicorn with Gunicorn for production?
For production deployments, the recommended pattern is to use Gunicorn as the process manager with Uvicorn as the worker class . Gunicorn provides mature process management (graceful restarts, signal handling, worker health monitoring) while Uvicorn provides the ASGI event loop inside each worker...
12. How do you configure SSL/TLS (HTTPS) in Uvicorn?
Uvicorn supports HTTPS natively by accepting a certificate and private key. This is useful for local development with HTTPS or for simple single-server deployments where a reverse proxy is not involved. # Run with SSL (requires certificate and private key) uvicorn main:app \ --ssl-keyfile ./key.p...
13. What is the ASGI lifespan protocol and how does Uvicorn support it?
The ASGI lifespan protocol provides startup and shutdown events for an ASGI application, allowing it to initialise resources (database connections, caches, background tasks) before serving requests and clean them up on shutdown. # FastAPI lifespan example (modern approach) from contextlib import ...
14. How do you configure Uvicorn logging and access logs?
Uvicorn uses Python's standard logging module with configurable log levels and optional access logging. Log configuration can be provided via CLI flags, environment variables, or a config file. # Log level options: critical, error, warning, info (default), debug, trace uvicorn main:app --log-leve...
15. What are proxy headers in Uvicorn and how do you configure trusted proxies?
When Uvicorn runs behind a reverse proxy (Nginx, Caddy, a load balancer), the proxy forwards requests on behalf of the original client. Without proxy header support, Uvicorn would see the proxy's IP as the client address and the internal scheme ( http ) rather than the original ( https ). The --p...
16. How does Uvicorn handle WebSocket connections?
Uvicorn has native WebSocket support, making it suitable for real-time applications like chat, live dashboards, and collaborative tools. WebSocket connections are handled via the websockets or wsproto library. # Pure ASGI WebSocket application async def app (scope, receive, send): if scope[ "type...
17. What is the --root-path setting in Uvicorn and when do you need it?
The --root-path setting tells Uvicorn (and consequently your ASGI application) that it is mounted at a specific URL path prefix. This is needed when your application is served at a sub-path behind a reverse proxy - for example, your app is at https://example.com/api/v1/ rather than https://exampl...
18. How do you use Uvicorn with a Unix domain socket instead of a TCP port?
Instead of binding to a TCP host:port, Uvicorn can listen on a Unix domain socket (UDS) - a special file on the filesystem used for inter-process communication. This is faster than TCP loopback for communication between processes on the same machine. # Bind to a Unix domain socket uvicorn main:ap...
19. What is the --factory flag in Uvicorn and when is it useful?
The --factory flag tells Uvicorn to treat the specified application path as a factory function - a callable that takes no arguments and returns an ASGI application - rather than as the application itself. # Without --factory: APP is the application object directly uvicorn main:app # With --factor...
20. How do you configure Uvicorn with environment variables?
Most Uvicorn CLI flags can be set via UVICORN_* prefixed environment variables , making it easy to configure in containerised environments and CI/CD pipelines without changing command-line arguments. # Environment variable equivalents of CLI flags export UVICORN_HOST = 0.0.0.0 export UVICORN_PORT...
21. What is Uvicorn's --interface flag and what application types does it support?
The --interface flag tells Uvicorn which application protocol to expect. The default auto setting detects the interface automatically, but you can force a specific mode. --interface options Value Interface WebSocket support Notes auto (default) Auto-detect ASGI3, ASGI2, or WSGI If ASGI Recommende...
22. How do you run Uvicorn inside a Docker container?
Uvicorn is widely used in containerised deployments. The key considerations are binding to the right host, setting the correct number of workers, and choosing between running Uvicorn directly or via Gunicorn. # Dockerfile - single-container Uvicorn FROM python:3.12-slim WORKDIR /app COPY requirem...
23. What is the difference between Uvicorn, Hypercorn, and Daphne as ASGI servers?
Several ASGI server implementations exist. Uvicorn is the most widely used, but Hypercorn and Daphne are also production-ready alternatives with different strengths. ASGI server comparison Feature Uvicorn Hypercorn Daphne HTTP/1.1 Yes Yes Yes HTTP/2 No Yes Yes HTTP/3 No Yes No WebSockets Yes Yes ...
24. How do you handle graceful shutdown in Uvicorn?
Uvicorn handles OS signals to shut down gracefully - completing in-flight requests before stopping. Understanding this is important for zero-downtime deployments and container orchestration. # Uvicorn responds to these OS signals: # SIGINT (Ctrl+C) - graceful shutdown # SIGTERM (kill default) - g...
25. What are the key Uvicorn settings for a production-hardened deployment?
Development defaults are convenient but inappropriate for production. A hardened production configuration disables debug features, removes identifying headers, tunes performance, and restricts network exposure. # Production-hardened Uvicorn command uvicorn main:app \ --host 0 .0.0.0 \ --port 8000...
26. How do you run Uvicorn with systemd for automatic restarts and log rotation?
On Linux servers without Docker, systemd is the standard way to run Uvicorn as a managed service - providing automatic restarts on failure, boot-time startup, and journal-based logging. # /etc/systemd/system/myapp.service [ Unit ] Description = My FastAPI Application After = network.target [ Serv...
27. What is the relationship between Uvicorn and FastAPI?
FastAPI and Uvicorn are complementary tools at different layers of the stack. FastAPI is the ASGI application framework ; Uvicorn is the ASGI server that runs it. FastAPI generates the HTTP routing, request validation, and response serialisation; Uvicorn handles the network I/O, event loop, and c...
28. How do you configure Uvicorn's timeout settings?
Uvicorn provides several timeout parameters that control how long the server waits for client activity and worker health before taking action. Uvicorn timeout settings Setting Default Purpose --timeout-keep-alive 5s Seconds to wait for a new request on a keep-alive connection before closing --tim...
29. How do you write a minimal ASGI application that works with Uvicorn without any framework?
Since Uvicorn implements ASGI, any Python callable that follows the ASGI specification can be run with it - no framework required. Understanding the raw ASGI interface deepens your understanding of how frameworks like FastAPI and Starlette work under the hood. # main.py - minimal HTTP ASGI app as...
30. How do you configure Uvicorn's log config file for custom logging formats?
Uvicorn's --log-config flag accepts a logging configuration in JSON or YAML format (using Python's dictConfig ) or in INI format ( fileConfig ). This enables structured logging, custom formats, and routing logs to different handlers. # loggi n g.jso n - cus t om log co nf ig i n dic t Co nf ig f ...
31. What is the --app-dir flag in Uvicorn and when do you need it?
The --app-dir flag adds a specific directory to sys.path before Uvicorn tries to import the application. This is useful when your application module is not in the current working directory or the standard Python path. # Project structure: # /project/ # src/ # myapp/ # main.py ← app lives here # W...
32. How do you test a Uvicorn-served ASGI application without starting the server?
For unit and integration testing, you don't want to actually start a server and make HTTP requests. The httpx library's ASGITransport (or Starlette's TestClient ) allows you to test ASGI applications in-process - no socket, no port, no server startup required. # Using httpx.AsyncClient with ASGIT...
33. What is Granian and how does it compare to Uvicorn as an ASGI server alternative?
Granian is a newer ASGI-compatible HTTP server written in Rust using Tokio and hyper. It is designed as a high-performance alternative to Uvicorn, with native HTTP/2, TLS, and WebSocket support baked in. Uvicorn vs Granian Feature Uvicorn Granian Language Python (Cython extensions) Rust HTTP/1.1 ...
34. What is the scope dictionary in the ASGI protocol and what does it contain?
The scope dictionary is the first argument passed to an ASGI application callable. It contains metadata about the incoming connection - its type (HTTP, WebSocket, or lifespan) and all relevant connection details. # Inspecting the scope in an ASGI app async def app (scope, receive, send): print(sc...
35. What are best practices for deploying Uvicorn in a Kubernetes environment?
Kubernetes brings its own deployment patterns that intersect with Uvicorn's configuration. Getting the combination right ensures zero-downtime deployments, proper health checking, and correct signal handling. Kubernetes + Uvicorn checklist Concern Recommendation Host binding Always --host 0.0.0.0...