Skip to main content
InterviewHubPRO
HomeTracksSection 20: Python & AsyncIO (65 Qs)
Section 20 of 6465 Questions (1 Per Page)

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 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.5 Connected Milestones
65 of 65 Qs

Part 1: Candid Experience, Architecture & Intro (1 - 5)

5 Questions
1
SeniorCode#System Design

What 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").

2
SeniorCode#System Design#HTTP & REST APIs

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).

3
SeniorCode#Forms#Performance

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.

4
SeniorCode#System Design

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).

5
SeniorCode#Testing#System Design

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 Questions
6
Most AskedSeniorCode#python#Python Core Language

Memory 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.

7
Most AskedSeniorCode#python#Python Core Language

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.

8
SeniorCode#python#Python Core Language

Mutable vs Immutable data types:

Immutable: int, float, str, tuple, frozenset, bytes • Mutable: list, dict, set.

9
Most AskedSeniorCode#System Design

`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.

10
SeniorCode#TypeScript

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.

11
SeniorCode#python#Python Core Language

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.

12
SeniorCode#python#Python Core Language

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).

13
SeniorCode#python#Python Core Language

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.

14
SeniorCode#python#Python Core Language

`*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**.

15
SeniorCode#python#Python Core Language

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.

16
SeniorCode#python#Python Core Language

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().

17
SeniorCode#python#Python Core Language

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.

18
SeniorCode#python#Python Core Language

`__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.

19
SeniorCode#python#Python Core Language

`@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.

20
SeniorCode#python#Python Core Language

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.

21
SeniorCode#python#Python Core Language

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.

22
SeniorCode#python#Python Core Language

Exception Chaining (`raise ... from ...`):

Preserves the root cause exception trace when re-raising a higher-level custom domain exception using from e.

23
SeniorCode#python#Python Core Language

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.

24
SeniorCode#python#Python Core Language

List, Dict, and Set Comprehensions:

Concise, readable syntax for creating collections from iterables with inline filtering.

25
SeniorCode#python#Python Core Language

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 Questions
26
SeniorCode#Async & Promises

Threading 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.

27
Most AskedSeniorCode#Async & Promises

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.

28
Most AskedSeniorCode#Async & Promises#Event Loop

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().

29
SeniorCode#Async & Promises

`asyncio.gather()` vs `asyncio.TaskGroup()`:

asyncio.gather(): Runs tasks concurrently • asyncio.TaskGroup() (Python 3.11+): Implements Structured Concurrency.

30
SeniorCode#Async & Promises

`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.

31
SeniorCode#Async & Promises

Async Context Managers & Async Iterators:

Async Context Manager: Implements aenter and aexit with async with • Async Iterator: Implements aiter and anext with async for.

32
SeniorCode#Async & Promises

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.

33
SeniorCode#Async & Promises

Process Pools vs Thread Pools and Shared State:

Thread Pool: Shares the same memory space • Process Pool: Separate memory spaces.

34
SeniorCode#Async & Promises

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.

35
SeniorCode#Async & Promises

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.

36
SeniorCode#Async & Promises#Data Structures

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.

37
SeniorCode#Async & Promises

Graceful AsyncIO Shutdown:

Catch SIGTERM and SIGINT, cancel all pending tasks, and wait for them to finish with asyncio.gather(*tasks, return_exceptions=True).

38
SeniorCode#Async & Promises

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.

39
SeniorCode#Async & Promises#Data Structures

Producer-Consumer with `asyncio.Queue`:

Decouples producers generating work from worker consumers processing work concurrently with flow control.

40
SeniorCode#Async & Promises

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 Questions
41
SeniorCode#Forms#Performance

Why 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.

42
SeniorCode#HTTP & REST APIs

WSGI vs ASGI:

WSGI (Flask, Django): Synchronous request-response specification • ASGI (FastAPI, Starlette): Asynchronous server interface.

43
Most AskedSeniorCode#Dependency Injection#HTTP & REST APIs

FastAPI Dependency Injection (`Depends()`):

A declarative mechanism to inject shared resources (database sessions, authentication, configs) into route handlers with automatic lifecycle cleanup.

44
SeniorCode#Forms#Performance

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.

45
SeniorCode#Async & Promises#HTTP & REST APIs

`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.

46
SeniorCode#HTTP & REST APIs

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.

47
SeniorCode#HTTP & REST APIs

FastAPI Middleware:

Intercepts incoming HTTP requests before reaching endpoints and inspects outgoing responses (e.g. adding request timings or correlation IDs).

48
SeniorCode#HTTP & REST APIs

Centralized Exception Handling in FastAPI:

Catch custom domain exceptions globally and transform them into standardized JSON error responses.

49
SeniorCode#HTTP & REST APIs

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.

50
SeniorCode#HTTP & REST APIs

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.

51
Most AskedSeniorCode#Security & Auth#HTTP & REST APIs

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.

52
SeniorCode#HTTP & REST APIs

Server-Sent Events (SSE) in FastAPI:

Stream real-time text events to clients over a persistent HTTP connection using StreamingResponse.

53
Most AskedSeniorCode#HTTP & REST APIs

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.

54
SeniorCode#HTTP & REST APIs

OpenAPI (Swagger) Customization in FastAPI:

Customize API metadata, security schemes, and documentation tags directly on the FastAPI app instance.

55
SeniorCode#HTTP & REST APIs

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 Questions
56
MidCode#Databases & SQL

SQLAlchemy 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.

57
MidCode#Databases & SQL

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().

58
MidCode#Async & Promises#Databases & SQL

Async SQLAlchemy with `asyncpg`:

Use createasyncengine with postgresql+asyncpg:// and AsyncSession to perform non-blocking database queries in FastAPI.

59
MidCode#Databases & SQL

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.

60
MidCode#Databases & SQL

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.

61
SeniorCode#System Design#Databases & SQL

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.

62
MidCode#Databases & SQL#Data Structures

Celery Retries & Task Idempotency:

Use exponential backoff for network failures and ensure tasks are idempotent (can be executed multiple times without unintended side effects).

63
MidCode#Databases & SQL

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.

64
SeniorCode#Memory Management#Databases & SQL

Preventing Worker Memory Leaks:

Python workers running heavy libraries can suffer from fragmented RAM over time. Configure maxtasksper_child to restart worker processes periodically.

65
MidCode#Databases & SQL

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.