Q: What is Git and why is it used?
A: Git is a distributed version control system that tracks changes in source code during software development. It enables:
Q: What is the difference between Git and GitHub?
A:
Q: Explain the basic Git workflow.
A:
git add)git commit)git push)Working Directory → git add → Staging Area → git commit → Local Repo → git push → Remote Repo
Q: What is the difference between git pull and git fetch?
A:
git fetch: Downloads changes from remote but doesn't merge them. Updates remote-tracking branches.git pull: Combination of git fetch + git merge. Downloads and immediately merges changes into current branch.# Fetch only
git fetch origin main
# Pull (fetch + merge)
git pull origin main
Q: What is git merge vs git rebase? (IMPORTANT - Asked in Interview Experience 01)
A:
Git Merge:
git checkout main
git merge feature-branch
# Creates merge commit: "Merge branch 'feature-branch' into main"
Git Rebase:
git checkout feature-branch
git rebase main
# Moves all commits from feature-branch on top of main
When to use what:
Q: What is a merge conflict and how do you resolve it?
A: A merge conflict occurs when Git cannot automatically merge changes because the same lines were modified in different branches.
Resolution steps:
<<<<<<< HEAD
Your current changes
=======
Incoming changes
>>>>>>> branch-name
git add <resolved-file>git commit to complete the mergeQ: What is git stash and when would you use it?
A: git stash temporarily saves uncommitted changes so you can work on something else.
Use cases:
git stash # Save current changes
git stash pop # Restore and remove from stash
git stash apply # Restore but keep in stash
git stash list # View all stashes
git stash drop # Remove a stash
Q: What is the difference between git reset and git revert?
A:
git reset:
git reset --soft HEAD~1 # Undo commit, keep changes staged
git reset --mixed HEAD~1 # Undo commit and staging, keep changes
git reset --hard HEAD~1 # Undo everything (DESTRUCTIVE)
git revert:
git revert # Creates new commit undoing the specified commit
Q: What is a detached HEAD state?
A: When HEAD points directly to a commit instead of a branch reference.
Occurs when:
git checkout <commit-hash>To fix:
git checkout main # Return to a branch
# OR create a new branch from detached state
git checkout -b new-branch
Q: What is git cherry-pick?
A: Applies changes from specific commits from one branch to another.
git cherry-pick
# Useful for: Applying a bug fix from one branch to another without merging everything
Q: What is .gitignore and how does it work?
A: A file that specifies which files/directories Git should ignore.
Common patterns:
# Dependencies
node_modules/
venv/
# Environment variables
.env
.env.local
# Build outputs
dist/
build/
*.pyc
# IDE
.vscode/
.idea/
# OS files
.DS_Store
Thumbs.db
# Logs
*.log
logs/
Note: Files already tracked won't be ignored. Use:
git rm --cached # Remove from tracking, keep locally
Q: What are common Git branching strategies?
A:
1. Git Flow:
main (production), develop (integration)feature/*, release/*, hotfix/*2. GitHub Flow:
3. Trunk-Based Development:
Q: What is a Pull Request (PR)?
A: A request to merge changes from one branch to another, providing:
Best practices:
Q: What are Git hooks?
A: Scripts that run automatically at certain points in Git workflow.
Common hooks:
pre-commit: Run before commit (linting, formatting)pre-push: Run before push (run tests)post-merge: Run after mergeprepare-commit-msg: Modify commit messageExample pre-commit hook:
#!/bin/sh
# Run linter before commit
npm run lint
if [ $? -ne 0 ]; then
echo "Linting failed. Commit aborted."
exit 1
fi
Q: How would you undo the last commit but keep the changes?
git reset --soft HEAD~1
# Changes remain staged, ready to modify and recommit
Q: How do you rename a branch?
# Rename current branch
git branch -m new-name
# Rename from another branch
git branch -m old-name new-name
# Push renamed branch and delete old remote branch
git push origin :old-name new-name
git push origin -u new-name
Q: How do you delete a branch?
# Delete local branch
git branch -d branch-name # Safe delete (only if merged)
git branch -D branch-name # Force delete
# Delete remote branch
git push origin --delete branch-name
Q: You accidentally committed to the wrong branch. How do you fix it?
# Move commit to correct branch
git checkout correct-branch
git cherry-pick wrong-branch # Apply the commit
git checkout wrong-branch
git reset --hard HEAD~1 # Remove from wrong branch
Q: How do you find which commit introduced a bug?
git bisect start
git bisect bad # Current commit is bad
git bisect good # Last known good commit
# Git will checkout middle commit, test it
git bisect good/bad # Mark current commit
# Repeat until bug commit is found
git bisect reset # Exit bisect mode
Q: What are the phases of Software Development Life Cycle (SDLC)?
A:
Q: What is Agile methodology?
A: An iterative approach to software development emphasizing:
Key principles:
Q: What is a Sprint in Agile?
A: A time-boxed iteration (typically 1-4 weeks) where a team:
Q: What is Scrum?
A: An Agile framework with specific roles and ceremonies:
Roles:
Ceremonies:
Q: What is the difference between Agile and Waterfall?
A:
| Aspect | Waterfall | Agile |
|---|---|---|
| Approach | Sequential, linear | Iterative, incremental |
| Flexibility | Rigid, changes difficult | Flexible, welcomes changes |
| Testing | After development | Continuous |
| Customer Involvement | Beginning and end | Throughout |
| Delivery | End of project | Frequent releases |
| Best for | Well-defined requirements | Evolving requirements |
Q: What is Kanban?
A: A visual workflow management method using boards with columns:
Key principles:
Difference from Scrum:
Q: What is DevOps?
A: A culture combining development and operations to:
Key practices:
Q: What are the different levels of software testing?
A:
1. Unit Testing:
2. Integration Testing:
3. System Testing:
4. Acceptance Testing:
Q: What is the difference between Black Box and White Box testing?
A:
Black Box Testing:
White Box Testing:
Q: What is Test-Driven Development (TDD)?
A: A development approach where tests are written before code:
Cycle:
Benefits:
Example:
// 1. Write test first (RED)
test('add function should sum two numbers', () => {
expect(add(2, 3)).toBe(5);
});
// 2. Write minimal code (GREEN)
function add(a, b) {
return a + b;
}
// 3. Refactor if needed
Q: What is Behavior-Driven Development (BDD)?
A: Extension of TDD focusing on behavior from user perspective using natural language:
Format: Given-When-Then
Given a user is logged in
When they click "Add to Cart"
Then the item should appear in their cart
And cart count should increase by 1
Tools: Cucumber, Jasmine, Jest
Q: What is regression testing?
A: Re-running tests after code changes to ensure existing functionality still works.
When needed:
Automated regression tests catch unintended side effects.
Q: What is smoke testing?
A: Quick, basic tests to verify critical functionality works.
Purpose:
Example: Can users login? Can they access homepage?
Q: What is load testing vs stress testing?
A:
Load Testing:
Stress Testing:
Q: What is mocking in testing?
A: Creating fake objects to simulate real dependencies.
Why mock:
Example:
// Mock database call
const mockDb = {
getUser: jest.fn().mockResolvedValue({ id: 1, name: 'John' })
};
// Test uses mock instead of real database
test('getUserById returns user', async () => {
const user = await getUserById(1, mockDb);
expect(user.name).toBe('John');
});
Q: What is test coverage and is 100% coverage necessary?
A: Test coverage measures percentage of code executed by tests.
Types:
100% coverage:
Q: What makes a good unit test?
A: F.I.R.S.T. Principles:
Additional:
Q: What is the test pyramid?
A: A model showing ideal distribution of test types:
/\
/E2E\ ← Few, slow, expensive
/______\
/ \
/Integration\ ← Some
/____________\
/ \
/ Unit Tests \ ← Many, fast, cheap
/__________________\
Principle: More unit tests (base), fewer integration tests, even fewer E2E tests.
Q: What is clean code?
A: Code that is:
Q: What are SOLID principles?
A: Five object-oriented design principles:
1. Single Responsibility Principle (SRP):
# BAD: Class doing too much
class User:
def save_to_database(self):
pass
def send_email(self):
pass
def generate_report(self):
pass
# GOOD: Separated concerns
class User:
pass
class UserRepository:
def save(self, user):
pass
class EmailService:
def send_email(self, user):
pass
2. Open/Closed Principle (OCP):
# BAD: Need to modify for new types
class PaymentProcessor:
def process(self, type):
if type == "credit":
# credit card logic
elif type == "paypal":
# paypal logic
# GOOD: Extend with new classes
class PaymentProcessor:
def process(self):
pass
class CreditCardProcessor(PaymentProcessor):
def process(self):
# credit card logic
class PayPalProcessor(PaymentProcessor):
def process(self):
# paypal logic
3. Liskov Substitution Principle (LSP):
4. Interface Segregation Principle (ISP):
5. Dependency Inversion Principle (DIP):
# BAD: Direct dependency
class App:
def __init__(self):
self.database = MySQLDatabase() # Tightly coupled
# GOOD: Depend on abstraction
class App:
def __init__(self, database: DatabaseInterface):
self.database = database # Loosely coupled
Q: What is DRY principle?
A: Don't Repeat Yourself - Every piece of knowledge should have a single, unambiguous representation.
Benefits:
# BAD: Repeated logic
def calculate_price_for_regular(price):
return price * 0.9
def calculate_price_for_premium(price):
return price * 0.8
# GOOD: DRY
def calculate_price(price, discount):
return price * (1 - discount)
Q: What is KISS principle?
A: Keep It Simple, Stupid - Simplicity should be a key goal; avoid unnecessary complexity.
Examples:
Q: What is YAGNI principle?
A: You Aren't Gonna Need It - Don't add functionality until it's necessary.
Benefits:
Q: What should you look for in a code review?
A:
Functionality:
Code Quality:
Testing:
Performance:
Security:
Documentation:
Q: What is technical debt?
A: The implied cost of future rework caused by choosing quick/easy solution now instead of better approach.
Types:
Managing:
Q: What is refactoring?
A: Restructuring existing code without changing external behavior to improve:
When to refactor:
Common refactorings:
Golden rule: Have tests before refactoring!
Q: What are code smells?
A: Indicators that code might need refactoring:
Common smells:
Q: What is the difference between Authentication and Authorization?
A:
Authentication (AuthN):
Authorization (AuthZ):
Flow: Authentication first, then Authorization
Q: What are common authentication methods?
A:
1. Basic Authentication:
2. Token-based (JWT):
3. OAuth 2.0:
4. Multi-Factor Authentication (MFA):
Q: What is JWT (JSON Web Token)?
A: A compact, self-contained token for securely transmitting information.
Structure: header.payload.signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. ← Header
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4. ← Payload
TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ ← Signature
Components:
Use cases:
Benefits:
Drawbacks:
Q: What is the difference between session-based and token-based authentication?
A:
Session-based:
Token-based:
| Aspect | Session | Token |
|---|---|---|
| Storage | Server | Client |
| Scalability | Harder | Easier |
| Cross-domain | Difficult | Easy |
| Mobile apps | Not ideal | Ideal |
Q: What is SQL Injection and how do you prevent it?
A: Attack where malicious SQL code is inserted into queries.
Example attack:
-- User input: ' OR '1'='1
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '';
-- Returns all users!
Prevention:
# BAD
query = f"SELECT * FROM users WHERE username = '{username}'"
# GOOD
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
Q: What is Cross-Site Scripting (XSS)?
A: Injecting malicious scripts into web pages viewed by other users.
Types:
Example:
alert('XSS') -->
Hello, alert('XSS')
Prevention:
< to <, > to >Q: What is Cross-Site Request Forgery (CSRF)?
A: Trick authenticated user into executing unwanted actions.
Example:
Prevention:
Q: What are best practices for storing passwords?
A:
Never:
Do:
import bcrypt
# Hashing
password = b"mysecretpassword"
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password, salt)
# Verification
if bcrypt.checkpw(password, hashed):
print("Password matches!")
Q: What is HTTPS and why is it important?
A: HTTP over TLS/SSL - encrypts data between client and server.
Benefits:
When needed:
Q: What is CORS (Cross-Origin Resource Sharing)?
A: Browser security feature that restricts cross-origin HTTP requests.
Same-Origin Policy:
http://site-a.com can't request http://site-b.comCORS headers allow it:
Access-Control-Allow-Origin: https://trusted-site.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type
Why important:
Q: What is the principle of least privilege?
A: Grant minimum permissions necessary to perform a task.
Examples:
Benefits:
Q: Why is input validation important?
A: Never trust user input!
Risks without validation:
Validation types:
Q: What is the difference between encoding, encryption, and hashing?
A:
Encoding:
Encryption:
Hashing:
Q: What is REST?
A: Representational State Transfer - Architectural style for web services.
Key constraints:
Q: What are HTTP methods and when to use them?
A:
| Method | Purpose | Idempotent | Safe | Use Case |
|---|---|---|---|---|
| GET | Retrieve resource | ✅ | ✅ | Fetch data |
| POST | Create resource | ❌ | ❌ | Create new |
| PUT | Update/Replace | ✅ | ❌ | Full update |
| PATCH | Partial update | ❌ | ❌ | Partial update |
| DELETE | Delete resource | ✅ | ❌ | Remove |
| HEAD | Headers only | ✅ | ✅ | Check existence |
| OPTIONS | Allowed methods | ✅ | ✅ | CORS preflight |
Q: What is idempotency in APIs? (IMPORTANT - You were asked this!)
A: An operation that produces same result when called multiple times.
Why important:
Examples:
GET /users/123 - Always returns same user (idempotent)PUT /users/123 - Setting data to same value multiple times (idempotent)DELETE /users/123 - First call deletes, subsequent calls do nothing (idempotent)POST /users - Creates new user each time (NOT idempotent)Making POST idempotent:
// Use idempotency key
POST /payments
Headers: {
"Idempotency-Key": "unique-request-id"
}
// Server checks if request with this key already processed
Q: What are HTTP status codes and their meanings?
A:
1xx - Informational:
2xx - Success:
3xx - Redirection:
4xx - Client Errors:
5xx - Server Errors:
Q: What is the difference between PUT and PATCH?
A:
PUT:
PUT /users/123
{
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
// All fields required
PATCH:
PATCH /users/123
{
"email": "newemail@example.com"
}
// Only updating email
Q: What is API versioning and why is it needed?
A: Managing changes to APIs without breaking existing clients.
Strategies:
1. URL versioning:
https://api.example.com/v1/users
https://api.example.com/v2/users
2. Header versioning:
GET /users
Headers: { "API-Version": "2" }
3. Query parameter:
https://api.example.com/users?version=2
When to version:
Q: What is rate limiting?
A: Controlling number of requests a client can make in a time period.
Why needed:
Implementation:
Response:
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640000000
Retry-After: 60
Q: What is pagination in APIs?
A: Dividing large result sets into pages.
Methods:
1. Offset-based:
GET /users?offset=20&limit=10
2. Cursor-based:
GET /users?cursor=eyJpZCI6MTIzfQ&limit=10
3. Page-based:
GET /users?page=3&per_page=10
Response includes:
{
"data": [...],
"pagination": {
"total": 100,
"page": 3,
"per_page": 10,
"next_cursor": "xyz"
}
}
Q: What makes a good API design?
A:
1. Consistency:
2. Intuitive:
3. Well-documented:
4. Versioned:
5. Secure:
6. Error handling:
{
"error": {
"code": "INVALID_EMAIL",
"message": "Email format is invalid",
"field": "email",
"details": "Expected format: user@example.com"
}
}
Q: What is RESTful resource naming convention?
A:
Use nouns, not verbs:
✅ GET /users
❌ GET /getUsers
✅ POST /users
❌ POST /createUser
Use plural for collections:
✅ GET /users
❌ GET /user
✅ GET /users/123
✅ GET /users/123/posts
Hierarchical:
/users/{userId}/posts/{postId}/comments
Use hyphens, not underscores:
✅ /user-profiles
❌ /user_profiles
Lowercase:
✅ /users
❌ /Users
Q: What is HATEOAS?
A: Hypermedia As The Engine Of Application State - API responses include links to related resources.
{
"id": 123,
"name": "John",
"links": {
"self": "/users/123",
"posts": "/users/123/posts",
"friends": "/users/123/friends"
}
}
Benefits:
Q: What is GraphQL?
A: A query language for APIs allowing clients to request exactly what they need.
Key features:
Example query:
{
user(id: 123) {
name
email
posts {
title
comments {
text
}
}
}
}
Q: GraphQL vs REST - when to use what?
A:
Use REST when:
Use GraphQL when:
Comparison:
| Aspect | REST | GraphQL |
|---|---|---|
| Endpoints | Multiple | Single |
| Over-fetching | Common | Rare |
| Under-fetching | Common (N+1) | Rare |
| Caching | Easy (HTTP) | Complex |
| Learning curve | Low | Higher |
Q: What are WebSockets and when would you use them?
A: Bidirectional, full-duplex communication over a single TCP connection.
REST/HTTP:
WebSocket:
Use cases:
Not needed for:
Q: What is monolithic architecture?
A: Single, unified application where all components are interconnected and interdependent.
Structure:
[Single Application]
├── UI Layer
├── Business Logic
├── Data Access
└── Database
Pros:
Cons:
Q: What are microservices?
A: Architectural style where app is collection of small, independent services.
Characteristics:
Example:
[API Gateway]
├── [User Service] → [User DB]
├── [Order Service] → [Order DB]
├── [Payment Service] → [Payment DB]
└── [Notification Service] → [Notification DB]
Pros:
Cons:
Q: When to use microservices vs monolith?
A:
Start with monolith when:
Move to microservices when:
Q: What is an API Gateway?
A: Single entry point for all client requests to microservices.
Responsibilities:
Example: AWS API Gateway, Kong, Nginx
Q: How do microservices communicate?
A:
Synchronous:
1. REST/HTTP:
2. gRPC:
Asynchronous:
1. Message Queue:
Service A → [Queue] → Service B
2. Event Bus:
Service A publishes "OrderCreated"
↓
Service B (Inventory): Updates stock
Service C (Email): Sends confirmation
Service D (Analytics): Logs event
Q: What is service discovery?
A: Mechanism for services to find each other in distributed system.
Why needed:
Types:
1. Client-side discovery:
2. Server-side discovery:
Q: What is layered (N-tier) architecture?
A: Organizing code into horizontal layers, each with specific responsibility.
Common layers:
┌────────────────────┐
│ Presentation Layer │ ← UI, API endpoints
├────────────────────┤
│ Business Layer │ ← Business logic
├────────────────────┤
│ Data Access Layer │ ← Database operations
├────────────────────┤
│ Database │
└────────────────────┘
Rules:
Benefits:
Drawbacks:
Q: What is MVC (Model-View-Controller)?
A: Design pattern separating application into three components:
Model:
View:
Controller:
Flow:
User → Controller → Model → Controller → View → User
Example (web app):
# Model
class User:
def get_by_id(self, id):
return db.query(f"SELECT * FROM users WHERE id={id}")
# Controller
@app.route('/users/')
def get_user(id):
user = User().get_by_id(id)
return render_template('user.html', user=user)
# View (user.html)
{{ user.name }}
Benefits:
Q: What is event-driven architecture?
A: System where components communicate through events.
Components:
Characteristics:
Example use case:
E-commerce order placed:
→ Inventory service: Reserve items
→ Payment service: Process payment
→ Email service: Send confirmation
→ Analytics service: Log event
Benefits:
Challenges:
Q: What is the Saga pattern?
A: Managing distributed transactions across microservices.
Problem:
Solution - Choreography:
Each service publishes events, others listen and react:
Order Service: Create order → Event
Payment Service: Charge card → Event
Inventory Service: Reserve items → Event
If failure: Each service compensates (undo its action)
Solution - Orchestration:
Central coordinator manages flow:
[Saga Orchestrator]
1. Call Order Service
2. Call Payment Service
3. Call Inventory Service
If any fails → trigger compensations
Q: What is Circuit Breaker pattern?
A: Prevent cascading failures when service is down.
States:
Flow:
Closed → (failures exceed threshold) → Open
Open → (timeout) → Half-Open
Half-Open → (success) → Closed
Half-Open → (failure) → Open
Benefits:
Implementation: Netflix Hystrix, Resilience4j
Q: What is the Strangler Fig pattern?
A: Gradually replace monolith with microservices.
Strategy:
Why called Strangler Fig:
Q: What is CQRS (Command Query Responsibility Segregation)?
A: Separate read and write operations.
Traditional:
[Same Model for Read & Write]
CQRS:
Commands (Write) → [Write Model] → Database
Queries (Read) ← [Read Model] ← Database
Benefits:
Use when:
Q: What is the Bulkhead pattern?
A: Isolate resources to prevent total system failure.
Analogy: Ship compartments - if one fills with water, others stay intact.
Implementation:
Service has 100 threads:
- 70 for normal API calls
- 20 for database operations
- 10 for external API calls
If external API hangs, only those 10 threads affected
Benefits:
Q: What is database per service pattern?
A: Each microservice has its own database.
Benefits:
Challenges:
Q: How to maintain data consistency across microservices?
A:
1. Eventual Consistency:
2. Saga Pattern:
3. Two-Phase Commit (2PC):
4. Event Sourcing:
Q: What is the API Composition pattern?
A: Combine data from multiple services for a query.
Example:
GET /orders/123/details needs:
- Order info (Order Service)
- Customer info (Customer Service)
- Product details (Product Service)
API Gateway/Composer:
1. Call Order Service
2. Call Customer Service (parallel)
3. Call Product Service (parallel)
4. Combine results
5. Return to client
Drawbacks:
Q: What is Continuous Integration (CI)?
A: Practice of frequently merging code changes into shared repository, with automated builds/tests.
Key practices:
Benefits:
Q: What is Continuous Deployment vs Continuous Delivery?
A:
Continuous Delivery (CD):
Continuous Deployment:
Pipeline:
Code → Build → Test → Stage → [Manual Approval] → Production (Delivery)
Code → Build → Test → Stage → Production (Deployment)
Q: What is a CI/CD pipeline?
A: Automated workflow for taking code from commit to production.
Typical stages:
Tools: Jenkins, GitHub Actions, GitLab CI, CircleCI, Travis CI
Q: What is Infrastructure as Code (IaC)?
A: Managing infrastructure through code instead of manual processes.
Benefits:
Tools:
Example (Terraform):
"aws_instance"">resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
}
}
Q: What is Docker?
A: Platform for developing, shipping, and running applications in containers.
Container:
Benefits:
Q: What is the difference between Container and Virtual Machine?
A:
Virtual Machine:
Container:
VM: [App → OS → Hypervisor → Hardware]
Container: [App → Container Runtime → OS → Hardware]
Q: What is a Dockerfile?
A: Blueprint for building Docker images.
Example:
# Base image
FROM node:18-alpine
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy app code
COPY . .
# Expose port
EXPOSE 3000
# Run command
CMD ["npm", "start"]
Common instructions:
FROM: Base imageWORKDIR: Set working directoryCOPY: Copy filesRUN: Execute command during buildEXPOSE: Document portCMD: Default command when container startsENV: Set environment variablesQ: What is Docker Compose?
A: Tool for defining and running multi-container applications.
Example (docker-compose.yml):
version: '3'
services:
web:
build: .
ports:
- "3000:3000"
depends_on:
- db
environment:
- DATABASE_URL=postgres://db:5432/myapp
db:
image: postgres:14
environment:
- POSTGRES_PASSWORD=secret
volumes:
- db-data:/var/lib/postgresql/data
volumes:
db-data:
Commands:
docker-compose up # Start all services
docker-compose down # Stop all services
docker-compose logs # View logs
Q: What is Kubernetes?
A: Container orchestration platform for automating deployment, scaling, and management.
Key concepts:
Pod:
Deployment:
Service:
ConfigMap/Secret:
Q: Why use Kubernetes?
A:
Q: What is a Kubernetes manifest?
A: YAML file defining desired state.
Example:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: myapp:1.0
ports:
- containerPort: 3000
Q: What is IaaS, PaaS, and SaaS?
A:
IaaS (Infrastructure as a Service):
PaaS (Platform as a Service):
SaaS (Software as a Service):
Analogy - Pizza:
Q: What is AWS EC2?
A: Elastic Compute Cloud - Virtual servers in the cloud.
Key concepts:
Q: What is AWS S3?
A: Simple Storage Service - Object storage.
Features:
Use cases:
Q: What is AWS Lambda?
A: Serverless compute - Run code without managing servers.
Characteristics:
Use cases:
Example:
def lambda_handler(event, context):
name = event['name']
return {
'statusCode': 200,
'body': f'Hello {name}!'
}
Q: What is AWS RDS?
A: Relational Database Service - Managed database.
Features:
Supported databases:
Q: What is a CDN (Content Delivery Network)?
A: Network of distributed servers delivering content based on user location.
How it works:
Benefits:
Examples: CloudFront (AWS), Cloudflare, Akamai
Q: What is auto-scaling?
A: Automatically adjusting compute resources based on demand.
Types:
Vertical scaling (scale up/down):
Horizontal scaling (scale out/in):
Scaling triggers:
Configuration:
Q: What is caching and when should you use it?
A: Storing frequently accessed data in fast-access storage.
Benefits:
What to cache:
What NOT to cache:
Q: What are different caching strategies?
A:
1. Cache-Aside (Lazy Loading):
1. Check cache
2. If miss → query database
3. Store in cache
4. Return data
Pros: Only cache needed data
Cons: Cache misses slow
2. Write-Through:
1. Write to database
2. Write to cache
3. Return
Pros: Cache always fresh
Cons: Write latency, cache unused data
3. Write-Behind (Write-Back):
1. Write to cache
2. Async write to database
3. Return immediately
Pros: Fast writes
Cons: Data loss risk if cache fails
4. Refresh-Ahead:
Q: What are cache eviction policies?
A:
LRU (Least Recently Used):
LFU (Least Frequently Used):
FIFO (First In, First Out):
TTL (Time To Live):
Q: What is Redis and when to use it?
A: In-memory data store used as cache, database, message broker.
Features:
Use cases:
Q: What is database indexing?
A: Data structure improving query performance.
How it works:
Example:
-- Without index
SELECT * FROM users WHERE email = 'john@example.com';
-- Scans all rows
-- Create index
CREATE INDEX idx_email ON users(email);
-- Now lookup is O(log n) instead of O(n)
Trade-offs:
Q: What is lazy loading?
A: Loading resources only when needed.
Example - Images:
Example - Code:
// Don't load until needed
button.onclick = async () => {
const module = await import('./heavy-module.js');
module.doSomething();
};
Benefits:
Q: What is database connection pooling?
A: Maintaining pool of reusable database connections.
Problem:
Solution:
[Connection Pool]
├── Connection 1 (idle)
├── Connection 2 (in use)
├── Connection 3 (idle)
└── Connection 4 (in use)
Request comes → Borrow connection → Use → Return to pool
Benefits:
Configuration:
Q: What is the N+1 query problem?
A: Performance issue where you make N additional queries in a loop.
Problem:
# 1 query to get posts
posts = Post.query.all()
# N queries (one per post)
for post in posts:
author = post.author # Separate query each time!
Result: 1 + N queries for N posts
Solution - Eager Loading:
# Single query with JOIN
posts = Post.query.options(joinedload(Post.author)).all()
for post in posts:
author = post.author # No additional query!
Result: 1 query total
Q: What is database denormalization?
A: Intentionally adding redundancy to improve read performance.
Normalized:
Users: Posts:
id | name id | user_id | title
1 | John 1 | 1 | Hello
# Need JOIN to get author name
Denormalized:
Posts:
id | user_id | author_name | title
1 | 1 | John | Hello
# No JOIN needed!
Trade-offs:
When to use:
Q: What is minification?
A: Removing unnecessary characters from code without changing functionality.
Before:
function calculateTotal(price, tax) {
const total = price + (price * tax);
return total;
}
After minification:
function calculateTotal(p,t){return p+p*t}
Removed:
Tools: UglifyJS, Terser, cssnano
Q: What is code splitting?
A: Breaking code into smaller bundles loaded on demand.
Instead of:
app.js (2MB) → User waits for entire bundle
Split:
main.js (100KB) → Loads immediately
route1.js (500KB) → Loads when needed
route2.js (400KB) → Loads when needed
Implementation:
// Dynamic import
const AdminPanel = lazy(() => import('./AdminPanel'));
Q: What is tree shaking?
A: Removing unused code from final bundle.
Example:
// utils.js
export function used() { }
export function unused() { }
// app.js
import { used } from './utils';
// Final bundle only includes 'used', removes 'unused'
Requires:
Q: What is scalability?
A: Ability of system to handle growing amount of work by adding resources.
Types:
Vertical Scaling (Scale Up):
Horizontal Scaling (Scale Out):
Q: What is a load balancer?
A: Distributes incoming traffic across multiple servers.
Benefits:
Algorithms:
Round Robin:
Least Connections:
IP Hash:
Weighted:
Examples: Nginx, HAProxy, AWS ELB
Q: What is the difference between stateful and stateless applications?
A:
Stateless:
Request 1 → Server A
Request 2 → Server B (works fine, no state needed)
Stateful:
Request 1 → Server A (creates session)
Request 2 → Server B (doesn't have session, fails!)
Making stateful apps scalable:
Q: What is database sharding?
A: Splitting database across multiple servers.
Vertical sharding (schema):
Database 1: Users table
Database 2: Orders table
Database 3: Products table
Horizontal sharding (rows):
Database 1: Users 1-1000
Database 2: Users 1001-2000
Database 3: Users 2001-3000
Sharding key examples:
Benefits:
Challenges:
Q: What is read replication?
A: Having multiple copies of database for reading.
[Master DB] ← Writes
↓ (replication)
[Replica 1] ← Reads
[Replica 2] ← Reads
[Replica 3] ← Reads
Benefits:
Trade-offs:
Q: What is database partitioning?
A: Dividing table into smaller pieces.
Horizontal partitioning:
Vertical partitioning:
Benefits:
Q: What are log levels?
A: Severity categories for log messages.
Common levels (lowest to highest):
TRACE:
DEBUG:
INFO:
WARN:
ERROR:
FATAL:
Q: What are best practices for logging?
A:
1. Structured logging:
# BAD
logger.info(f"User {user_id} logged in from {ip}")
# GOOD
logger.info("User logged in", extra={
"user_id": user_id,
"ip_address": ip,
"timestamp": now,
"event": "login"
})
2. Include context:
3. Don't log sensitive data:
4. Log appropriate level:
5. Make logs searchable:
Q: What is the difference between logging and monitoring?
A:
Logging:
Monitoring:
Example:
Q: What metrics should you monitor?
A:
Application metrics:
Infrastructure metrics:
Business metrics:
Q: What is APM (Application Performance Monitoring)?
A: Tools tracking application performance and user experience.
Features:
Tools: New Relic, Datadog, AppDynamics
Q: What are SLI, SLO, and SLA?
A:
SLI (Service Level Indicator):
SLO (Service Level Objective):
SLA (Service Level Agreement):
Q: What is alerting and how to do it effectively?
A: Notifications when things go wrong.
Best practices:
1. Alert on symptoms, not causes:
2. Actionable:
3. Avoid alert fatigue:
4. Levels:
Q: What is your debugging process?
A:
1. Reproduce:
2. Gather information:
3. Form hypothesis:
4. Test hypothesis:
5. Fix:
6. Verify:
Q: What debugging tools/techniques do you use?
A:
Debuggers:
Logging:
Profiling:
Binary search:
Rubber duck debugging:
Q: What is a stack trace and how to read it?
A: Shows function call sequence leading to error.
Example:
Error: Cannot read property 'name' of undefined
at getUserName (user.js:15:20)
at formatUser (formatter.js:8:12)
at processRequest (handler.js:25:5)
Reading:
Q: How to debug production issues?
A:
1. Check monitoring/logs:
2. Recent changes:
3. Compare with working state:
4. Reproduce in staging:
5. Emergency rollback if critical:
Never:
Q: What is HTTP?
A: HyperText Transfer Protocol - Application protocol for web communication.
Characteristics:
Q: What happens when you type URL in browser?
A:
1. DNS Lookup:
2. TCP Connection:
3. HTTP Request:
4. Server Processing:
5. HTTP Response:
6. Rendering:
Q: What is TCP vs UDP?
A:
TCP (Transmission Control Protocol):
UDP (User Datagram Protocol):
Q: What is the OSI model?
A: Conceptual model with 7 layers describing network communication.
Layers (top to bottom):
Simplified (TCP/IP model):
Q: What is DNS?
A: Domain Name System - Phone book of the internet.
Function:
google.com → 142.250.185.46Process:
Record types:
Q: What is a reverse proxy?
A: Server sitting between clients and backend servers.
Functions:
Example: Nginx, Apache
vs Forward proxy:
Q: What is WebSocket?
A: Protocol for full-duplex communication over single TCP connection.
HTTP:
WebSocket:
Use cases:
Handshake:
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Q: What is latency vs throughput vs bandwidth?
A:
Latency:
Throughput:
Bandwidth:
Analogy:
Q: When would you use each data structure?
A:
Array:
Linked List:
Stack:
Queue:
Hash Map:
Set:
Tree (Binary Search Tree):
Graph:
Heap:
Q: What are time complexities you should know?
A:
Common complexities:
Q: What is the difference between depth-first search (DFS) and breadth-first search (BFS)?
A:
DFS:
BFS:
Example tree:
1
/ \
2 3
/ \
4 5
Q: What is a design pattern?
A: Reusable solution to commonly occurring problem in software design.
Categories:
Q: What is Singleton pattern?
A: Ensures class has only one instance with global access point.
Use cases:
Example:
class Database:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
# Initialize connection
return cls._instance
# Same instance always
db1 = Database()
db2 = Database()
assert db1 is db2 # True
Caution:
Q: What is Factory pattern?
A: Delegates object creation to a factory method.
Example:
class ShapeFactory:
def create_shape(self, shape_type):
if shape_type == "circle":
return Circle()
elif shape_type == "square":
return Square()
factory = ShapeFactory()
shape = factory.create_shape("circle")
Benefits:
Q: What is Adapter pattern?
A: Allows incompatible interfaces to work together.
Use case: Using third-party library with different interface
Example:
# Old interface
class OldSystem:
def old_method(self):
return "Old"
# New interface expected
class NewInterface:
def new_method(self):
pass
# Adapter
class Adapter(NewInterface):
def __init__(self, old_system):
self.old_system = old_system
def new_method(self):
return self.old_system.old_method()
Q: What is Decorator pattern?
A: Adds functionality to objects without modifying them.
Example:
# Python has built-in decorator syntax
def log_execution(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
result = func(*args, **kwargs)
print(f"Finished {func.__name__}")
return result
return wrapper
@log_execution
def process_data(data):
return data.upper()
Q: What is Observer pattern?
A: Objects subscribe to events and get notified of changes.
Use cases:
Example:
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def notify(self, data):
for observer in self._observers:
observer.update(data)
class Observer:
def update(self, data):
print(f"Received: {data}")
subject = Subject()
observer1 = Observer()
subject.attach(observer1)
subject.notify("Event occurred!")
Q: What is Strategy pattern?
A: Define family of algorithms, make them interchangeable.
Example:
class PaymentStrategy:
def pay(self, amount):
pass
class CreditCard(PaymentStrategy):
def pay(self, amount):
print(f"Paid {amount} with credit card")
class PayPal(PaymentStrategy):
def pay(self, amount):
print(f"Paid {amount} with PayPal")
class ShoppingCart:
def __init__(self, payment_strategy):
self.payment_strategy = payment_strategy
def checkout(self, amount):
self.payment_strategy.pay(amount)
cart = ShoppingCart(CreditCard())
cart.checkout(100)
Benefits:
Q: What is the difference between concurrency and parallelism?
A:
Concurrency:
Parallelism:
Q: What is a race condition?
A: When multiple threads/processes access shared data and outcome depends on timing.
Example:
# Two threads increment counter
counter = 0
def increment():
global counter
temp = counter
# Context switch can happen here!
counter = temp + 1
# Thread 1 and Thread 2 both increment
# Expected: counter = 2
# Actual: counter = 1 (race condition!)
Solution:
Q: What is a deadlock?
A: Two or more processes waiting for each other to release resources.
Example:
Process A: Holds Lock1, wants Lock2
Process B: Holds Lock2, wants Lock1
Both wait forever!
Conditions for deadlock:
Prevention:
Q: What is a mutex vs semaphore?
A:
Mutex (Mutual Exclusion):
Semaphore:
Example:
# Mutex
from threading import Lock
mutex = Lock()
mutex.acquire()
# Critical section
mutex.release()
# Semaphore (e.g., connection pool with 5 connections)
from threading import Semaphore
semaphore = Semaphore(5)
semaphore.acquire()
# Use resource
semaphore.release()
Q: What is thread vs process?
A:
Process:
Thread:
When to use:
Q: What is asynchronous programming?
A: Non-blocking execution where program continues while waiting for operations.
Synchronous:
result1 = api_call_1() # Wait 1s
result2 = api_call_2() # Wait 1s
# Total: 2s
Asynchronous:
future1 = api_call_1() # Start
future2 = api_call_2() # Start
result1 = await future1 # Wait
result2 = await future2 # Wait
# Total: 1s (parallel)
Use cases:
Q: What is HTTP/2 vs HTTP/1.1?
A:
HTTP/1.1:
HTTP/2:
Benefits:
Q: What are cookies vs sessions vs tokens?
A:
Cookies:
Sessions:
Tokens (JWT):
Q: What is SSL/TLS?
A: Cryptographic protocols providing secure communication.
SSL (Secure Sockets Layer): Deprecated
TLS (Transport Layer Security): Modern version
Handshake process:
Certificate:
Q: What is AJAX?
A: Asynchronous JavaScript and XML - Update page without reload.
Traditional:
Click link → Full page reload
AJAX:
fetch('/api/data')
.then(response => response.json())
.then(data => {
// Update page dynamically
});
Benefits:
Q: What is JSONP?
A: JSON with Padding - Workaround for CORS before CORS existed.
How it works:
function handleData(data) {
console.log(data);
}
Modern approach: Use CORS headers instead
Q: How would you design a URL shortener (like bit.ly)?
A:
Requirements:
Design:
Database:
urls table:
- id (primary key)
- original_url
- short_code (unique)
- created_at
- clicks
analytics table:
- short_code
- clicked_at
- ip_address
- user_agent
Generate short code:
import hashlib
def shorten(url):
# Hash URL
hash = hashlib.md5(url.encode()).hexdigest()
# Take first 7 characters
short_code = hash[:7]
# Check if exists, regenerate if collision
return short_code
API endpoints:
POST /shorten
{
"url": "https://example.com/very/long/url"
}
Response: { "short_url": "https://short.ly/abc123" }
GET /:short_code
→ Redirect to original URL
Scaling considerations:
Q: How would you design a rate limiter?
A:
Requirements:
Approaches:
1. Token Bucket:
class RateLimiter:
def __init__(self, capacity, refill_rate):
self.capacity = capacity
self.tokens = capacity
self.refill_rate = refill_rate # tokens per second
self.last_refill = time.time()
def allow_request(self):
self._refill()
if self.tokens >= 1:
self.tokens -= 1
return True
return False
def _refill(self):
now = time.time()
elapsed = now - self.last_refill
tokens_to_add = elapsed * self.refill_rate
self.tokens = min(self.capacity, self.tokens + tokens_to_add)
self.last_refill = now
2. Redis-based (Sliding Window):
def is_allowed(user_id, limit=100, window=60):
key = f"rate_limit:{user_id}"
now = time.time()
# Remove old entries
redis.zremrangebyscore(key, 0, now - window)
# Count requests in window
count = redis.zcard(key)
if count < limit:
redis.zadd(key, {now: now})
redis.expire(key, window)
return True
return False
Storage:
Q: How would you handle file uploads in a web application?
A:
Small files (<10MB):
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
# Validate
if not allowed_file(file.filename):
return error('Invalid file type')
# Generate unique filename
filename = secure_filename(file.filename)
unique_name = f"{uuid.uuid4()}_{filename}"
# Save
file.save(os.path.join(UPLOAD_FOLDER, unique_name))
return {'url': f'/uploads/{unique_name}'}
Large files:
Security:
Q: Application is slow in production but fast in development. How do you debug?
A:
Steps:
Check metrics:
Enable profiling:
import cProfile
profiler = cProfile.Profile()
profiler.enable()
# ... code ...
profiler.disable()
profiler.print_stats()
Check logs:
Common culprits:
Tools:
Q: How do you debug a memory leak?
A:
Steps:
Monitor memory usage:
Heap dump analysis:
import tracemalloc
tracemalloc.start()
# ... run code ...
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:10]:
print(stat)
Common causes:
Tools:
Q: Database query is slow. How do you optimize it?
A:
Process:
EXPLAIN the query:
EXPLAIN ANALYZE
SELECT * FROM users WHERE email = 'test@example.com';
Check for:
Add indexes:
CREATE INDEX idx_users_email ON users(email);
Optimize query:
Other improvements:
Q: How do you handle database migration with zero downtime?
A:
Strategy:
Backward compatible changes first:
-- ✅ GOOD: Add column (nullable or with default)
ALTER TABLE users ADD COLUMN phone VARCHAR(15) DEFAULT NULL;
-- ❌ BAD: Remove column immediately
ALTER TABLE users DROP COLUMN old_field;
Deployment steps for column rename:
Phase 1: Add new column
ALTER TABLE users ADD COLUMN full_name VARCHAR(255);
Phase 2: Dual writes (app writes to both)
user.name = name
user.full_name = name # Write to both
Phase 3: Backfill data
UPDATE users SET full_name = name WHERE full_name IS NULL;
Phase 4: Switch reads to new column
return user.full_name # Read from new column
Phase 5: Remove old column
ALTER TABLE users DROP COLUMN name;
General principles:
Q: Tell me about a time you solved a challenging technical problem.
A: Use STAR method:
Situation: Describe context
Task: Your responsibility
Action: What you did
Result: Outcome with metrics
Q: How do you approach learning a new technology/framework?
A:
Process:
Understand the why:
Official documentation:
Hands-on practice:
Read source code:
Community:
Example:
"When learning Docker, I started with official docs, built a simple containerized Node.js app, then containerized my existing projects. I read Dockerfiles from popular projects to understand best practices."
Q: Describe a time when you had to make a trade-off between technical debt and delivering features quickly.
A:
Good answer structure:
Example:
"We needed to launch a feature for a product demo in 2 days. Proper implementation needed authentication refactor (1 week). I built a working prototype with hardcoded values documented as TODO. After demo, I created ticket, got it prioritized, and implemented properly in next sprint."
Q: Tell me about a time you had a disagreement with a team member.
A:
Structure:
Example:
"Teammate wanted MongoDB for new feature; I suggested PostgreSQL. We discussed:
Q: How do you handle code review feedback?
A:
Good practices:
Don't take it personally:
Ask clarifying questions:
Be open to learning:
Discuss respectfully:
Document learnings:
Example:
"Reviewer suggested using a HashMap instead of my nested loops. I asked why, learned about time complexity improvement, updated code, and documented the pattern for future reference."
Q: Walk me through a project you're proud of.
A:
Structure:
Project overview:
Your role:
Challenges faced:
Results:
Future improvements:
Example template:
"I built a real-time chat application using Node.js and Socket.io that supports 1000+ concurrent users. I implemented:
Challenge was handling reconnections without message loss. Implemented message queuing with acknowledgments.
Result: 99.9% message delivery, < 100ms latency, used by 500+ students in my college."
Q: How do you ensure code quality in your projects?
A:
Practices:
Code reviews:
Testing:
Linting & formatting:
Static analysis:
Documentation:
CI/CD:
Q: What do you do when you're stuck on a problem?
A:
Approach:
Debug systematically (15-30 min):
Research (30 min):
Simplify (15 min):
Rubber duck debugging:
Ask for help:
Important: Document solution for future reference!
Q: How do you stay updated with technology trends?
A:
Methods:
Reading:
Practice:
Community:
Courses:
Newsletters:
Balance: Learn what's relevant to work/interests, don't chase every new framework.
Q: Tell me about a time you failed.
A:
Structure:
Example:
"In my first project, I didn't set up proper error handling. When the database went down, the entire app crashed with no logging. I learned the importance of:
Now I always implement proper error handling from day one and set up monitoring alerts."
Q: How do you handle tight deadlines?
A:
Approach:
Clarify requirements:
Break down tasks:
Prioritize:
Communicate:
Time management:
Quality:
Example:
"When we had 3 days for a 1-week feature, I identified core functionality (user can upload and view files), postponed nice-to-haves (batch upload, file preview), communicated timeline, and delivered core feature with 90% test coverage. Added remaining features in next sprint."
Q: Why do you want to work at this company?
A:
Structure:
Company mission alignment:
Technical interest:
Growth opportunity:
Culture:
Make it personal: Connect to your experience or interests.
Q: Why should we hire you?
A:
Highlight:
Technical skills:
Relevant projects:
Learning ability:
Passion:
Cultural fit:
Q: Where do you see yourself in 3-5 years?
A:
Good answer:
Growth trajectory:
Technical mastery:
Impact:
Company alignment:
Avoid:
Q: What questions do you have for us? (Always ask questions!)
A:
Good questions:
About the role:
About team/mentorship:
About growth:
About company:
About evaluation:
Avoid:
Technical:
Projects:
Behavioral:
Coding Round:
System Design:
General:
Remember: Companies value passion for learning, problem-solving ability, and cultural fit as much as technical skills. Show them you're eager to learn and contribute!
Good luck! 🚀