Python Core Language, AsyncIO & Backend Architecture Master Interview Bank
CPython internals, GIL (Global Interpreter Lock), memory management, AsyncIO event loop, generators, decorators, typing, and FastAPI/Django.
Curriculum Roadmap & Learning Path
5 StagesPart 1: Candid Experience, Architecture & Intro (1 - 5)
5 QuestionsWhat is Python, and what are its core architectural characteristics (interpreted, dynamically typed, multi-paradigm)?
Python is a high-level, general-purpose, interpreted, dynamically typed, garbage-collected programming language created by Guido van Rossum in 1991. It emphasizes readability, rapid developer productivity, and clean syntax ("batteries included").
Walk me through your hands-on experience building Python backend applications, and how you decide between FastAPI, Flask, and Django.
"I am a Senior Backend and Full-Stack Engineer specializing in high-performance Python, asynchronous microservices, and distributed architectures. I build services using FastAPI, Flask, and Django, integrated with async database drivers (asyncpg), message brokers (RabbitMQ, Redis), and background task workers (Celery, ARQ).
Describe a severe Python backend performance bottleneck you resolved.
How to Explain in an Interview: Problem: In a FastAPI ingestion API, request latency jumped from 40ms to 4.2 seconds under heavy load • Root Cause: A developer used synchronous requests.get() and called json.loads() on a 25MB payload inside an async def route, which blocked the.
Strategy for dependency management and packaging:
I use uv (Astral's blazingly fast Rust-based package manager) or Poetry with deterministic lockfiles. In Docker, I use Multi-Stage Builds: Builder stage: Compiles C extensions and wheels • Final stage: Uses a slim image (python:3.12-slim), copies only installed packages, and runs as a non-root user (USER nonroot).
Approach to automated testing in Python:
pytest with pytest-asyncio for async tests • Wrap tests in transactional rollbacks so every test runs in an isolated nested transaction that rolls back on teardown (fast, clean, and avoids • Mock external HTTP APIs using respx and run real PostgreSQL/Redis instances in CI with Testcontainers.
Part 2: Python Core Language, Internals & Runtime (6 - 25)
20 QuestionsMemory management in Python: Reference Counting & Generational GC:
CPython manages memory in two ways: Reference Counting (Immediate): Every object tracks how many variables point to it (ob_refcnt) • Generational Cyclic GC (Background): Detects circular references (a.b = b; b.a = a) where reference counts never hit 0, grouping objects into 3.
What is the Global Interpreter Lock (GIL) and free-threaded Python?
The GIL is a mutex in CPython that ensures only one native thread executes Python bytecode at a time, protecting CPython memory management from race conditions.: Impact: Multi-threaded Python cannot run CPU-bound tasks in parallel across multiple CPU cores.
Mutable vs Immutable data types:
Immutable: int, float, str, tuple, frozenset, bytes • Mutable: list, dict, set.
`is` vs `==` and Integer Caching:
==: Compares values (a == b) • is: Compares memory identity (id(a) == id(b)) • Small Integer Caching: CPython pre-allocates integers between -5 and 256, so a = 100; b = 100; a is b is True.
Python Decorators and `functools.wraps`:
A decorator is a function that takes another function, wraps its behavior, and returns a new function. functools.wraps is essential to preserve the original function's name (name) and docstring.
Generators and the `yield` keyword:
A generator produces values on demand one at a time using yield instead of returning an entire collection at once, achieving O(1) memory consumption.
The Iterator Protocol:
An object is an iterator if it implements two dunder methods: iter() (returns self) and next() (returns next item or raises StopIteration).
Context Managers and the `with` statement:
Guarantees resource acquisition and deterministic cleanup (e.g. closing files or DB connections) via enter and exit, even if an unhandled exception is raised.
`*args`, `**kwargs`, positional-only and keyword-only arguments:
args: Collects positional arguments into a tuple • kwargs: Collects keyword arguments into a dictionary • /: Everything to the left is positional-only • ``: Everything to the right is keyword-only**.
Dunder methods: `__str__` vs `__repr__`, `__new__` vs `__init__`:
str: User-friendly readable string for end users • repr: Unambiguous string for developers and debugging (eval(repr(obj)) == obj) • new: Allocates and returns the new instance in memory (used in Singletons and immutable types) • init: Initializes the newly created instance attributes.
Multiple Inheritance and Method Resolution Order (MRO):
Python resolves multiple inheritance orders using the C3 Linearization Algorithm (depth-first, left-to-right, preserving local precedence). Check it with ClassName.mro().
Metaclasses in Python:
A metaclass is a "class of a class" that defines how a class is constructed. Classes are instances of metaclasses (default is type). Used in ORMs (Django models) and Pydantic.
`__slots__` and memory reduction:
By default, Python objects store attributes in a dynamic dictionary (dict). Defining slots prevents dict creation, allocating fixed array pointers and saving up to 60% RAM for millions of objects.
`@staticmethod` vs `@classmethod` vs Instance Methods:
Instance method: Takes self; accesses and mutates instance state • @classmethod: Takes cls; accesses class state; ideal for alternative factory constructors • @staticmethod: Takes neither self nor cls; acts as an isolated pure function inside a class namespace.
Shallow Copy (`copy.copy()`) vs Deep Copy (`copy.deepcopy()`);
Shallow Copy: Duplicates the outer container, but inserts references to the original nested objects • Deep Copy: Recursively duplicates the container and all nested objects completely.
Dataclasses vs NamedTuple vs Pydantic:
dataclass: Built-in; automatically generates init, repr, and eq • NamedTuple: Immutable tuple subclass; lightweight with named fields • Pydantic: Full data parsing and runtime validation for APIs with JSON coercion.
Exception Chaining (`raise ... from ...`):
Preserves the root cause exception trace when re-raising a higher-level custom domain exception using from e.
First-Class Functions:
In Python, functions are first-class citizens: they can be passed as arguments, returned from other functions, assigned to variables, and stored in data structures.
List, Dict, and Set Comprehensions:
Concise, readable syntax for creating collections from iterables with inline filtering.
The `dis` module and CPython Bytecode:
CPython compiles Python source code into bytecode before executing it on the virtual machine. Use dis.dis() to inspect low-level bytecode instructions.
Part 3: Asynchronous Programming & Concurrency (26 - 40)
15 QuestionsThreading vs Multiprocessing vs AsyncIO:
AsyncIO: Single-thread cooperative multitasking via an event loop • Threading: Multiple OS threads sharing same memory, bounded by the GIL • Multiprocessing: Multiple independent OS processes, each with its own Python interpreter and memory.
AsyncIO: Coroutines, Tasks, and Futures:
Coroutine: A function declared with async def that can pause execution via await • Task: A wrapper that schedules a coroutine to run on the event loop concurrently (asyncio.create_task()) • Future: Low-level object representing an eventual result of an async operation.
Blocking the Event Loop & offloading to threads:
Running synchronous blocking code (time.sleep, requests.get, image processing) in an async route freezes the single event loop thread for all users! Fix: Offload to a background thread using asyncio.to_thread().
`asyncio.gather()` vs `asyncio.TaskGroup()`:
asyncio.gather(): Runs tasks concurrently • asyncio.TaskGroup() (Python 3.11+): Implements Structured Concurrency.
`wait()` vs `as_completed()` vs `shield()`:
as_completed(): Yields results as each task finishes, processing fastest responses first • wait(): Waits for tasks with return conditions (FIRSTCOMPLETED, ALLCOMPLETED) • shield(): Protects a critical coroutine from being cancelled by its caller.
Async Context Managers & Async Iterators:
Async Context Manager: Implements aenter and aexit with async with • Async Iterator: Implements aiter and anext with async for.
CPU-bound vs I/O-bound scaling:
I/O-Bound: Use AsyncIO or Threading (waiting for DB, network sockets) • CPU-Bound: Use ProcessPoolExecutor or background task queues (Celery/RabbitMQ) across multiple CPU cores.
Process Pools vs Thread Pools and Shared State:
Thread Pool: Shares the same memory space • Process Pool: Separate memory spaces.
Race Conditions and Locks:
A race condition occurs when two threads concurrently read and modify shared data. Fix: Protect critical sections using threading.Lock or asyncio.Lock.
Deadlocks in multi-threaded applications:
Thread A holds Lock 1 and waits for Lock 2, while Thread B holds Lock 2 and waits for Lock 1. Both freeze indefinitely. Prevention: Always acquire multiple locks in identical order across all code paths.
I/O Multiplexing (`epoll` / `kqueue`):
OS kernel primitives that monitor thousands of file descriptors and network sockets, waking up the Python event loop only when a socket has data ready to read/write.
Graceful AsyncIO Shutdown:
Catch SIGTERM and SIGINT, cancel all pending tasks, and wait for them to finish with asyncio.gather(*tasks, return_exceptions=True).
AnyIO and Structured Concurrency:
AnyIO is an asynchronous compatibility library that works across both AsyncIO and Trio, enforcing structured concurrency where background tasks cannot outlive their enclosing scope.
Producer-Consumer with `asyncio.Queue`:
Decouples producers generating work from worker consumers processing work concurrently with flow control.
Gunicorn with Uvicorn Workers:
Gunicorn acts as the master process manager, spawning and monitoring multiple worker processes (one per CPU core) running the Uvicorn ASGI event loop.
Part 4: Web Frameworks, APIs & FastAPI (41 - 55)
15 QuestionsWhy FastAPI achieves high performance:
Starlette: Built on Starlette for high-throughput asynchronous ASGI routing • Pydantic v2: Powered by Pydantic's core written in Rust for 5-10x faster JSON serialization and schema validation • Async Native: Runs concurrently on the AsyncIO event loop.
WSGI vs ASGI:
WSGI (Flask, Django): Synchronous request-response specification • ASGI (FastAPI, Starlette): Asynchronous server interface.
FastAPI Dependency Injection (`Depends()`):
A declarative mechanism to inject shared resources (database sessions, authentication, configs) into route handlers with automatic lifecycle cleanup.
Pydantic v2 performance boost:
Pydantic v2 rewrote its validation engine in Rust (pydantic-core), delivering up to 17x faster JSON validation and strict type parsing.
`async def` vs standard `def` in FastAPI endpoints:
async def: Runs directly on the main AsyncIO event loop thread • Standard def: FastAPI automatically offloads standard def routes to an internal worker thread pool, preventing blocking code from freezing the.
BackgroundTasks vs Celery:
FastAPI BackgroundTasks: Runs in-process in the same service after returning the HTTP response • Celery: Distributed task queue backed by Redis/RabbitMQ.
FastAPI Middleware:
Intercepts incoming HTTP requests before reaching endpoints and inspects outgoing responses (e.g. adding request timings or correlation IDs).
Centralized Exception Handling in FastAPI:
Catch custom domain exceptions globally and transform them into standardized JSON error responses.
Application Factory Pattern in Flask:
Enables creating multiple instances of a Flask app with different configurations (e.g. testing vs production) by defining a create_app() factory function.
Flask Contexts: Application vs Request Context:
Application Context (current_app, g): Bound to the application instance; stores DB connections and global app configs • Request Context (request, session): Bound to the current incoming HTTP request; stores cookies, headers, and form data.
JWT Authentication with Refresh Token Rotation:
Issue a short-lived Access Token (15m) and a long-lived Refresh Token (7d). On refresh, invalidate the old refresh token and issue a brand new pair.
Server-Sent Events (SSE) in FastAPI:
Stream real-time text events to clients over a persistent HTTP connection using StreamingResponse.
API Rate Limiting with Redis:
Track request count per IP address in Redis with an expiration window. If count exceeds limit, raise HTTP 429 Too Many Requests.
OpenAPI (Swagger) Customization in FastAPI:
Customize API metadata, security schemes, and documentation tags directly on the FastAPI app instance.
Secure File Uploads: `UploadFile` vs `bytes`:
bytes: Reads the entire file directly into RAM (crashes server on large multi-gigabyte files) • UploadFile: Uses a SpooledTemporaryFile; buffers in RAM up to 1MB, then rolls over to disk automatically.
Part 5: ORMs, Databases & Background Workers (56 - 65)
10 QuestionsSQLAlchemy 2.0 vs Legacy 1.x:
SQLAlchemy 2.0 unifies the Core and ORM syntax around explicit select() statements and provides full native support for type hints and async sessions.
Unit of Work and Identity Map:
Identity Map: Tracks all loaded objects by primary key, ensuring querying the same row twice returns the exact same in-memory object instance • Unit of Work: Batches all inserts, updates, and deletes, executing them in optimal order upon session.commit().
Async SQLAlchemy with `asyncpg`:
Use createasyncengine with postgresql+asyncpg:// and AsyncSession to perform non-blocking database queries in FastAPI.
N+1 Query Elimination in SQLAlchemy:
Fetching 100 posts and iterating their comments triggers 100 individual queries. Fix: Use selectinload() or joinedload() to eager-load relations in a single or secondary batched query.
Alembic Migration Best Practices:
Always inspect autogenerated migrations before applying • Use op.batchaltertable for SQLite compatibility • Ensure all new columns have default values or are nullable for zero downtime.
Celery Architecture: Broker & Result Backend:
Broker (RabbitMQ/Redis): Queues task messages • Worker: Consumes and executes tasks • Result Backend (Redis/DB): Stores task return values and statuses.
Celery Retries & Task Idempotency:
Use exponential backoff for network failures and ensure tasks are idempotent (can be executed multiple times without unintended side effects).
Celery Canvas Workflows:
chain: Executes tasks sequentially (task1 task2) • group: Executes tasks in parallel • chord: Executes a group in parallel, then calls a callback when all finish.
Preventing Worker Memory Leaks:
Python workers running heavy libraries can suffer from fragmented RAM over time. Configure maxtasksper_child to restart worker processes periodically.
Alternatives to Celery (ARQ, Dramatiq):
ARQ: Ultra-fast asynchronous task queue built on Redis and AsyncIO; ideal for FastAPI • Dramatiq: Simpler, thread-based alternative to Celery with superior out-of-the-box retry logic and RabbitMQ/Redis backends.