๐Ÿ PYTHON CORE FUNDAMENTALS

1. What are Pythonโ€™s key features? Interpreted, dynamically typed, garbage-collected, supports OOP/functional/procedural paradigms, extensive standard library, indentation-enforced syntax.

2. What is the GIL? Why does it matter? Global Interpreter Lock โ€” a mutex that allows only one thread to execute Python bytecode at a time. Prevents true parallelism with threads. Use multiprocessing for CPU-bound tasks; asyncio/threads are fine for I/O-bound.

3. Mutable vs Immutable types?

  • Mutable: list, dict, set โ€” can change after creation.
  • Immutable: int, float, str, tuple, frozenset โ€” cannot. Using a mutable default argument in a function is a classic bug โ€” use None and assign inside.

4. List vs Tuple vs Set vs Dict?

TypeOrderedMutableDuplicatesLookup
listโœ…โœ…โœ…O(n)
tupleโœ…โŒโœ…O(n)
setโŒโœ…โŒO(1)
dictโœ… (3.7+)โœ…keys: โŒO(1)

5. What are *args and **kwargs?

  • *args โ€” captures extra positional args as a tuple.
  • **kwargs โ€” captures extra keyword args as a dict.

6. What is a list comprehension? What about dict/set comprehensions? Concise way to create collections.

squares = [x**2 for x in range(10) if x % 2 == 0]
sq_dict = {x: x**2 for x in range(5)}
sq_set  = {x**2 for x in range(5)}

7. What are generators? Why use them? Functions using yield that produce values lazily โ€” one at a time. Memory-efficient for large sequences. next() advances them; exhausted after one pass.

def count_up(n):
    for i in range(n):
        yield i

8. yield vs return? return completely exits a function and hands back a value. yield pauses the function, saves its state, returns a value, and resumes from that point on the next call.

9. What are decorators? Functions that wrap another function to extend its behavior without modifying it. Use @ syntax.

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("before")
        result = func(*args, **kwargs)
        print("after")
        return result
    return wrapper

10. What are context managers? How do you make one? Manage setup/teardown with with. Implement __enter__ and __exit__, or use @contextmanager.

with open("file.txt") as f:
    data = f.read()

11. What is the difference between is and ==?

  • == checks value equality.
  • is checks identity (same object in memory). a = [1]; b = [1]; a == b โ†’ True, a is b โ†’ False.

12. What are lambda functions? Anonymous, single-expression functions. lambda x, y: x + y. Use for short callbacks/sort keys; avoid for complex logic.

13. What is map(), filter(), reduce()?

  • map(fn, iterable) โ€” apply fn to each element.
  • filter(fn, iterable) โ€” keep elements where fn returns True.
  • reduce(fn, iterable) โ€” fold iterable to single value (from functools). List comprehensions are usually preferred over map/filter.

14. Shallow copy vs Deep copy?

  • Shallow (copy.copy()) โ€” new object, but nested objects are still references.
  • Deep (copy.deepcopy()) โ€” fully independent clone of everything.

15. What are Pythonโ€™s exception handling keywords?

  • try: Code that might throw an error.
  • except: Code that runs if an error occurs.
  • else: Code that runs if no error occurs.
  • finally: Code that runs regardless of errors (e.g., closing connections).

16. What does if __name__ == "__main__": do? (Added) It prevents the code inside the block from running if the script is imported as a module into another script. It only runs if the file is executed directly.

17. What is enumerate() and zip()?

  • enumerate(iterable) โ€” yields (index, value) pairs.
  • zip(a, b) โ€” pairs elements from multiple iterables, stops at shortest.

18. What is defaultdict and Counter? From collections:

  • defaultdict(int) โ€” returns a default value for missing keys instead of raising KeyError.
  • Counter(iterable) โ€” counts hashable elements, returns dict-like with counts.

19. What is the difference between append() and extend()?

  • append(x) โ€” adds x as a single element.
  • extend(iterable) โ€” adds all elements of iterable individually.

20. What is a closure? A function that remembers variables from its enclosing scope even after that scope has exited.

21. What is global and nonlocal?

  • global x โ€” tells Python that x in this function refers to the module-level variable.
  • nonlocal x โ€” refers to the nearest enclosing (non-global) scope variable.

