Part 1: Python, Django, and Backend Fundamentals
Python Fundamentals
1. What is the difference between mutable and immutable data types in Python? Mutable objects can be changed after creation (e.g., Lists, Dictionaries, Sets). Immutable objects cannot be changed; modifying them creates a new object in memory (e.g., Integers, Strings, Tuples).
2. Difference between a List and a Tuple?
Lists are mutable and defined with []. Tuples are immutable, defined with (), and are generally faster and more memory-efficient than lists.
3. Difference between a Dictionary and a Set?
Both use {}. A Dictionary is a collection of key-value pairs where keys are unique. A Set is an unordered collection of unique elements (keys only, no values).
4. What are Python decorators? A decorator is a function that takes another function, extends its behavior without modifying it, and returns a new function. Commonly used for logging, authentication, and caching.
5. What are generators?
Generators are functions that return an iterable sequence of items one at a time using the yield keyword, rather than storing them all in memory. Great for processing large datasets.
6. 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.
7. What is list comprehension?
A concise way to create lists using a single line of code. Example: [x**2 for x in range(10) if x % 2 == 0].
8. What are lambda functions?
Small, anonymous, inline functions defined using the lambda keyword. They can have multiple arguments but only one expression. Example: add = lambda x, y: x + y.
9. Explain map(), filter(), and reduce().
map(): Applies a function to all items in an iterable.filter(): Returns items from an iterable for which a function returns True.reduce(): Applies a rolling computation to sequential pairs of values in an iterable (requiresfunctoolsimport).
10. What are *args and **kwargs?
*args: Allows passing a variable number of positional arguments (received as a tuple).**kwargs: Allows passing a variable number of keyword arguments (received as a dictionary).
11. Shallow copy vs Deep copy? A shallow copy creates a new object but inserts references to the items found in the original. A deep copy creates a new object and recursively copies all objects found in the original, ensuring no shared references.
12. 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).
13. What is the __init__ method?
It is the constructor method in Python classes, automatically called when a new instance of a class is created. It initializes object attributes.
14. __str__ vs __repr__?
__str__: Returns an informal, human-readable string representation of an object.__repr__: Returns a formal, detailed string representation meant for developers (ideally, code that could recreate the object).
15. What is the self keyword?
self represents the instance of the class. It binds the attributes and methods to that specific object.
16. Class method vs Instance method vs Static method?
- Instance method: Takes
selfas the first parameter; modifies object state. - Class method: Takes
clsas the first parameter (@classmethod); modifies class state that applies across all instances. - Static method: Takes neither
selfnorcls(@staticmethod); acts like a regular function that belongs to the class’s namespace but doesn’t modify state.
17. Does Python support multiple inheritance?
Yes. A class can inherit from multiple base classes. Example: class Child(Base1, Base2):
18. What is MRO (Method Resolution Order)?
The order in which Python searches for base classes during multiple inheritance. It follows the C3 linearization algorithm (left-to-right, depth-first). Accessible via ClassName.__mro__.
19. What is Duck Typing? A concept where the type of an object is less important than the methods/attributes it possesses. “If it walks like a duck and quacks like a duck, it’s a duck.”
20. What is the GIL (Global Interpreter Lock)? A mutex in CPython that allows only one thread to execute Python bytecodes at a time. This makes CPU-bound multi-threading inefficient in Python, though I/O-bound multi-threading is still useful.
21. 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.
22. How is memory managed in Python? Python manages memory automatically using a private heap. Memory allocation is handled by the Python memory manager.
23. How does Garbage Collection work in Python? Python uses Reference Counting (deallocating objects when their reference count drops to zero) and a cyclic garbage collector to detect and break circular references.
24. What are Context Managers (with statement)?
They ensure proper allocation and release of resources (like closing a file or database connection), even if an exception occurs. Implemented using __enter__ and __exit__ methods.
25. is vs ==?
== checks for value equality (do they have the same data?). is checks for identity (do they point to the exact same object in memory?).
26. Python Exception Handling structure?
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).
27. What is a virtual environment? An isolated environment that allows you to install specific versions of packages for a project without conflicting with global system packages.
28. 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__().
29. Python Scope Resolution (LEGB)? Python searches for variables in this order: Local, Enclosing (non-local), Global, and Built-in.
30. 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.
31. 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).
32. __new__ vs __init__?
__new__ creates and returns a new instance of a class (allocates memory). __init__ initializes that newly created instance.
33. 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()).
34. Global vs Local variables?
Local variables are declared inside a function and are only accessible there. Global variables are declared outside and accessible anywhere, but require the global keyword to be modified inside a function.
35. How do you copy a dictionary?
Using dict.copy() for a shallow copy, or copy.deepcopy(dict) from the copy module for a deep copy.
Django Fundamentals & ORM
36. What is Django? A high-level, open-source Python web framework that encourages rapid development and clean, pragmatic design. It follows the “Batteries Included” philosophy.
37. Explain Django’s architecture (MVT). Model-View-Template.
- Model: Handles database data and logic.
- View: Handles business logic and routing data between Model and Template.
- Template: Handles presentation/UI (HTML).
38. 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.
39. What is manage.py?
A command-line utility created in every Django project used to interact with the project (e.g., runserver, makemigrations, shell).
40. Purpose of settings.py?
It contains all the configuration for the Django project: database setups, installed apps, middleware, static files paths, and security keys.
41. What is a Django Model?
A Python class that inherits from models.Model. It defines the fields and behaviors of the data, automatically mapping to a database table.
42. What are Django Migrations? Migrations are Django’s way of propagating changes made to your models (adding a field, deleting a model, etc.) into the database schema.
43. makemigrations vs migrate?
makemigrations: Generates the migration files based on model changes.migrate: Applies those generated migration files to the actual database.
44. What is the Django ORM? Object-Relational Mapper. It allows you to interact with your database using Python code instead of writing raw SQL.
45. What is a QuerySet? A collection of data from a database. It is lazy, meaning it doesn’t hit the database until the data is actually evaluated/used.
46. filter() vs exclude()?
filter() returns records matching the given parameters. exclude() returns records that do not match the given parameters.
47. get() vs filter()?
get() returns a single object and raises DoesNotExist if 0 found, or MultipleObjectsReturned if >1 found. filter() returns a QuerySet (which can be empty or contain multiple items) and never raises these errors.
48. select_related vs prefetch_related?
Both optimize database queries by preventing N+1 problems.
select_related: Uses an SQLJOIN. Used for single-valued relationships (OneToOne, ForeignKey).prefetch_related: Does a separate lookup in Python. Used for multi-valued relationships (ManyToMany, Reverse ForeignKey).
49. What are F() expressions?
Allow you to reference a model field’s value directly in the database without pulling it into Python memory. Used for concurrent updates. Example: Product.objects.update(price=F('price') + 10).
50. What are Q() objects?
Used to construct complex database queries involving logical operators like OR (|) and NOT (~), which basic filter() cannot do easily.
51. Aggregate vs Annotate?
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.
52. How to bypass ORM and write raw SQL?
Using Model.objects.raw('SELECT * FROM table') or using django.db.connection for direct cursor execution.
53. What is the Django Admin?
An automatically generated backend UI provided by Django to perform CRUD operations on your models. Enabled by registering models in admin.py.
54. What are Django Signals? A dispatcher system that allows decoupled applications to get notified when certain actions occur elsewhere in the framework (e.g., a model is saved).
55. Pre-save vs Post-save signals?
pre_save: Triggered right before a model’ssave()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).
56. What is Django Middleware? A framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output (e.g., Authentication, CSRF protection).
57. Explain the Django Request-Response cycle.
URL hits web server → WSGI/ASGI → Middleware → URL Router (urls.py) → View → Model/Database → Template → View → Middleware → Web server → Browser.
58. What is the CSRF token?
Cross-Site Request Forgery token. A security measure generated by Django to prevent malicious websites from submitting forms on behalf of an authenticated user. Required in all POST forms using {% csrf_token %}.
59. 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).
60. 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.
61. 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.
62. How does user authentication work in Django?
Django provides a built-in User model, session management, and utility functions like authenticate(), login(), and logout() to handle user state securely.
63. 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.
64. 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.
65. 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).
66. How does URL routing work (urls.py)?
Django uses URL dispatcher to map URL patterns (using regex or path converters like <int:id>) to their corresponding View functions.
67. 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).
68. Static vs Media files?
- Static: Files bundled with the app (CSS, JS, logos). Collected via
collectstaticfor production. - Media: User-uploaded files (profile pictures, document uploads).
69. What are Django Fixtures?
JSON, XML, or YAML files used to populate the database with initial dummy or required data using the loaddata command.
70. Why override the save() method on a model?
To execute custom logic every time a specific model is saved, such as auto-generating a slug from a title before committing to the database.
General Backend & Databases
71. What is an RDBMS? Relational Database Management System. Stores data in structured tables with rows and columns, linked by relationships (e.g., PostgreSQL, MySQL).
72. SQL vs NoSQL?
- SQL (Relational): Structured schema, ACID compliant, uses tables. Good for complex queries and strict data integrity.
- NoSQL (Non-relational): Flexible schema, scalable horizontally, uses documents/key-value pairs (e.g., MongoDB, Redis). Good for unstructured data and rapid scaling.
73. Primary Key vs Foreign Key?
- Primary Key: Uniquely identifies a record in a table. Cannot be NULL.
- Foreign Key: A field in one table that uniquely identifies a row in another table, establishing a relationship.
74. Unique constraint vs Primary Key? A table can have multiple Unique constraints but only one Primary Key. Unique constraints can accept NULL values (depending on the DB), while Primary Keys cannot.
75. 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).
76. What is Denormalization? Intentionally adding redundant data to a database to improve read performance and reduce complex JOIN operations, usually in read-heavy applications.
77. Explain ACID properties.
- Atomicity: All parts of a transaction succeed, or none do.
- Consistency: Data remains valid according to rules before and after a transaction.
- Isolation: Concurrent transactions don’t interfere with each other.
- Durability: Committed transactions remain saved even in system failures.
78. What are Database Indexes? Data structures (often B-trees) that improve the speed of data retrieval operations on a table at the cost of additional storage space and slower writes.
79. 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.
80. What is a Database Transaction? A sequence of operations performed as a single logical unit of work. It must be completed entirely (Commit) or completely undone (Rollback).
81. What is the N+1 Query Problem?
An anti-pattern where an application executes 1 query to retrieve an object, and then N queries to retrieve related data for each object. Solved in Django using select_related/prefetch_related.
82. What is Connection Pooling? Maintaining a cache of open database connections that can be reused for future requests, rather than opening and closing a connection per request, massively improving performance.
83. What is the CAP Theorem? States that a distributed data store can only simultaneously provide two of three guarantees: Consistency, Availability, and Partition Tolerance.
84. MVC vs MVT architecture?
- MVC: Model-View-Controller. Controller handles routing/logic, View is strictly UI.
- MVT: Model-View-Template (Django). The framework acts as the Controller, View handles logic, Template is the UI.
85. HTTP vs HTTPS? HTTPS is HTTP with encryption and verification via SSL/TLS certificates. It ensures data sent between client and server is secure and cannot be intercepted (Man-in-the-Middle attack).
86. Explain HTTP Methods.
- GET: Retrieve data.
- POST: Create new data.
- PUT: Update existing data entirely.
- PATCH: Update data partially.
- DELETE: Remove data.
87. Idempotent vs Safe HTTP methods?
- Safe: Doesn’t modify data (GET, OPTIONS).
- Idempotent: Making the same request multiple times produces the same server state as a single request (GET, PUT, DELETE). POST is not idempotent.
88. Common HTTP Status Codes?
- 200: OK / 201: Created
- 400: Bad Request / 401: Unauthorized (not logged in) / 403: Forbidden (lacks permission) / 404: Not Found
- 500: Internal Server Error
89. Session vs Cookies? Cookies are stored on the client’s browser (can hold session IDs). Sessions are stored on the server-side, mapped to the user via the session ID stored in the client’s cookie.
90. Token-based vs Session-based authentication?
- 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.
91. What is JWT (JSON Web Token)? A compact, URL-safe token used for stateless authentication. It consists of three parts: Header, Payload (claims/data), and Signature.
92. What is OAuth2? An authorization framework that enables third-party applications to obtain limited access to a web service without sharing passwords (e.g., “Log in with Google”).
93. What is CORS?
Cross-Origin Resource Sharing. A browser security feature that restricts cross-origin HTTP requests. Handled in Django via django-cors-headers.
94. 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.
95. What is Rate Limiting? Restricting the number of requests a user/IP can make to an API within a specific timeframe to prevent abuse, scraping, and DDoS attacks.
96. What is Load Balancing? Distributing incoming network traffic across multiple backend servers to ensure no single server is overwhelmed, improving responsiveness and availability.
97. Forward Proxy vs Reverse Proxy?
- Forward Proxy: Sits in front of client devices, routing requests to the internet (hides client).
- Reverse Proxy: Sits in front of web servers, routing internet requests to the servers (hides server, handles SSL, load balances e.g., Nginx).
98. 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.
99. Why use Message Queues (Celery/RabbitMQ)? To handle long-running or background tasks (like sending emails or processing images) asynchronously, ensuring the main HTTP request-response cycle isn’t blocked.
100. Web Server (Nginx) vs App Server (Gunicorn)?
- Nginx: Serves static files, handles SSL, acts as a reverse proxy. Cannot run Python natively.
- Gunicorn: WSGI HTTP server that translates web requests into Python code for Django to understand.
Part 2: REST API, WebRTC/WebSockets, Docker, Redis, and Caching
Understanding of REST API
101. What is REST? Representational State Transfer. An architectural style for designing networked applications based on standard HTTP protocols.
102. What are the guiding principles of REST?
- Client-Server separation. 2. Statelessness. 3. Cacheability. 4. Uniform Interface. 5. Layered System.
103. 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).
104. What is a RESTful URI?
A URL that identifies a resource using nouns, not verbs. (e.g., /api/users/123 instead of /api/getUser?id=123).
105. 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).
106. What is HATEOAS? Hypermedia As The Engine Of Application State. A constraint of REST where responses contain links to other related endpoints, allowing the client to navigate the API dynamically.
107. PUT vs PATCH in REST? PUT replaces the entire resource. PATCH partially updates the resource, changing only the fields provided.
108. Serialization vs Deserialization?
- Serialization: Converting a complex object (like a Django Model instance) into a native Python datatype, then into JSON.
- Deserialization: Parsing incoming JSON back into complex types/Models after validation.
109. What is Django REST Framework (DRF)? A powerful toolkit built on top of Django to rapidly and cleanly build Web APIs, providing serialization, views, authentication, and routing out of the box.
110. APIView vs ViewSet in DRF?
APIView: Base class for views. You manually define HTTP methods (get(),post()).ViewSet: Combines logic for related views into a single class using actions (list(),retrieve(),create()), which DRF routers automatically map to URLs.
111. What is the role of 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).
112. What is a ModelSerializer? A DRF shortcut that automatically generates a Serializer class with fields matching a specific Django Model, including default validators.
113. Authentication vs Permissions in DRF?
- 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).
114. How does Throttling work in DRF?
It controls the rate of requests a user can make to an API (Rate Limiting). Configured globally or per-view (e.g., 100/day).
115. Why is API Versioning important?
It allows developers to make breaking changes to an API (e.g., /v2/users/) without breaking existing client applications still using older versions (/v1/users/).
WebRTC and WebSockets
116. What are WebSockets? A communication protocol providing full-duplex, persistent, bi-directional communication channels over a single TCP connection. Best for real-time apps (chat apps, live sports updates).
117. WebSockets vs HTTP Polling/Long-Polling?
- Polling: Client repeatedly asks the server for updates. High overhead.
- WebSockets: Open connection where server actively pushes data to the client instantly. Low overhead.
118. How does a WebSocket handshake work?
It starts as a standard HTTP request with an Upgrade: websocket header. If the server supports it, it responds with HTTP 101 Switching Protocols, converting the connection to a WebSocket.
119. What is Django Channels? A project that takes Django and extends its abilities beyond HTTP, enabling it to handle WebSockets, chat protocols, and other asynchronous protocols.
120. ASGI vs WSGI?
- WSGI: Synchronous Python standard for web servers. Handles one request at a time per thread.
- ASGI: Asynchronous Server Gateway Interface. Supports synchronous AND asynchronous apps (like WebSockets and long-polling).
121. What is WebRTC? Web Real-Time Communication. An open framework that enables peer-to-peer (P2P) video, audio, and arbitrary data communication directly between browsers without plugins.
122. WebRTC vs WebSockets? WebSockets are client-to-server. WebRTC is client-to-client (Peer-to-Peer), minimizing latency, making it ideal for video calling and VoIP.
123. What is Signaling in WebRTC? WebRTC needs a way for peers to find each other before establishing a P2P connection. Signaling uses a central server (often via WebSockets) to exchange connection data (SDP and ICE candidates).
124. STUN vs TURN servers?
- STUN: Tells a client its public IP address to bypass NAT routers.
- TURN: A fallback relay server used when a direct P2P connection fails due to strict firewalls.
125. What does Peer-to-Peer (P2P) mean? A network topology where clients communicate directly with each other, sharing resources without relying on a central server for data transfer.
Docker
126. What is Docker? A platform that uses OS-level virtualization to deliver software in standardized packages called containers, containing code, runtime, system tools, and libraries.
127. 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.
128. Docker Image vs Container? An Image is a read-only blueprint containing the instructions and code to create a container. A Container is the live, running instance of an Image.
129. What is a Dockerfile?
A text document containing all the commands a user could call on the command line to assemble a Docker Image (e.g., FROM, RUN, COPY, CMD).
130. docker run vs docker build?
docker build: Creates a Docker image from a Dockerfile.docker run: Starts a container from a Docker image.
131. What are Docker Volumes? Mechanisms to persist data generated by and used by Docker containers. Without volumes, data is lost when a container is destroyed.
132. What is Docker Compose?
A tool for defining and running multi-container Docker applications using a docker-compose.yml file (e.g., spinning up a Django app container and a PostgreSQL database container together).
133. What is port mapping in Docker?
Connecting a port on the host machine to a port inside the container (e.g., -p 8000:80). This allows external traffic to reach the app running inside the container.
134. Docker network types (Bridge, Host, None)?
- Bridge: Default. Containers can talk to each other on an isolated internal network.
- Host: Container shares the host’s network stack directly.
- None: Disables all networking for the container.
135. Why use Docker for local development? It eliminates the “it works on my machine” problem. It ensures exact parity between development, staging, and production environments.
Redis & Caching Mechanism
136. What is Caching? Storing a copy of expensive, frequently accessed data in a fast, temporary storage layer (usually RAM) so future requests are served faster than querying the primary database.
137. Cache Hit vs Cache Miss?
- Hit: Requested data is found in the cache.
- Miss: Data is not in the cache, forcing the system to query the primary database (and usually saving the result to the cache afterward).
138. What is Redis? Remote Dictionary Server. An open-source, in-memory, NoSQL key-value data store used primarily as a database, cache, and message broker.
139. Redis vs Memcached? Memcached is simple string-based caching. Redis supports complex data structures (Lists, Sets, Hashes), disk persistence, and pub/sub messaging.
140. What data structures does Redis support? Strings, Lists, Sets, Sorted Sets, Hashes, Bitmaps, and HyperLogLogs.
141. Why is Redis so fast? It stores all data in primary memory (RAM) and uses a highly optimized single-threaded event loop, avoiding context switching and thread locks.
142. Cache Eviction Policies (LRU, LFU)? Rules for what data to delete when the cache is full.
- LRU (Least Recently Used): Discards items that haven’t been accessed for the longest time.
- LFU (Least Frequently Used): Discards items accessed the least number of times overall.
143. What is TTL (Time To Live)? An expiration time assigned to a cached item. Once the TTL expires, the item is automatically deleted from the cache, ensuring stale data isn’t kept forever.
144. Common Caching Strategies?
- Cache-Aside (Lazy Loading): App checks cache; if miss, queries DB, updates cache, returns data.
- Write-Through: App writes to cache AND DB simultaneously.
- Write-Behind: App writes to cache, which asynchronously writes to DB later.
145. What is Redis Pub/Sub? Publish/Subscribe. A messaging paradigm where senders (publishers) send messages to channels without knowing the receivers (subscribers), used in real-time notifications or chat.
146. How to implement caching in Django?
Configure a cache backend (like Redis) in settings.py (CACHES dict). Use Django’s cache API (cache.set(), cache.get()) or decorators (@cache_page).
147. Per-view vs Template fragment caching in Django?
- Per-view: Caches the entire HTML output of a specific view using
@cache_page(timeout). - Template fragment: Caches only a specific block of a template using
{% cache timeout cache_name %} … {% endcache %}.
148. 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.
149. 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.
150. What is Distributed Caching? A cache shared across multiple application servers, hosted on a separate cluster of nodes (like Redis Cluster). It ensures all app servers see the exact same cached data and scales horizontally.