Python 3.12 • Django 5 • FastAPI • PostgreSQL
Python 3.12, Django 5 & FastAPI Backend Interview Questions & Answers (2026)
Crack Indian Product Startup, GCC & Service MNC Python backend interviews with deep CPython/GIL internals, Django ORM optimization, Async FastAPI, PostgreSQL MVCC, Celery reliability, and distributed system design.
Freshers CPython Internals Q1. What is the Python GIL (Global Interpreter Lock) and how do you achieve true parallelism in Python?
The GIL is a mutex in standard CPython ensuring only one native thread executes Python bytecode at a time to protect reference-counted objects. For I/O-bound workloads (HTTP, DB, files), threading or asyncio works great because C extensions release the GIL during I/O waits. For CPU-bound workloads, use multiprocessing (separate OS processes/memory), ProcessPoolExecutor, native C/Rust extensions (NumPy), or Python 3.13+ free-threaded builds (PEP 703).
Freshers Python Core Q2. Explain the difference between Generators (yield) and List Comprehensions, and when to use each.
List comprehensions eagerly compute and hold all elements in RAM (O(n) memory), which is fast for small collections you iterate multiple times. Generators produce items lazily one at a time via yield (O(1) memory) — critical in backend services when streaming 10-million-row CSV exports, parsing huge log files, or batching DB cursors without OOM crashes.
Freshers Django ORM Q3. What is the exact difference between select_related() and prefetch_related() in Django?
select_related() performs a SQL JOIN in a single query and is used for single-valued relationships (ForeignKey, OneToOneField). prefetch_related() runs a separate SQL query for the related table using WHERE id IN (...) and joins records in Python — ideal for ManyToManyField and reverse ForeignKey relations without duplicating parent rows.
Freshers FastAPI Basics Q4. How does FastAPI achieve high performance and automatic validation compared to Flask?
FastAPI runs natively on ASGI (Starlette + Uvicorn) enabling non-blocking async I/O concurrency, uses Pydantic v2 (Rust-powered pydantic-core) for ultra-fast request/response schema validation and serialization, provides clean Dependency Injection via Depends(), and auto-generates OpenAPI/Swagger docs directly from Python type hints.
Freshers Python Pitfalls Q5. Why are mutable default arguments (def add(item, bucket=[])) dangerous in Python?
Default argument values are evaluated ONCE at function definition time, not on each function call. Every call without an explicit second argument mutates the exact same shared list instance across requests — causing severe cross-user data leakage in web APIs. Always default to None and initialize inside the body (bucket = [] if bucket is None else bucket).
Experienced FastAPI Concurrency Trap Q6. What happens if you call a blocking synchronous DB/HTTP library inside an `async def` FastAPI endpoint?
Calling blocking sync code (like requests.get() or sync psycopg2) inside `async def` blocks the single asyncio event loop thread, stalling ALL concurrent requests handled by that worker! Either switch to true async drivers (httpx.AsyncClient, asyncpg, AsyncSession) OR define the route with regular `def` so FastAPI automatically offloads it to Starlette’s AnyIO threadpool.
Experienced Django & DRF Scale Q7. Why does OFFSET pagination slow down at page 5,000 and how do you fix it in DRF / FastAPI?
SQL OFFSET 100000 LIMIT 20 forces PostgreSQL to scan and discard 100,000 rows on every request (O(offset)) and produces duplicate/skipped rows if new records insert mid-browse. Replace it with Keyset / Cursor Pagination (WHERE (created_at, id) < (:cursor_ts, :cursor_id) ORDER BY created_at DESC, id DESC LIMIT 20) backed by a composite index for constant O(1) index-seek latency.
Experienced PostgreSQL Internals Q8. How does PostgreSQL MVCC work and why do long-running idle-in-transaction sessions cause table bloat?
MVCC (Multi-Version Concurrency Control) creates new row versions (dead tuples) on UPDATE/DELETE instead of overwriting in-place so readers never block writers. AUTOVACUUM can only reclaim dead tuples older than the oldest active transaction snapshot; a forgotten open transaction prevents vacuuming across the entire table, causing massive disk bloat and degrading index scans.
Experienced Celery & Async Jobs Q9. How do you make Celery background tasks reliable and idempotent in production?
Enable task_acks_late=True and task_reject_on_worker_lost=True so tasks re-queue if a worker crashes mid-job (at-least-once delivery), pass only primitive IDs rather than serialized ORM models, make every handler idempotent via DB unique keys/state checks, configure bounded exponential retry with jitter + Dead Letter Queues (DLQ), and set soft/hard time limits.
Experienced Zero-Downtime Migrations Q10. How do you add a NOT NULL column or index on a 50M-row PostgreSQL table with zero downtime in Alembic/Django?
Follow the Expand-and-Contract pattern: (1) create indexes with CREATE INDEX CONCURRENTLY (outside a transaction block) so writes never lock, (2) add new columns as nullable or with fast Postgres 11+ constant defaults, (3) backfill in small throttled batches, (4) add a CHECK (col IS NOT NULL) NOT VALID constraint and then VALIDATE CONSTRAINT (ShareUpdateExclusiveLock — non-blocking!) before dropping legacy columns in a subsequent release.
System Design Django vs FastAPI Q11. When would you choose Django + DRF vs FastAPI for a new production backend in 2026?
Choose Django 5 + DRF when building domain-heavy CRUD/SaaS/admin platforms that benefit from batteries-included ORM, migrations, auth/RBAC, Admin panel, and rapid team standardization. Choose FastAPI for high-concurrency async I/O gateways, streaming SSE/WebSocket AI backends, microservices proxying LLMs/APIs, or data-science inference services needing strict Pydantic schemas and asyncpg throughput.
System Design Rate Limiting Q12. Design a distributed API Rate Limiter in Python + Redis that handles bursts accurately without race conditions.
Implement a Sliding Window Counter or Token Bucket inside an atomic Redis Lua script (EVALSHA) keyed by user_id/API-key + route. Running check-and-increment inside Lua guarantees single-threaded atomicity across all Gunicorn/Uvicorn workers, sets automatic EXPIRE TTLs, and returns remaining quota + Retry-After headers in under 1ms.
System Design Database Connection Pooling Q13. Why does scaling Uvicorn/Gunicorn workers crash PostgreSQL connections and how does PgBouncer fix it?
Each PostgreSQL backend process consumes ~5–10 MB RAM; 20 containers × 4 workers × 10 pool connections = 800 DB connections, saturating CPU context switching and max_connections. Place PgBouncer in Transaction Pooling mode between Python apps and PostgreSQL so thousands of app connections multiplex cleanly onto ~50–100 active DB backends.
System Design Memory Profiling Q14. A FastAPI service memory grows steadily until OOMKill every 18 hours. How do you debug the leak?
Inspect Prometheus container RSS vs Python heap metrics, attach tracemalloc snapshots across endpoints (comparing top allocations over time) or py-spy / memray live flamegraphs. Common culprits in Python backends: unbounded in-memory dicts/lru_cache without maxsize, unclosed aiohttp/httpx sessions, circular references holding large request payloads, or Pandas/NumPy native allocator fragmentation.
System Design Webhook Security Q15. How do you securely ingest Razorpay/Stripe payment webhooks in Django/FastAPI?
Read the raw unparsed request body bytes, verify the HMAC-SHA256 signature using hmac.compare_digest() (constant-time comparison preventing timing attacks) plus timestamp tolerance against replay attacks, store event_id with a UNIQUE DB constraint for idempotency, return HTTP 200 immediately, and process heavy fulfillment asynchronously in Celery/Kafka.
Freshers Python Concurrency Q16. Show how Python 3.11+ asyncio.TaskGroup improves structured concurrency over asyncio.gather().
asyncio.TaskGroup guarantees structured cleanup: if any sibling task raises an exception, TaskGroup automatically cancels all remaining in-flight tasks and surfaces an ExceptionGroup — preventing leaked orphan coroutines in FastAPI backends.
Python 3.12 Structured Concurrency with asyncio.TaskGrouppython
import asyncio, httpx
async def fetch_dashboard(user_id: int) -> dict:
async with httpx.AsyncClient(timeout=3.0) as client:
async with asyncio.TaskGroup() as tg:
profile = tg.create_task(client.get(f"https://api.internal/users/{user_id}"))
orders = tg.create_task(client.get(f"https://api.internal/orders?u={user_id}"))
return {"profile": profile.result().json(), "orders": orders.result().json()}
Freshers Django ORM Q17. Show how Django F() expressions and select_for_update() prevent race conditions during stock decrements.
Computing stock -= 1 in Python memory loses concurrent updates. Combining transaction.atomic(), select_for_update(), or conditional QuerySet.filter(stock__gte=qty).update(stock=F("stock") - qty) executes atomically inside PostgreSQL.
Atomic Conditional Stock Deduction in Django ORMpython
from django.db.models import F
updated = Product.objects.filter(id=product_id, stock__gte=qty).update(
stock=F("stock") - qty
)
if updated == 0:
raise InsufficientStockError("Item out of stock")
Freshers Python Descriptors Q18. How do Python Descriptors (__get__, __set__) power @property and Django/SQLAlchemy ORM fields?
Any object implementing __get__, __set__, or __delete__ intercepts attribute access on an owner class. Django Field classes and SQLAlchemy InstrumentedAttributes use descriptors to translate model.email reads/writes into lazy DB loading, dirty-tracking, and type validation transparently.
Experienced FastAPI & Pydantic v2 Q19. Show a production FastAPI endpoint using Pydantic v2 field validation and Dependency Injection (Depends).
Pydantic v2 executes validation in Rust (pydantic-core), while FastAPI Depends() cleanly injects async DB sessions, auth principals, and rate limiters with zero global state and easy pytest dependency overrides.
FastAPI Async Route + Pydantic v2 + Depends()python
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
class CreateOrderIn(BaseModel):
sku: str = Field(min_length=3, max_length=32)
qty: int = Field(ge=1, le=20)
@router.post("/orders", status_code=201)
async def create_order(payload: CreateOrderIn, db=Depends(get_async_db), user=Depends(current_user)):
return await order_service.place(db, user.id, payload)
Experienced SQLAlchemy 2.0 Async Q20. Why does accessing a lazy relationship in Async SQLAlchemy 2.0 raise MissingGreenlet, and how do you fix it?
Implicit synchronous IO cannot run inside an async event loop. Always declare explicit eager-loading strategies on your select() statement — selectinload() for collections and joinedload() for many-to-one — or configure lazy="raise" globally so N+1 bugs fail loudly in tests.
SQLAlchemy 2.0 Async selectinload (Zero MissingGreenlet)python
stmt = (
select(Order)
.options(selectinload(Order.items))
.where(Order.user_id == user_id)
.order_by(Order.created_at.desc())
.limit(20)
)
orders = (await session.scalars(stmt)).all()
Experienced Django Architecture Q21. Why do senior teams avoid heavy business logic in Django Signals (post_save) in favor of an explicit Service Layer?
Django Signals create invisible control flow, fail to run during bulk_create()/QuerySet.update(), complicate transaction rollback boundaries (unless wrapped in transaction.on_commit()), and make unit tests brittle. Explicit service functions keep orchestration traceable, typed, and testable.
Experienced FastAPI BackgroundTasks vs Celery Q22. When is FastAPI BackgroundTasks acceptable vs when MUST you use Celery / ARQ / Kafka?
FastAPI BackgroundTasks runs inside the same worker process right after sending the HTTP response — acceptable only for tiny, non-critical fire-and-forget tasks like logging an audit ping. For emails, billing, PDFs, or AI jobs that require retries, persistence across deploys, and rate caps, always use Celery/Kafka.
System Design PostgreSQL Query Tuning Q23. Show how to verify an Index-Only Scan and composite Keyset Pagination index in PostgreSQL.
Run EXPLAIN (ANALYZE, BUFFERS) to inspect actual row estimates, shared buffer hits, and sort memory. A composite B-Tree index matching your exact filter + sort order eliminates heap fetches and O(offset) scans.
PostgreSQL Composite Index + Keyset Cursor Querysql
CREATE INDEX CONCURRENTLY idx_orders_user_created_id
ON orders (user_id, created_at DESC, id DESC);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_paise, created_at FROM orders
WHERE user_id = 42 AND (created_at, id) < ('2026-11-20T10:00:00Z', 99812)
ORDER BY created_at DESC, id DESC LIMIT 20;
System Design Webhook Security Q24. Show constant-time HMAC-SHA256 webhook verification in Python.
Always compute the HMAC digest over the raw unparsed request body bytes and compare using hmac.compare_digest() to prevent timing side-channel attacks.
Constant-Time Razorpay/Stripe HMAC Verificationpython
import hashlib, hmac
def verify_webhook_signature(raw_body: bytes, received_sig: str, secret: str) -> bool:
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, received_sig)
System Design ASGI Worker Sizing Q25. How do you size Gunicorn + Uvicorn workers for a containerized FastAPI or Django ASGI service?
For pure async I/O FastAPI services on Kubernetes, run 1 Uvicorn worker per vCPU container limit (let Kubernetes HPA scale pods cleanly without duplicating memory caches). For sync Django WSGI apps, size workers around (2 × vCPU) + 1 bounded by container RAM and PgBouncer pool capacity.