22. What is PEP 8? The official style guide for Python code. It dictates conventions for readability, such as 4-space indentation, variable naming (snake_case), and class naming (CamelCase).

23. What is a virtual environment and requirements.txt? (Expanded) An isolated environment that allows you to install specific versions of packages for a project without conflicting with global system packages. requirements.txt is a file listing all project dependencies, installed via pip install -r requirements.txt.

24. Iterator vs Iterable?

  • Iterable: An object you can loop over (List, String) possessing __iter__().
  • Iterator: An object representing a stream of data possessing __iter__() and __next__().

25. Python Scope Resolution (LEGB)? Python searches for variables in this order: Local, Enclosing (non-local), Global, and Built-in.

26. pass, break, continue?

  • pass: A null operation; acts as a placeholder.
  • break: Exits the loop entirely.
  • continue: Skips the rest of the current iteration and moves to the next loop iteration.

27. What is pickling in Python? Pickling serializes a Python object to a byte stream (pickle.dumps()). Unpickling deserializes it back (pickle.loads()). Used for saving objects to disk or sending over a network. Never unpickle untrusted data.


๐Ÿงฉ OBJECT-ORIENTED PROGRAMMING (OOP)

28. Four pillars of OOP?

  1. Encapsulation โ€” hide internal state, expose interface.
  2. Abstraction โ€” expose only whatโ€™s necessary.
  3. Inheritance โ€” child class reuses parentโ€™s behavior.
  4. Polymorphism โ€” same interface, different implementations.

29. What is __init__ vs __new__?

  • __new__ โ€” creates the instance (class method, rarely overridden).
  • __init__ โ€” initializes the already-created instance.

30. Explain @staticmethod vs @classmethod vs instance method.

  • instance method โ€” receives self; accesses instance and class state.
  • @classmethod โ€” receives cls; used for factory methods or class-level state.
  • @staticmethod โ€” receives neither; just a utility function namespaced in the class.

31. What is the self keyword? self represents the instance of the class. It binds the attributes and methods to that specific object.

32. What is inheritance? What is MRO? A class can inherit attributes/methods from a parent. Python uses C3 linearization for Method Resolution Order (__mro__), determining which parentโ€™s method is called first in multiple inheritance.

33. What are @property and setters? Allow method access like attribute access, with optional validation on set.

@property
def name(self): return self._name
@name.setter
def name(self, v): self._name = v.strip()

34. What is __str__ vs __repr__?

  • __str__ โ€” human-readable string (str(obj), print(obj)).
  • __repr__ โ€” unambiguous developer string, ideally eval-able. Fallback if __str__ missing.

35. What is duck typing? โ€œIf it walks like a duck and quacks like a duck, itโ€™s a duck.โ€ Python doesnโ€™t check types; it checks whether an object has the needed method/attribute. Enables flexible, interface-driven code.

36. Abstract classes in Python? Use abc.ABC and @abstractmethod. Subclasses must implement abstract methods or they cannot be instantiated.

37. What is __slots__? Declares a fixed set of attributes, preventing __dict__ creation. Reduces memory for classes with many instances.

38. What are Metaclasses? A metaclass is a โ€œclass of a class.โ€ It defines how a class behaves. Just as an object is an instance of a class, a class is an instance of a metaclass (default is type).

39. What are Dunder/Magic methods? Special methods surrounded by double underscores (e.g., __len__, __add__). They allow custom objects to integrate natively with Python syntax (like using + or len()).


โšก MEMORY, PERFORMANCE & ASYNC

40. How does Python manage memory? Reference counting + cyclic garbage collector. When ref count hits 0, memory is freed. gc module handles cyclic references.

41. Multithreading vs Multiprocessing in Python?

  • Multithreading: Shares memory space. Good for I/O-bound tasks (network requests, file I/O). Bypasses GIL limitations by waiting.
  • Multiprocessing: Creates separate memory spaces (processes). Good for CPU-bound tasks (heavy math). Bypasses the GIL entirely.

42. What is asyncio? When is it useful? Pythonโ€™s async framework using async/await. Excellent for I/O-bound, high-concurrency tasks (many simultaneous network calls). Not useful for CPU-bound (use multiprocessing).

