150 Python Full Stack Interview Questions & Answers
From core CPython internals, async/await, and OOP to Django, FastAPI, PostgreSQL, SQLAlchemy, Celery, Redis, React, Docker, and scalable microservices architecture.
What You’ll Cover
Level: Beginner → Intermediate → Advanced → Senior Engineer
Technologies covered:
Python Core Language & Data Types
How does Python execute code and what is CPython ?
Python source code is compiled into intermediate bytecode (.pyc) and executed by the CPython virtual machine interpreter.
CPython is the standard reference implementation of Python written in C.
What is the difference between mutable and immutable types in Python?
Mutable types like lists, dicts, and sets can be modified in place after creation without changing their memory ID.
Immutable types like ints, floats, strings, and tuples cannot be altered and allocate new objects upon modification.
How does Python manage memory and what is Reference Counting ?
Python manages memory automatically using reference counting combined with a cyclic garbage collector.
Every object tracks references pointing to it, deallocating memory immediately when its reference count drops to zero.
What is the Global Interpreter Lock ( GIL ) and why does it exist?
The GIL is a mutex in CPython that allows only one native thread to execute Python bytecode at a time.
It ensures thread-safe memory management within CPython‘s reference counting system while limiting CPU-bound multithreading.
What is the difference between is and == in Python?
The is operator compares object identity, checking if two variables point to the exact same memory address.
The == operator compares equality, evaluating whether the values held by two objects are equivalent.
What are *args and **kwargs in Python function definitions?
*args captures excess positional arguments into a tuple.
**kwargs captures excess keyword arguments into a dictionary, enabling flexible dynamic function signatures.
How do List Comprehensions work and why are they faster than loops?
List comprehensions provide concise syntax for creating lists from existing iterables.
They run faster than standard for loops because bytecode execution happens at optimized C-level speed inside CPython.
What is the difference between a shallow copy and a deep copy?
A shallow copy constructs a new collection but inserts references to the original child objects.
A deep copy recursively duplicates both the parent collection and all nested child objects independently.
How does Exception Handling work with try , except , else, and finally ?
try encloses risky code, except catches specified exceptions, and else executes only if no exceptions occur.
The finally block executes unconditionally for guaranteed resource cleanup like closing files and database connections.
What are Python Dunder (Magic) Methods and how are they used?
Dunder methods begin and end with double underscores, defining built-in operator and protocol behaviors.
Examples include __init__ for initialization, __str__ for readable representation, and __len__ for collection sizing.
Functions, Scopes & Functional Programming
What is the LEGB Rule for variable scope resolution in Python?
Python resolves variable names hierarchically: Local, Enclosing closures, Global module level, and Built-in namespaces.
The first matching scope defines the variable unless explicitly overridden using global or nonlocal declarations.
How do Closures work in Python?
A closure is an inner function that retains access to variables from its enclosing scope even after the outer function finishes.
Closures capture lexical state, providing lightweight encapsulation without requiring full class declarations.
What is a Decorator and how does it modify function behavior?
A decorator is a callable that accepts a function, wraps its execution with cross-cutting logic, and returns a callable.
They are applied using @decorator syntax for concerns like authentication, caching, timing, and logging.
What are Lambda Functions and when should they be used?
Lambda functions are small, anonymous, single-expression inline functions defined using the lambda keyword.
They are best used for short throwaway operations inside higher-order functions like map, filter, and sorted.
How do map(), filter(), and reduce() work in Python?
map applies a transformation function to each item in an iterable lazily.
filter yields items that evaluate to true, while functools.reduce combines elements cumulatively into a single result.
What is the difference between an Iterable, an Iterator, and a Generator?
An iterable implements __iter__ returning an iterator, while an iterator implements __next__ yielding values sequentially.
A generator is an iterator created using functions containing yield, producing values lazily without storing entire lists in memory.
How does the yield keyword work in Python generators?
The yield keyword pauses function execution, saves its local stack frame, and yields a value to the caller.
When __next__ is called again, execution resumes immediately after the yield statement with state preserved.
What are Generator Expressions and how do they save memory?
Generator expressions use parenthesis syntax (x for x in iterable) to produce items lazily on demand.
They consume minimal memory because elements are computed one at a time rather than allocated in RAM.
What is functools.wraps and why is it used in decorators?
functools.wraps is a helper decorator applied to wrapper functions inside custom decorators.
It copies original function metadata like __name__, __doc__, and type annotations, preserving debugging introspection.
How does functools.lru_cache implement memoization?
lru_cache wraps a function with a Least Recently Used cache dictionary mapping arguments to return values.
Subsequent calls with identical arguments return instantly from cache, avoiding redundant expensive computations.
Object-Oriented Programming & Metaprogramming
What is the difference between Class Attributes and Instance Attributes?
Class attributes belong to the class definition itself and are shared across all instances.
Instance attributes belong to individual object instances, typically initialized inside __init__ using self.
What is the difference between @ classmethod and @ staticmethod ?
@classmethod receives the class object (cls) as its first argument, allowing factory instantiation and class-state access.
@staticmethod behaves like a plain function scoped inside a class namespace without accessing self or cls.
How does Multiple Inheritance and Method Resolution Order (MRO) work?
Python supports multiple inheritance using the C3 Linearization algorithm to determine method lookup order.
The MRO can be inspected via Class.mro(), preventing ambiguity and diamond inheritance conflicts.
What does the super() function do in Python?
super() returns a proxy object delegating method calls to the next class in the current class’s MRO.
It ensures cooperative multiple inheritance without hardcoding explicit parent class names.
How do Property Decorators (@property) work in Python?
@property turns a method into a getter, allowing attribute access syntax while executing custom logic.
Companion @setter and @deleter decorators enable encapsulation, input validation, and computed properties.
What are Abstract Base Classes (ABCs) in the abc module?
ABCs define interface contracts that derived classes must implement using the @abstractmethod decorator.
Instantiating a subclass that lacks required abstract methods raises a TypeError at runtime.
What is Duck Typing and how does Python apply it?
Duck typing determines an object’s suitability by presence of methods and properties rather than its explicit class hierarchy.
If an object implements the required interface like __iter__, Python treats it as valid regardless of type.
What are __slots__ and how do they optimize memory?
__slots__ declares a fixed set of attribute names, replacing the default instance __dict__ with a compact array.
This significantly reduces memory footprint and accelerates attribute access when instantiating millions of objects.
What are Context Managers and the __enter__ and __exit__ methods?
Context managers manage runtime resources deterministically using the with statement.
__enter__ sets up the resource, while __exit__ guarantees cleanup and error handling even if exceptions occur.
What is a Metaclass in Python?
A metaclass is a class whose instances are classes themselves; type is the default metaclass in Python.
Custom metaclasses intercept class creation, validating attributes and registering classes dynamically at import time.
Advanced Python Internals & Concurrency
What is the difference between Multiprocessing and Multithreading in Python?
Multithreading shares one process and memory space but is constrained by the GIL for CPU-bound tasks.
Multiprocessing spawns separate operating system processes with independent GILs, enabling true multi-core CPU parallelism.
How does the asyncio event loop work in Python?
asyncio runs a single-threaded cooperative multitasking event loop that orchestrates asynchronous tasks and callbacks.
When a coroutine awaits an I/O operation, control yields back to the loop to execute other ready tasks concurrently.
What is the difference between async def and normal def functions?
async def defines a coroutine function that returns a coroutine object when called rather than executing immediately.
Coroutines must be awaited using await or scheduled on an event loop to execute their asynchronous logic.
What is asyncio.gather () vs asyncio.wait ()?
asyncio.gather runs multiple awaitable tasks concurrently and returns aggregated results in order.
asyncio.wait accepts a collection of tasks and returns sets of completed and pending tasks with fine-grained control.
What is the concurrent.futures module used for?
concurrent.futures provides high-level ThreadPoolExecutor and ProcessPoolExecutor abstractions for managing background worker pools.
It executes callables asynchronously, returning Future objects representing eventual task completion.
How does Type Hinting and the typing module benefit Python code?
Type hinting specifies expected argument and return types, improving code readability and IDE auto-completion.
Static analysis tools like mypy catch bugs before runtime without affecting CPython‘s dynamic execution speed.
What are Dataclasses in Python and how do they compare to Pydantic ?
Dataclasses (@dataclass) automatically generate boilerplate methods like __init__, __repr__, and __eq__ based on type annotations.
Pydantic extends this by performing strict runtime data validation, parsing, and serialization, ideal for web APIs.
How does Python’s cyclic garbage collector detect circular references?
The cyclic GC tracks container objects using doubly-linked lists across three generational collection pools.
It periodically detects unreachable isolated subgraphs where objects reference each other but are unreachable from roots.
What is the collections module and what useful data structures does it provide?
The collections module provides specialized containers: deque for fast double-ended queues, Counter for frequency counting,
defaultdict for auto-initializing missing keys, and namedtuple for readable lightweight tuples.
How does the struct module handle binary data in Python?
The struct module packs Python values into binary bytes and unpacks binary strings into Python objects using format strings.
It enables low-level network socket communication, binary file parsing, and C library data interchange.
SQL, PostgreSQL & Relational Database Design
What is the difference between INNER JOIN, LEFT JOIN, and FULL OUTER JOIN?
INNER JOIN returns rows with matching values in both tables.
LEFT JOIN returns all rows from the left table with matching right rows, filling non-matches with NULL.
FULL OUTER JOIN returns all rows with matches from either table.
What are Clustered and Non-Clustered Indexes in relational databases?
A clustered index determines the physical storage order of table rows on disk.
A non-clustered index is a separate B-tree structure holding indexed column keys and pointers to the physical rows.
What are the ACID properties in database transaction management?
Atomicity ensures all operations succeed or roll back entirely. Consistency maintains all database schema constraints.
Isolation keeps concurrent transactions independent, and Durability guarantees committed changes survive system crashes.
What are Transaction Isolation Levels in PostgreSQL ?
PostgreSQL supports Read Committed, Repeatable Read, and Serializable isolation levels.
They control exposure to concurrency anomalies like dirty reads, non-repeatable reads, and phantom reads.
What is the N+1 query problem and how do you diagnose it?
The N+1 problem occurs when an application executes 1 query for parents followed by N individual queries for children.
It creates excessive database roundtrips and is diagnosed using query profilers and ORM logging.
What is Database Normalization and why is 3NF standard?
Normalization organizes relational tables to reduce data redundancy and eliminate insert, update, and delete anomalies.
Third Normal Form (3NF) ensures non-key columns depend solely on the primary key, providing optimal data integrity.
How do Connection Pools work and why are they essential in Python?
Opening new database TCP connections is slow and resource-heavy; connection pools keep pre-authenticated connections open for reuse.
They dramatically reduce latency and protect databases from connection exhaustion under high traffic.
What are PostgreSQL JSONB columns and when should they be used?
JSONB stores decomposed binary JSON data supporting GIN indexing and fast key-value lookups.
Use JSONB for semi-structured data, dynamic user attributes, and evolving schemas without altering relational tables.
What is Database Sharding vs Read Replicas?
Read replicas replicate primary data to multiple servers to multiply read query throughput horizontally.
Sharding splits database rows horizontally across separate database nodes based on a partition shard key.
How do Database Deadlocks occur and how do you prevent them?
Deadlocks occur when two transactions hold locks on resources the other needs, creating an unresolvable cyclic wait.
Prevent deadlocks by updating tables in identical sequence, keeping transactions brief, and using proper indexes.
Django Architecture & ORM
What is the MVT (Model-View-Template) architecture in Django ?
Model handles data structure and database queries. View processes business logic and HTTP requests.
Template renders user-facing HTML presentation, separating concerns cleanly.
How does Django ORM work and what is QuerySet laziness?
Django ORM maps Python model classes to database tables and translates Python methods into SQL queries.
QuerySets are lazy, executing SQL commands only when iterated, sliced, or evaluated with methods like list().
What is select_related () vs prefetch_related () in Django ?
select_related performs a SQL JOIN for single-valued relationships (ForeignKey, OneToOne) in one database roundtrip.
prefetch_related executes a separate query for multi-valued relationships (ManyToMany, reverse FK), merging results in Python.
How do Django Migrations work under the hood?
makemigrations inspects model changes and generates versioned migration Python files.
migrate applies these changes to database tables, tracking applied history in the django_migrations table.
What are Django Signals and when should you use them?
Signals allow decoupled applications to get notified when framework actions occur (like post_save or pre_delete).
Use signals for cross-cutting triggers like sending emails or invalidating caches, but avoid overusing them for core logic.
How does Django Middleware process HTTP requests and responses?
Middleware classes form a layered pipeline intercepting requests before reaching views and responses before returning to clients.
They handle cross-cutting features like session authentication, CSRF validation, and security headers.
What are Django Model Managers and QuerySet methods?
A Model Manager (like objects) is the interface through which Django models perform database queries.
Custom managers extend models with reusable, domain-specific filter queries like Order.objects.completed().
How do you handle Database Transactions in Django with atomic()?
transaction.atomic() wraps code blocks in database transactions, guaranteeing all operations succeed or roll back on error.
It can be used as a context manager or method decorator to protect transactional consistency.
What is the Django User Model and how should you customize it?
Django provides a default user model with username authentication, but production apps should use AbstractUser.
Customizing early allows using email as the primary login field and adding profile attributes without future migration pains.
How does Django ‘s Form and ModelForm validation work?
Forms validate incoming data using clean_<fieldname>() methods and general clean() validation.
Valid data populates cleaned_data, while invalid entries populate form.errors with localized validation messages.
Django REST Framework (DRF) & API Design
What is the difference between Serializers and ModelSerializers in DRF?
Serializer provides explicit field mapping and custom serialization logic independent of database models.
ModelSerializer automatically generates serializer fields, validators, and create/update logic based on Django models.
What are ViewSets and Routers in Django REST Framework?
ViewSets group CRUD logic for a resource into a single class rather than multiple individual view handlers.
Routers automatically generate standard RESTful URL patterns for all ViewSet actions.
How does API Authentication work in DRF?
DRF provides modular authentication classes: SessionAuthentication for web clients, TokenAuthentication, and JWT via simplejwt.
Authentication credentials validate the request and populate request.user and request.auth.
How does DRF handle Permissions and custom permission classes?
Permission classes check whether an authenticated user can access views (has_permission) or specific object instances (has_object_permission).
Custom classes inherit BasePermission and return boolean authorization decisions.
What is Pagination in DRF and what styles are available?
Pagination splits large query results into manageable pages, reducing server memory and network bandwidth.
DRF supports PageNumberPagination, LimitOffsetPagination, and high-performance CursorPagination.
How does Throttling ( Rate Limiting ) work in DRF?
Throttles restrict the rate of API requests made by authenticated users and anonymous IP addresses.
Exceeding configured rate limits returns an HTTP 429 Too Many Requests response with a Retry-After header.
What are SerializerMethodFields and when should you avoid them?
SerializerMethodField computes dynamic read-only values by executing a custom Python method during serialization.
Avoid executing database queries inside SerializerMethodField because it introduces severe N+1 query performance problems.
How do you implement nested serializers with writable support in DRF?
Nested serializers serialize related parent-child models within a single JSON payload.
To support writable creation, override the create() and update() serializer methods to pop and persist nested child objects explicitly.
How does Content Negotiation and Filtering work in DRF?
Content negotiation selects the response renderer (JSON, Browsable API) based on client Accept headers.
django-filter integrates with DRF to provide declarative query parameter filtering across API endpoints.
How do you optimize slow DRF API endpoints?
Optimize endpoints using select_related and prefetch_related to eliminate N+1 queries.
Restrict returned fields using values() or only(), paginate datasets, and cache frequent read responses in Redis.
FastAPI, Pydantic & Async Web Frameworks
What is FastAPI and why is it so fast?
FastAPI is a modern, high-performance async Python web framework built on Starlette and Pydantic.
It achieves high throughput by running native async/await on the ASGI standard and compiling validations in Pydantic.
What is the role of Pydantic in FastAPI ?
Pydantic defines data schemas using Python type annotations, performing automatic input validation, type coercion, and JSON serialization.
It raises descriptive validation errors and automatically populates OpenAPI Swagger documentation.
What is the difference between WSGI and ASGI ?
WSGI is the synchronous Python web server gateway standard used by traditional frameworks like Django and Flask.
ASGI is the asynchronous standard supporting async/await, WebSockets, HTTP/2, and long-lived streaming connections.
What are Uvicorn and Gunicorn in Python deployments?
Uvicorn is a lightning-fast ASGI web server implementation running uvloop and httptools.
Gunicorn acts as a process manager running multiple Uvicorn worker processes to maximize multi-core CPU utilization.
How does Dependency Injection work in FastAPI with Depends ?
FastAPI uses Depends() in route signatures to declare reusable dependencies like database sessions, authentication, and security checks.
FastAPI resolves dependency graphs automatically, managing their lifecycles and sharing cached results within requests.
What are Path Parameters, Query Parameters, and Request Bodies in FastAPI ?
Path parameters match URL segments (/items/{item_id}). Query parameters match URL query strings (?limit=10).
Request bodies are declared using Pydantic models and deserialized from incoming JSON payloads.
How does Background Tasks work in FastAPI ?
FastAPI‘s BackgroundTasks parameter schedules lightweight background operations like sending confirmation emails after returning HTTP responses.
It runs tasks within the current server process without blocking the immediate client response.
How does FastAPI handle Global Exception Handlers?
Custom exception handlers are registered using @app.exception_handler(CustomException) to catch domain exceptions.
They format standardized JSON error responses, preventing uncaught exceptions from returning generic 500 errors.
How does Middleware work in FastAPI ?
Middleware wraps incoming HTTP requests before route handlers and outgoing responses before transmission.
Common middleware includes CORSMiddleware, GZipMiddleware, and custom timing and correlation ID interceptors.
How does FastAPI automatically generate OpenAPI (Swagger) documentation?
FastAPI inspects route definitions, type annotations, and Pydantic schemas to generate an interactive OpenAPI JSON specification.
It serves Swagger UI at /docs and ReDoc at /redoc out of the box with zero manual documentation effort.
SQLAlchemy & Modern Python Data Access
What is SQLAlchemy and how do Core and ORM differ?
SQLAlchemy is a Python SQL toolkit and ORM providing database abstraction and connection management.
SQLAlchemy Core provides a schema-centric SQL expression language, while ORM maps relational tables to domain classes.
What is the SQLAlchemy Session and how does the Unit of Work pattern work?
The Session manages database transactions and tracks in-memory entity modifications.
Under the Unit of Work pattern, changes accumulate in memory and are persisted atomically upon calling session.commit().
How does modern Async SQLAlchemy 2.0 work?
SQLAlchemy 2.0 provides native async engines (AsyncEngine) and sessions (AsyncSession) compatible with asyncpg.
Queries execute using async/await syntax like await session.execute(select(User)), preventing event loop blocking.
What is Alembic and how does it handle database migrations?
Alembic is the database migration tool for SQLAlchemy that generates and applies versioned migration scripts.
It compares SQLAlchemy metadata models against database schemas to auto-generate upgrade() and downgrade() functions.
What are SQLAlchemy Relationship Loading strategies?
Loading strategies control when related records load: selectinload uses an IN query ideal for async collections,
joinedload executes SQL JOINs for one-to-one links, and lazyload defers queries until attribute access.
How does SQLAlchemy prevent SQL injection vulnerabilities?
SQLAlchemy automatically binds query parameters as typed literal data placeholders across all Core and ORM statements.
Parameters are transmitted separately from SQL command text, ensuring untrusted user inputs can never execute as SQL code.
What are Declarative Base and Mapped Columns in SQLAlchemy 2.0?
DeclarativeBase is the base class for ORM models in SQLAlchemy 2.0, utilizing Mapped[] type annotations.
mapped_column() combines type hinting, database column configuration, and nullability into concise declarations.
How do you handle Many-to-Many relationships in SQLAlchemy ?
Many-to-Many relationships require an association table holding foreign keys pointing to both related entity tables.
The relationship() function maps the association table using the secondary parameter on both domain model classes.
How do you execute Raw SQL in SQLAlchemy safely?
Raw SQL is executed using the text() construct, binding parameters with colon syntax (text(“SELECT * FROM users WHERE id = :id”)).
Parameters pass safely via session.execute(query, {“id”: user_id}), ensuring strict parameterization.
What is the difference between flush() and commit() in SQLAlchemy ?
flush() emits SQL INSERT, UPDATE, and DELETE statements to the database transaction, populating generated IDs without committing.
commit() permanently commits the active transaction to the database, writing changes to disk and closing the transaction.
Authentication, Security & Cryptography
How does Password Hashing work with bcrypt and Argon2 in Python?
Passwords must never be stored in plain text; bcrypt and Argon2 apply cryptographic salt and thousands of computation iterations.
This key stretching dramatically slows down hardware-accelerated brute-force attacks and eliminates rainbow table exploits.
How does JWT (JSON Web Token) Authentication work in Python APIs?
Upon login, the server cryptographically signs a Base64-encoded token containing user claims and expiration timestamps.
Clients send this token inside the Authorization: Bearer <token> header, which the API validates statelessly without database lookups.
What is the difference between Access Tokens and Refresh Tokens ?
Access tokens are short-lived (e.g. 15 minutes) for authenticating API requests directly.
Refresh tokens are long-lived, securely stored in the database, and used solely to issue fresh access tokens when expired.
How do you prevent Cross-Site Scripting ( XSS ) in Python web applications?
Template engines like Jinja2 and Django auto-escape HTML variables by default to neutralize script injection.
Content Security Policy (CSP) headers restrict script execution sources, and untrusted inputs are sanitized before storage.
How does Cross-Site Request Forgery ( CSRF ) protection work in Django ?
Django issues a unique, cryptographically random CSRF token in an HTTP-only cookie and embeds a matching token in web forms.
On POST requests, middleware verifies that both tokens match, stopping unauthorized cross-origin state changes.
What is CORS and how do you configure it in FastAPI and Django ?
Cross-Origin Resource Sharing (CORS) is a browser security protocol restricting cross-origin HTTP requests.
Configure CORS middleware by specifying allowed client origins, HTTP methods, and authorization headers explicitly.
What is Role-Based Access Control ( RBAC ) vs Permission-Based Access?
RBAC assigns access rights to coarse user roles (Admin, Editor), checking role membership.
Permission-based access assigns granular capabilities (posts:delete), providing superior flexibility and custom security policies.
What is Rate Limiting and how do you protect Python APIs from brute-force?
Rate limiting restricts requests per IP or user token using algorithms like Token Bucket or Sliding Window backed by Redis.
Exceeding limits blocks abuse with HTTP 429 responses, defending against denial-of-service and credential stuffing.
How should Production Secrets and API Keys be managed in Python?
Production secrets must never be committed to source code repositories.
Use environment variables (.env with python-dotenv) or cloud vaults (AWS Secrets Manager, HashiCorp Vault) loaded at startup.
What is Server-Side Request Forgery ( SSRF ) and how do you defend against it?
SSRF occurs when an attacker tricks the server into making HTTP requests to internal networks or cloud metadata APIs.
Defend against SSRF by validating URL protocols, whitelisting permitted domains, and blocking internal IP ranges (127.0.0.1, 169.254.169.254).
Asynchronous Tasks, Celery & Redis
What is Celery and why is an asynchronous task queue necessary?
Celery is a distributed task queue that runs long-running jobs (emails, PDF generation, video encoding) outside the web request cycle.
Offloading heavy tasks ensures web servers respond to HTTP requests in milliseconds without timing out.
What is a Message Broker and why is Redis or RabbitMQ used with Celery ?
A message broker acts as the communication buffer holding serialized task messages between the web application and Celery workers.
RabbitMQ provides robust enterprise queuing, while Redis provides ultra-fast in-memory queue storage and pub/sub capabilities.
What is the difference between a Message Broker and a Result Backend in Celery ?
The message broker transports task messages from producer to worker processes.
The result backend stores the return values, completion status, and exception traces of finished tasks for later retrieval.
How do you schedule periodic tasks in Celery with Celery Beat ?
Celery Beat is a scheduler daemon that dispatches tasks to the message broker at designated intervals or cron schedules.
Tasks configure schedule rules in settings using crontab() for daily reports, database cleanup, or billing jobs.
How do you handle Task Retries, Deadlines, and Failures in Celery ?
Celery tasks configure retry policies using autoretry_for, retry_backoff to introduce exponential backoff delays, and max_retries.
Tasks exceeding time limits trigger SoftTimeLimitExceeded exceptions, allowing graceful cleanup before hard termination.
What is the Cache-Aside pattern and how do you implement it with Redis ?
The application checks Redis for cached data first; if missing, it queries the database and stores the result in Redis with a TTL.
Subsequent requests read directly from Redis in memory, eliminating heavy database query load.
What are Redis Data Structures and when should you use them?
Redis provides Strings for key-value caching, Hashes for object representation, Lists for queues,
Sets for unique tags, and Sorted Sets (ZSet) for leaderboards and sliding-window rate limiters.
How do you handle Redis Cache Invalidation properly?
Invalidate cache keys when underlying database records mutate, or configure short Time-To-Live (TTL) expiration intervals.
Using key namespacing (e.g. user:123:profile) enables pattern-based deletion and clean multi-tenant isolation.
What is a Cache Stampede (Dog-Piling) and how do you prevent it?
A cache stampede happens when a popular cache key expires and thousands of concurrent requests query the database at once.
Prevent stampedes using distributed locks (Redlock), probabilistic early expiration, or background cache pre-warming.
What is Flower in the Celery ecosystem?
Flower is a web-based real-time monitoring and administration tool for Celery clusters.
It visualizes worker states, task progress, runtime graphs, and error rates, and allows remote task termination and rate adjustment.
Real-Time Communication & WebSockets
What is the difference between HTTP Polling, Server-Sent Events , and WebSockets ?
HTTP polling sends repeated request queries to check for new data, creating excessive network overhead.
Server-Sent Events (SSE) pushes one-way server-to-client updates over standard HTTP.
WebSockets establishes a persistent, full-duplex TCP connection allowing simultaneous bidirectional communication.
What are Django Channels and how do they enable WebSockets in Django ?
Django Channels extends Django beyond standard HTTP by introducing an ASGI interface supporting WebSockets, chat protocols, and IoT.
It handles asynchronous protocols while retaining access to Django models and authentication systems.
What is the Channel Layer in Django Channels ?
The Channel Layer is a communication system (usually backed by Redis) that allows multiple server instances to exchange messages.
It enables broadcasting messages across distributed WebSocket consumers and managing real-time chat groups.
How do WebSocket Consumers work in Django Channels ?
Consumers are ASGI equivalents of Django views that manage the lifecycle of WebSocket connections.
They implement connect, receive, and disconnect handlers, decoding JSON messages and forwarding them to client sockets.
How do WebSockets work natively in FastAPI ?
FastAPI provides native WebSocket endpoints using the @app.websocket(“/ws”) decorator and the WebSocket interface.
Endpoints accept incoming connections using await websocket.accept() and exchange messages using receive_text() and send_text().
How do you handle Authentication in WebSockets ?
Standard HTTP Authorization headers cannot always be sent during browser WebSocket handshakes.
Authenticate by passing JWT tokens inside query parameters (wss://api/ws?token=xyz) or verifying session cookies during the HTTP upgrade.
How do you scale WebSockets horizontally across multiple servers?
WebSockets require stateful connections; use Redis Pub/Sub backplanes to broadcast messages across server nodes.
Configure load balancers with session affinity (sticky sessions) to keep TCP socket connections stable.
What are Server-Sent Events (SSE) and when should you prefer them over WebSockets ?
SSE pushes real-time text streams over plain HTTP using text/event-stream content types, with automatic browser reconnection.
Prefer SSE over WebSockets for one-way feeds like live dashboards, stock price tickers, and streaming AI/LLM responses.
How do you stream LLM / AI token responses using FastAPI ?
FastAPI streams tokens using StreamingResponse wrapping an asynchronous generator function.
The generator yields chunks from OpenAI or Ollama in real time, flushing tokens to the client as they generate.
How do you handle Heartbeats and Ping/Pong frames in WebSockets ?
Network proxies and firewalls terminate idle TCP connections after inactivity.
WebSocket servers and clients exchange periodic ping/pong control frames to keep connections alive and detect dropped clients quickly.
Frontend Integration (React, Next.js & TypeScript)
How do React and Next.js SPAs communicate with Python APIs?
Frontends send asynchronous HTTP requests to Python APIs using Fetch or Axios, passing JSON payloads.
Authentication is handled by attaching JWT tokens inside the Authorization: Bearer <token> header or using secure HTTP-only cookies.
What is Server-Side Rendering (SSR) vs Client-Side Rendering (CSR) in full stack?
CSR downloads empty HTML and JavaScript bundles, executing rendering in the client’s browser.
SSR renders HTML on the Next.js server before sending it to the client, delivering instant initial page loads and superior SEO.
How do you handle JWT Token Refresh in React using Axios Interceptors?
Axios response interceptors intercept HTTP 401 Unauthorized responses from the Python backend.
The interceptor pauses requests, calls the token refresh endpoint with the refresh token, and replays failed requests with the new access token.
What is the Backend for Frontend ( BFF ) pattern in Python architectures?
The BFF pattern introduces dedicated backend proxy services tailored specifically to the needs of individual frontend clients.
The BFF manages authentication cookies, aggregates multiple microservice API calls, and shields internal APIs from the public internet.
How does TanStack Query ( React Query) optimize API data fetching?
TanStack Query manages server state caching, background re-fetching, deduplication, and optimistic updates in React.
It eliminates redundant HTTP requests to Python APIs and keeps frontend state synchronized seamlessly.
What is Next.js App Router and Server Components ?
The App Router architecture renders ReactServer Components (RSC) exclusively on the server by default.
Server Components fetch data from Python backends without shipping bulky client-side JavaScript libraries to browser users.
How do you securely handle File Uploads from React to a Python API?
Small files upload via multipart/form-data using FormData objects, validated and processed by Django or FastAPI.
For large files, the Python backend generates presigned S3 URLs, allowing the browser to upload directly to cloud storage safely.
What is TypeScript and why is it preferred for modern Python full stack projects?
TypeScript adds static typing to JavaScript, catching type mismatches between frontend API models and backend Python schemas.
Tools can auto-generate TypeScript interfaces directly from FastAPI‘s OpenAPI JSON schemas, ensuring complete end-to-end contract safety.
How do you handle Global State Management in modern React ?
Modern React separates UI state from server state, using TanStack Query for server data and lightweight libraries like Zustand for UI state.
This eliminates boilerplate Redux code while providing clean, decoupled state updates across components.
How do you serve compiled React / Next.js static assets with Python web servers?
Static frontend production builds (HTML, JS, CSS) are served by high-performance reverse proxies like NGINX or CDNs like Cloudflare.
Python application servers (Gunicorn, Uvicorn) focus exclusively on dynamic /api/* endpoints, maximizing resource efficiency.
Automated Testing & Quality Assurance
What is pytest and why is it preferred over unittest in Python?
pytest provides clean, concise test writing using standard Python assert statements rather than verbose self.assertEqual methods.
Its powerful fixture system, parameterized test support (@pytest.mark.parametrize), and rich plugin ecosystem make it industry-standard.
What are pytest Fixtures and how does fixture scope work?
Fixtures prepare test data, mock environments, and database states using dependency injection syntax.
Scopes control lifetime: function runs per test, module runs per test file, and session runs once for the entire test suite.
How does Mocking work with unittest.mock in Python?
Mocking replaces real dependencies (external APIs, payment gateways, emails) with simulated Mock or MagicMock objects.
patch intercepts imports during test execution, asserting that methods were called with expected arguments without executing real side-effects.
How do you test asynchronous code in pytest with pytest-asyncio ?
The pytest-asyncio plugin enables testing async def coroutines using @pytest.mark.asyncio.
It runs the test within an asyncio event loop, allowing await execution against async FastAPI endpoints and async database queries.
What is the Test Client in FastAPI and Django ?
FastAPI‘s TestClient (built on HTTPX) and Django‘s APIClient simulate HTTP requests directly against the application pipeline.
They test routing, serialization, and authentication end-to-end in memory without spinning up real web servers.
What is Database Testing and how do transactions isolate tests?
Tests run within database transactions that roll back automatically upon test completion, keeping test data isolated and clean.
pytest-django provides the @pytest.mark.django_db fixture to manage test databases seamlessly.
What is Code Coverage and how do you measure it with coverage.py ?
Code coverage measures the percentage of application source code lines executed during test runs.
Run pytest –cov=app to generate line and branch coverage metrics, highlighting untested logic branches and error handlers.
What is Mutation Testing and how does mutmut work in Python?
Mutation testing tests the quality of your test suite by introducing deliberate bugs (“mutants”) into your Python source code.
If tests fail, the mutant is killed (tests are effective); if tests pass, the mutant survived, revealing weak test assertions.
What are Integration Tests vs Unit Tests in Python Full Stack?
Unit tests test isolated functions in memory with dependencies mocked.
Integration tests verify that components work together against real databases, middleware, and API endpoints.
How do you implement End-to-End (E2E) testing with Playwright in Python?
Playwright automates Chromium, Firefox, and WebKit browsers using Python async APIs.
E2E tests interact with frontend UI buttons and forms, verifying that user workflows function correctly against the live full stack app.
Microservices, Docker & Cloud Architecture
What is the difference between a Monolith, Modular Monolith, and Microservices?
A Monolith packages all domain logic into a single codebase and shared database, offering simplicity and unified transactions.
Microservices divide functionality into independently deployable services with isolated databases, enabling independent scaling and autonomy.
How do you Dockerize a Python application efficiently with multi-stage builds?
Multi-stage Dockerfiles compile C dependencies and wheel packages in a builder stage and copy only finished artifacts to a slim runtime image.
This minimizes production image size, improves deployment speed, and removes build toolchain security vulnerabilities.
What is Docker Compose and how does it manage local development?
Docker Compose defines multi-container applications (FastAPI, PostgreSQL, Redis, Celery, NGINX) in a single docker-compose.yml file.
A single docker compose up command spins up all interconnected services with automated networking and volume persistence.
What is an API Gateway and what role does NGINX or Traefik play?
An API Gateway acts as the single public entry point for microservices, handling SSL termination, reverse proxy routing, and rate limiting.
NGINX and Traefik distribute client traffic to internal microservice instances while shielding internal network topologies.
What is the Outbox Pattern and why is it essential for Distributed Transactions?
Saving a database record and publishing a message to a broker are two distinct operations that cannot share atomic ACID transactions.
The Outbox Pattern writes messages into a local database outbox table in the same transaction, with a worker publishing them to the broker reliably.
What is Circuit Breaker pattern and how does it prevent cascading failures?
The Circuit Breaker pattern detects remote service failures and fails fast immediately without waiting for timeouts.
When error thresholds are reached, the circuit opens, returning fallbacks and allowing the struggling service time to recover.
How does Distributed Tracing work with OpenTelemetry in Python?
OpenTelemetry instruments Python applications to generate traces and spans that follow HTTP requests across distributed microservices.
It propagates traceparent headers across network calls, exporting traces to Jaeger or Datadog for visual latency bottleneck analysis.
What is Horizontal Auto-Scaling and how does Kubernetes scale Python pods?
Kubernetes Horizontal Pod Autoscaler (HPA) automatically adjusts the number of running application pods based on CPU, memory, or request queues.
Stateless Python containers scale dynamically to handle traffic spikes during peak hours and scale down during quiet periods.
What is a CI/CD Pipeline and how do GitHub Actions automate Python deployments?
A CI/CD pipeline automates testing, building, and deployment workflows triggered on git push events.
GitHub Actions runs linters (ruff, black), executes pytest test suites, builds Docker images, and deploys containers to production automatically.
SYSTEM DESIGN: Design a Production Full Stack E-Commerce Platform with Python & React .
The frontend uses Next.js for server-rendered SEO catalog pages, protected by Cloudflare CDN and WAF.
NGINX routes API traffic to FastAPI microservices: Identity Service, Product Catalog, Order Service, and Payment Service.
High-frequency catalog reads are cached in Redis using the Cache-Aside pattern, while orders store in PostgreSQL.
Asynchronous tasks like email receipts, invoice PDFs, and inventory syncing are processed by Celery workers backed by RabbitMQ.
