Python / Uvicorn Fundamentals Interview Questions
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:app --uds /tmp/uvicorn.sock # Programmatic: uvicorn.run("main:app", uds="/tmp/uvicorn.sock") # Nginx config to proxy to the Unix socket: # upstream app { # server unix:/tmp/uvicorn.sock; # } # server { # location / { # proxy_pass http://app; # } # } # Bind to a file descriptor (for socket activation, e.g. systemd): uvicorn main:app --fd 3 # systemd passes the pre-bound socket as fd 3
| Option | Flag | Use case |
|---|---|---|
| TCP host:port | --host + --port | Default; works everywhere |
| Unix domain socket | --uds /path/to/file.sock | Same-machine reverse proxy; slightly faster than TCP loopback |
| File descriptor | --fd | Systemd socket activation; container orchestrators |
Performance: Unix domain sockets bypass the TCP/IP stack entirely for same-machine communication, reducing latency. The improvement is measurable but modest - typically a few percent. The main practical benefit is avoiding port number management when running multiple services on the same host.
More Related questions...