43. What is the difference between concurrency and parallelism?

  • Concurrency โ€” dealing with multiple tasks at once (may interleave).
  • Parallelism โ€” executing multiple tasks literally simultaneously (multiple cores). Python threads give concurrency; multiprocessing gives parallelism.

44. What is the difference between synchronous and asynchronous programming?

  • Synchronous: Each task blocks until complete before the next one starts.
  • Asynchronous: Tasks can be initiated and control is returned while waiting (e.g., for I/O). Python supports this with asyncio, async/await.

45. What are common ways to optimize Python performance? Use built-ins, list comprehensions over loops, numpy for numerics, generators for large data, lru_cache for memoization, profiling with cProfile.


๐ŸŸฉ DJANGO CORE & MODELS

46. What is Django? What is its design philosophy? High-level Python web framework. Follows MTV (Model-Template-View). Philosophy: DRY (Donโ€™t Repeat Yourself), batteries-included, convention over configuration.

47. MTV vs MVC?

DjangoMVC equivalent
ModelModel
TemplateView
ViewController

In Django, the โ€œViewโ€ is the business logic layer (not the display layer).

48. What is the Django request/response lifecycle?

  1. Browser sends HTTP request.
  2. urls.py routes to a View.
  3. View queries Model, processes data.
  4. Template renders HTML.
  5. View returns HttpResponse.

49. Project vs App in Django? A Project is the entire application and its configurations (settings.py). An App is a modular, reusable web application that does one specific thing (e.g., blog app, auth app) within a Project.

50. What is manage.py? CLI tool for Django admin tasks: runserver, migrate, makemigrations, createsuperuser, shell, collectstatic, etc.

51. What is settings.py? Central configuration: INSTALLED_APPS, DATABASES, MIDDLEWARE, STATIC_URL, SECRET_KEY, DEBUG, ALLOWED_HOSTS, etc.

52. What is Django ORM? Object-Relational Mapper โ€” lets you interact with the database using Python objects instead of raw SQL. Each Model class maps to a DB table.

53. What are ForeignKey, OneToOneField, ManyToManyField?

  • ForeignKey โ€” many-to-one (many orders โ†’ one customer).
  • OneToOneField โ€” one-to-one (user โ†’ profile).
  • ManyToManyField โ€” many-to-many (books โ†” authors).

54. What is the difference between null=True and blank=True? (Added)

  • null=True: Database-level. Allows the database column to store NULL values.
  • blank=True: Validation-level. Allows the field to be empty in Django forms/admin.

55. What is related_name in a Django model? (Added) It defines the name of the reverse relation from the linked model back to the model that defines the ForeignKey. If you donโ€™t specify it, Django creates a default one (e.g., modelname_set).

56. What are migrations? Version-controlled DB schema changes. makemigrations generates migration files from model changes; migrate applies them to the DB.

57. What is select_related vs prefetch_related? Both reduce N+1 query problems.

  • select_related โ€” SQL JOIN, for FK/OneToOne (single query).
  • prefetch_related โ€” separate query + Python join, for ManyToMany/reverse FK.

58. What is the N+1 query problem? Fetching N objects then making 1 extra query per object for related data = N+1 queries total. Fix with select_related / prefetch_related.

59. What is QuerySet? Is it lazy? Represents a DB query that hasnโ€™t necessarily run yet. Yes, lazy โ€” evaluated only when iterated, sliced, or converted. Supports chaining: .filter().exclude().order_by().

60. Difference between .get() and .filter()?

  • .get() โ€” returns single object; raises DoesNotExist or MultipleObjectsReturned.
  • .filter() โ€” returns a QuerySet (empty if nothing matches).

61. filter() vs exclude()? filter() returns records matching the given parameters. exclude() returns records that do not match the given parameters.

62. What is F() expression? References a model field value in the DB without fetching it to Python. Useful for atomic updates: Product.objects.update(price=F('price') * 1.1).

63. What is Q() object? Enables complex queries with | (OR) and & (AND): Post.objects.filter(Q(title='x') | Q(body__contains='y')).

64. What is annotate() vs aggregate()?

  • aggregate(): Calculates a summary value over an entire QuerySet (returns a dictionary). Example: Total sum of all book prices.
  • annotate(): Calculates a summary value for each item in the QuerySet (returns a QuerySet). Example: Number of books written by each author.

