Advanced Interview Questions

How would you implement JWT authentication?

  1. POST /token checks credentials against a stored password hash.
  2. It returns a signed JWT with sub and a short exp.
  3. An OAuth2PasswordBearer dependency reads the Bearer token, verifies signature and expiry, and loads the user.
  4. Protected endpoints depend on that "current user" dependency; role checks build on it.
  5. Secrets live in env/secret manager; refresh tokens or short sessions limit damage from leaks.

BackgroundTasks vs Celery?

BackgroundTasksCelery / task queue
runs in the same process after the responseseparate worker processes
lost if the process crashesdurable, with retries
light work: emails, logsheavy or critical work, scheduling

How do you manage startup and shutdown?

With a lifespan async context manager passed to FastAPI(lifespan=...): create pools, clients and models before yield, close them after. It replaces the deprecated on_event handlers.

How do you deploy FastAPI in production?

  • Package it in a slim Docker image running Uvicorn as a non-root user.
  • One process per container on Kubernetes/Cloud Run, scaling the number of containers; several workers on a single VM.
  • Put HTTPS, compression and rate limiting at the load balancer or gateway.
  • Add health checks, structured logs, metrics and tracing.

What is ASGI?

Asynchronous Server Gateway Interface: the async successor of WSGI. It lets Python web apps handle many concurrent connections, WebSockets and long-lived requests. FastAPI/Starlette are ASGI apps; Uvicorn and Hypercorn are ASGI servers.