65. How to bypass ORM and write raw SQL? Using Model.objects.raw('SELECT * FROM table') or using django.db.connection for direct cursor execution.

66. What is abstract = True in Meta? Makes the model abstract โ€” no DB table is created. Used as a base class to share fields/methods across models.

67. What is the contenttypes framework in Django? The contenttypes framework provides a generic way to create relationships between any models using ContentType and GenericForeignKey. Used internally by Djangoโ€™s permission system and admin.


๐Ÿ–ฅ๏ธ DJANGO VIEWS, TEMPLATES & FORMS

68. Function-Based Views (FBV) vs Class-Based Views (CBV)?

  • FBV: Simple, explicit Python functions taking a request and returning a response. Requires more boilerplate for CRUD.
  • CBV: Uses Python classes. Promotes DRY code through inheritance and mixins. Great for standard CRUD operations (ListView, DetailView).

69. What are Mixins in Django? Classes that provide specific behaviors (e.g., LoginRequiredMixin) to be inherited by Class-Based Views. They allow multiple inheritance to compose view logic.

70. What is HttpRequest and HttpResponse?

  • HttpRequest โ€” Djangoโ€™s object for incoming requests; has .method, .GET, .POST, .user, .headers, .body.
  • HttpResponse โ€” what views return; contains status code, headers, content.

71. What is redirect() and render()?

  • render(request, 'template.html', context) โ€” renders a template to HttpResponse.
  • redirect('url') โ€” returns an HttpResponseRedirect.

72. How does URL routing work in Django? urls.py maps URL patterns to views using path() or re_path(). Project-level urls.py includes app-level ones with include().

73. reverse() vs reverse_lazy()? Used to generate URLs by their name. reverse() executes immediately. reverse_lazy() delays execution until the URL is actually needed, preventing circular import errors in class attributes (like success_url in CBVs).

74. What is template inheritance? {% extends "base.html" %} + {% block content %} allows child templates to fill in blocks from a parent. Promotes DRY layout.

75. What is the Django templates context? A dictionary mapping variable names to Python objects, passed from the View to the Template to dynamically render HTML.

76. What are Context Processors? Functions that inject variables into the context of all templates globally, so you donโ€™t have to pass them manually in every view (e.g., injecting the logged-in user).

77. Django Forms vs ModelForms?

  • forms.Form: You define all fields manually. Used for non-database forms (e.g., Contact Us).
  • forms.ModelForm: Automatically generates form fields based on a specific Django Model.

78. What is form.is_valid()? Runs all validators. On success, populates form.cleaned_data. On failure, populates form.errors.


๐Ÿ› ๏ธ DJANGO MIDDLEWARE, AUTH & ADMIN

79. What is middleware? Hooks into the request/response cycle globally. Ordered list in MIDDLEWARE. Each middleware processes request (topโ†’down) and response (bottomโ†’up). Used for auth, security headers, sessions, logging, etc.

80. What is CSRF protection? Cross-Site Request Forgery protection. Django includes {% csrf_token %} in forms and CsrfViewMiddleware to validate it. Prevents malicious sites from submitting forms on a userโ€™s behalf.

81. How do you extend the User model? AbstractUser vs AbstractBaseUser?

  • AbstractUser: Use when you want the default Django User fields (username, email, password) but want to add extra fields (e.g., phone_number).
  • AbstractBaseUser: Use when you want complete control over the User model (e.g., logging in with email only instead of username). Requires writing a custom User Manager.

82. What is @login_required? Decorator that redirects unauthenticated users to the login page. For CBVs, use LoginRequiredMixin.

83. What is the Django Admin? Auto-generated CRUD interface for your models. Register models with admin.site.register(Model) or @admin.register(Model). Customizable with ModelAdmin class.

84. What are Django signals? Allow decoupled apps to get notified when certain actions occur. Common: post_save, pre_save, post_delete, m2m_changed. Use @receiver decorator.

85. Pre-save vs Post-save signals?

  • pre_save: Triggered right before a modelโ€™s save() method completes. Good for modifying fields before saving.
  • post_save: Triggered right after a model is saved. Good for creating related objects (e.g., creating a Profile when a User is created).

86. When should you avoid signals? When the code is tightly coupled to that model anyway โ€” use modelโ€™s save() override instead. Signals make flow hard to trace; use sparingly.

87. Difference between static and media files?

  • Static โ€” CSS, JS, images bundled with code. Served via collectstatic + CDN/Nginx.
  • Media โ€” user-uploaded files. Configured with MEDIA_ROOT and MEDIA_URL.

88. What are Django Fixtures? JSON, XML, or YAML files used to populate the database with initial dummy or required data using the loaddata command.


๐ŸŒ DJANGO REST FRAMEWORK (DRF)

89. What is DRF? Django REST Framework โ€” powerful toolkit for building RESTful APIs on top of Django. Provides serializers, viewsets, routers, authentication, permissions, and browsable API.

90. What is a Serializer in DRF? It acts as the bridge between Django models and JSON data. It handles validation, serialization (Model to JSON), and deserialization (JSON to Model).

91. What is ModelSerializer? A DRF shortcut that automatically generates a Serializer class with fields matching a specific Django Model, including default validators.

92. APIView vs GenericAPIView vs ViewSet?

  • APIView โ€” base class, manual handling per HTTP method.
  • GenericAPIView + mixins โ€” adds queryset/serializer convenience.
  • ViewSet โ€” groups CRUD actions; used with Router for clean URL generation.

93. What are DRF permissions? Authentication vs Permissions?

  • Authentication: Who are you? (Identifies the user via Tokens, Sessions).
  • Permissions: What are you allowed to do? (Grants/denies access to endpoints via IsAuthenticated, IsAdminUser).

94. What is throttling in DRF? Rate limiting. AnonRateThrottle, UserRateThrottle. Configured in settings: DEFAULT_THROTTLE_RATES = {'user': '100/day'}.

95. What is pagination in DRF? Controls how list responses are chunked. PageNumberPagination, LimitOffsetPagination, CursorPagination. Configure PAGE_SIZE in settings or per view.


๐Ÿ“ก REST APIs & HTTP

96. What is REST? What are its principles/constraints? REST (Representational State Transfer) is an architectural style for APIs. Principles:

  1. Stateless โ€” server stores no client state between requests.
  2. Client-Server separation โ€” UI and data storage are decoupled.
  3. Uniform Interface โ€” consistent resource-based URLs.
  4. Cacheable โ€” responses should declare cacheability.
  5. Layered System โ€” client canโ€™t tell if connected directly to the server.
  6. Code on Demand (optional) โ€” server can send executable code.

97. REST vs SOAP? REST is an architectural style utilizing HTTP, typically using JSON (lightweight). SOAP is a strict protocol relying heavily on XML and specific messaging patterns (heavier, more rigid).

98. What are HTTP methods and their semantics?

MethodPurposeIdempotentSafe
GETReadโœ…โœ…
POSTCreateโŒโŒ
PUTReplaceโœ…โŒ
PATCHPartial updateโŒโŒ
DELETEDeleteโœ…โŒ

99. What are common HTTP status codes?

  • 200 OK, 201 Created, 204 No Content
  • 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 405 Method Not Allowed, 422 Unprocessable Entity, 429 Too Many Requests
  • 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable

100. Path parameters vs Query parameters?

  • Path: Used to identify a specific resource (/users/123).
  • Query: Used to sort, filter, or paginate resources (/users?role=admin&sort=asc).

101. What is the difference between PUT and PATCH?

  • PUT โ€” replaces the entire resource.
  • PATCH โ€” partial update, only sends fields to change.

102. What is idempotency? Why does it matter? An operation is idempotent if repeating it produces the same result. GET, PUT, DELETE are idempotent. Important for safe retries in distributed systems.

103. What is CORS? CORS (Cross-Origin Resource Sharing) is a browser security policy that blocks web pages from making requests to a different domain. Servers must send Access-Control-Allow-Origin headers to permit cross-origin requests. In Django, use django-cors-headers.

104. What is GraphQL vs REST?

  • REST โ€” resource-based URLs, fixed response shape.
  • GraphQL โ€” single endpoint, client specifies exact data shape, prevents over/under-fetching. More complex setup but flexible.

105. What is API versioning? How do you do it? Allows evolving the API without breaking clients. Strategies: URL prefix (/api/v1/), header (Accept: application/vnd.api+json;version=1), query param (?version=1). URL prefix is most common.

106. Pagination: Offset vs Cursor?

  • Offset/Limit: Skips N rows to fetch the next set. Slower on large datasets (database scans all skipped rows).
  • Cursor: Uses a unique, sequential pointer (like an ID or timestamp) to fetch the next set. Much faster for large datasets.

107. What is a webhook? Server-to-server push notification. Instead of polling, the provider sends an HTTP POST to your endpoint when an event occurs (payment completed, etc.).

108. What is HATEOAS? HATEOAS (Hypermedia As The Engine Of Application State) is a REST constraint where API responses include links to related actions/resources, making the API self-discoverable.

109. Session-based vs Token-based auth?

  • Session: Server stores session state; client sends session ID cookie. Stateful.
  • Token: Server issues a token (like JWT), client stores it and sends it in headers. Server validates token via signature. Stateless.

110. What is JWT? JSON Web Token. Three base64-encoded parts: header.payload.signature. Server signs with secret; anyone can read payload but not forge signature. Short-lived access tokens + refresh tokens is standard pattern.

111. What is OAuth2? Authorization framework for delegating access. โ€œLogin with Googleโ€ flow: user grants permission โ†’ provider issues access token โ†’ your app uses token to access resources on their behalf.

112. How should you securely store passwords? (Added) Never store plain-text passwords. Passwords must be hashed using a cryptographic, one-way hash function paired with a unique salt (e.g., PBKDF2, bcrypt, Argon2). Django handles this securely out-of-the-box.


๐Ÿ—„๏ธ DATABASES (SQL & NoSQL)

113. SQL vs NoSQL โ€” when to use which?

  • SQL (PostgreSQL, MySQL) โ€” structured data, relations, ACID, complex queries.
  • NoSQL (MongoDB, Redis) โ€” flexible schema, horizontal scale, document/key-value/graph models. Choose based on data structure and consistency requirements.

114. Primary Key vs Foreign Key vs Unique Key?

  • PK โ€” uniquely identifies each row, not null, indexed.
  • FK โ€” references PK of another table, enforces referential integrity.
  • Unique โ€” prevents duplicate values in a column, can be null (unlike PK).

115. What are ACID properties?

  • Atomicity โ€” all or nothing.
  • Consistency โ€” DB stays valid before and after transaction.
  • Isolation โ€” concurrent transactions donโ€™t interfere.
  • Durability โ€” committed data survives crashes.

116. What is a database transaction? A sequence of operations treated as a single unit. Either all succeed (commit) or all fail (rollback). In Django: with transaction.atomic():.

117. What is Database Normalization? Organizing data to reduce redundancy and improve data integrity.

  • 1NF: Atomic values, no repeating groups.
  • 2NF: 1NF + all non-key columns depend on the entire primary key.
  • 3NF: 2NF + no transitive dependencies (non-key columns donโ€™t depend on other non-key columns).

118. What is Denormalization? Intentionally adding redundant data to a database to improve read performance and reduce complex JOIN operations, usually in read-heavy applications.

119. What is an index? Data structure (B-tree by default) that speeds up lookups at the cost of write overhead and storage. Add on columns frequently used in WHERE, JOIN, ORDER BY. Avoid over-indexing.

120. Types of Joins?

  • Inner Join: Returns records with matching values in both tables.
  • Left Join: Returns all records from the left table, and matched records from the right.
  • Right Join: Returns all records from the right table, and matched records from the left.
  • Full Join: Returns all records when there is a match in either table.

121. What is the difference between WHERE and HAVING in SQL? (Added) WHERE filters rows before any groupings or aggregations are calculated. HAVING filters data after groupings/aggregations (GROUP BY) have been applied.

122. What is the difference between DELETE and TRUNCATE? (Added) DELETE removes rows one-by-one, logs each deletion, and can be rolled back within a transaction. TRUNCATE drops and recreates the entire table, making it much faster but generally unrecoverable.

123. What is connection pooling? Reusing existing DB connections instead of creating new ones per request. Reduces overhead. Tools: PgBouncer (PostgreSQL), Django DB connection pooling via CONN_MAX_AGE.

124. What is the CAP Theorem? States that a distributed data store can only simultaneously provide two of three guarantees: Consistency, Availability, and Partition Tolerance.


๐Ÿš€ CACHING & REDIS

125. What is caching? What types exist? Storing results of expensive operations for fast reuse.

  • In-memory โ€” Redis, Memcached (fastest).
  • Database cache โ€” DB table.
  • HTTP cache โ€” browser/CDN (ETags, Cache-Control headers).
  • Application-level โ€” @lru_cache, functools.cache.

126. What is Redis? Redis (Remote Dictionary Server) is an open-source, in-memory key-value data store. It supports rich data structures: strings, hashes, lists, sets, sorted sets, streams. Used for caching, session storage, pub/sub, rate limiting, and as a Celery broker.

127. Redis vs Memcached?

  • Redis: Richer data structures, persistence (RDB/AOF snapshots), pub/sub, Lua scripting, clustering, atomic operations.
  • Memcached: Simpler key-value only, multi-threaded (better single-node throughput for simple caching), no persistence. Use Redis for most modern use cases.

128. Common Caching Strategies?

  • Cache-Aside (Lazy loading): App checks cache first; on miss, loads from DB and stores in cache. Most common.
  • Write-Through: Write to cache and DB simultaneously. Cache is always up to date.
  • Write-Behind (Write-Back): Write to cache immediately, flush to DB asynchronously later. Fast writes but risk of data loss.
  • Read-Through: Cache sits in front of DB; cache handles DB read automatically on miss.

129. Cache Hit vs Cache Miss?

  • Cache hit: Requested data is found in the cache โ€” fast response.
  • Cache miss: Data is not in cache; must fetch from the original source, then store in cache. Expensive.

130. What is cache invalidation? Why is it hard? Cache invalidation is removing or updating stale cached data. Itโ€™s hard because you must decide exactly when data is stale. Strategies: TTL (Time-To-Live) expiry, event-driven invalidation (delete cache on model update), versioned cache keys.

131. What is a Cache Stampede (Dogpile Effect)? Occurs when a highly requested cached item expires (TTL hits 0), and thousands of requests simultaneously hit the primary database to regenerate it, potentially crashing the DB. Solved using locking or probabilistic early expiration.

132. Redis Persistence (RDB vs AOF)? Even though itโ€™s in-memory, Redis can save to disk.

  • RDB (Redis Database): Takes point-in-time snapshots of the dataset at specified intervals.
  • AOF (Append Only File): Logs every single write operation received by the server. Slower but no data loss.

133. How does Django integrate with Redis for caching? Set CACHES in settings.py using django-redis:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
    }
}

134. What are the different levels of caching in Django?

  • Per-site cache: Caches entire pages (not granular).
  • Per-view cache: @cache_page(60 * 15) decorator.
  • Template fragment cache: {% cache 500 sidebar %} in templates.
  • Low-level cache API: cache.set() / cache.get() for custom logic.

โš™๏ธ ASYNC TASK QUEUES

135. What is Celery? Distributed task queue for Python. Offloads long-running tasks (emails, image processing) to background workers. Uses Redis or RabbitMQ as broker. Schedule tasks with celery beat.

136. What is a message queue? Give an example. Decouples producers and consumers of work. Producer sends a message; consumer processes it async. Examples: RabbitMQ, Redis (Celery), AWS SQS. Prevents bottlenecks and retains tasks on failure.


๐Ÿ” WEBSOCKETS & WEBRTC

137. What is the difference between HTTP and WebSockets? HTTP is request-response โ€” the client initiates every communication. WebSockets provide a persistent, full-duplex connection where both client and server can push messages at any time after the initial handshake (via HTTP Upgrade header).

138. What is Django Channels? Django Channels extends Django to handle WebSockets, long-polling, and other async protocols alongside standard HTTP. It uses ASGI instead of WSGI and requires a channel layer (typically Redis) for communicating between consumers.

139. What is ASGI vs WSGI?

  • WSGI (Web Server Gateway Interface): Synchronous, handles one request at a time. Standard for traditional Django apps.
  • ASGI (Asynchronous Server Gateway Interface): Supports async, handles WebSockets and HTTP/2. Required for Django Channels.

140. What is WebRTC? WebRTC (Web Real-Time Communication) is a browser API that enables peer-to-peer audio, video, and data communication directly between browsers without a central media server. Used in video calls, screen sharing. It uses ICE/STUN/TURN for NAT traversal.

141. What is the role of a STUN/TURN server in WebRTC?

  • STUN: Helps a client discover its public IP and port behind a NAT.
  • TURN: Acts as a relay server when peer-to-peer fails (restrictive NATs/firewalls). More expensive but needed as a fallback.

๐Ÿณ DOCKER & DEVOPS

142. What is Docker? Why use it? Docker is a platform for packaging applications and their dependencies into containers โ€” lightweight, portable, isolated units. Ensures โ€œit works on my machineโ€ = โ€œit works everywhere.โ€ Replaces inconsistent environment setups.

143. Virtual Machine vs Docker Container? VMs virtualize the entire hardware layer and require a full Guest OS per VM. Containers virtualize the OS layer, sharing the host OS kernel, making them incredibly lightweight, fast to start, and resource-efficient.

144. What is the difference between an image and a container?

  • Image: Read-only blueprint/template (like a class).
  • Container: A running instance of an image (like an object). You can run many containers from one image.

145. What is a Dockerfile? A Dockerfile is a script of instructions to build a Docker image.

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["gunicorn", "myapp.wsgi:application"]

146. What is Docker Compose? Docker Compose is a tool for defining and running multi-container applications using a docker-compose.yml file. You define services (web, db, redis), their images, ports, volumes, and env vars. Run all with docker compose up.

147. What are Docker volumes? Volumes are Docker-managed persistent storage. Containers are ephemeral โ€” data is lost when a container is removed. Volumes persist data (e.g., database files) between container restarts. Use volumes: in Compose or -v flag in docker run.

148. What is the difference between CMD and ENTRYPOINT in a Dockerfile?

  • CMD: Default command that can be overridden at runtime.
  • ENTRYPOINT: Sets the containerโ€™s main process; harder to override. Use ENTRYPOINT for the executable and CMD for default arguments.

149. What is a reverse proxy? Why use Nginx with Django? Nginx sits in front of Django (Gunicorn), handles static files, SSL termination, load balancing, and passes dynamic requests to Gunicorn. Django/Gunicorn should never face the internet directly.

150. What is a .env file? Why is it important? Stores environment-specific config (secrets, DB URLs) outside of code. Never commit to git. Use python-decouple or django-environ to load in Django.

151. What is CI/CD?

  • CI (Continuous Integration) โ€” automatically run tests on every push.
  • CD (Continuous Deployment) โ€” automatically deploy if tests pass. Tools: GitHub Actions, GitLab CI, Jenkins.

๐Ÿ—๏ธ SYSTEM ARCHITECTURE, TESTING & GIT

152. What is horizontal vs vertical scaling?

  • Vertical โ€” bigger machine (more RAM/CPU). Has limits.
  • Horizontal โ€” more machines. Requires stateless app design and load balancer.

153. What is a load balancer? Distributing incoming network traffic across multiple backend servers to ensure no single server is overwhelmed, improving responsiveness and availability.

154. Microservices vs Monolith?

  • Monolith: Entire application tightly coupled in a single codebase.
  • Microservices: Application broken down into small, independent, loosely coupled services communicating via APIs.

155. What types of tests should a backend have?

  • Unit tests โ€” test individual functions/methods in isolation.
  • Integration tests โ€” test multiple components together (views + DB).
  • End-to-end tests โ€” test full request/response cycle.

156. What is pytest? How does it differ from unittest? pytest is a more Pythonic, less boilerplate testing framework. Fixtures > setUp/tearDown, simpler assertions, powerful plugins. Django: use pytest-django.

157. What is mocking? When do you use it? Replacing real objects with fakes during tests. Use when testing code that calls external services, DB, or APIs. unittest.mock.patch / MagicMock.

158. Git workflow basics? git init โ†’ git add โ†’ git commit. Branches for features (git checkout -b feature/x). merge or rebase back to main. pull request for code review. Never commit secrets.

159. What is a .gitignore file? (Added) A text file that tells Git which files or folders to ignore and not track in version control (e.g., venv/, .env, __pycache__/, .sqlite3).

160. What is git rebase vs git merge?

  • merge โ€” creates a merge commit, preserves history.
  • rebase โ€” replays commits on top of another branch, linear history. Donโ€™t rebase shared/public branches.