✅ ROUND 1 – Detailed Answers
1. Explain how the Node.js Event Loop works.
Answer:
Node.js is single-threaded, but it can handle asynchronous and non-blocking operations using the event loop, which is managed internally by libuv. The event loop continuously monitors the call stack and the callback queues.
When the call stack becomes empty, the event loop picks the next callback from the appropriate queue and pushes it onto the call stack for execution. This mechanism enables Node.js to handle I/O operations, timers, and network requests without blocking the main thread.
The event loop runs in six phases, executed in a fixed order:
-
Timers Phase
Executes callbacks fromsetTimeout()andsetInterval()whose timers have expired. -
Pending Callbacks Phase
Executes certain system-level callbacks, such as errors from TCP operations. -
Idle / Prepare Phase
Internal phase used by libuv for preparing the poll phase. Developers don’t interact with this phase directly. -
Poll Phase
One of the most important phases.-
Retrieves new I/O events.
-
Executes callbacks for completed I/O operations.
-
If no pending I/O and no timers, it will wait for incoming events.
-
-
Check Phase
Executes callbacks scheduled bysetImmediate(). -
Close Callbacks Phase
Executes close events like:
This cycle repeats continuously, enabling Node.js to remain non-blocking and efficient even with a single thread.
2. What is the difference between require and import in Node.js?
Answer:
require and import are two different module systems in Node.js.
require (CommonJS Module System)
-
Used in older versions of Node.js.
-
Synchronous loading.
-
Uses
module.exportsandexports. -
Works out of the box without any configuration.
Example:
import (ES Module System)
-
Introduced in ES6.
-
Asynchronous and more optimized for modern applications.
-
Uses
exportkeyword to expose functionality. -
Requires enabling
"type": "module"inpackage.jsonor using.mjsextension. -
Supports tree-shaking and works like modern JavaScript in frontend.
Example:
Summary Table
| Feature | require (CJS) | import (ESM) |
|---|---|---|
| Module type | CommonJS | ES Modules |
| Loading | Synchronous | Asynchronous |
| Exports | module.exports | export |
| Default support | Yes | Only in ESM mode |
| Tree shaking | No | Yes |
3. How does Express middleware work? Give an example.
Answer:
Middleware in Express is a function that runs between the request and response cycle. It has access to:
-
req(request object) -
res(response object) -
next()(function to pass control to the next middleware)
Use cases of middleware:
-
Authentication
-
Logging
-
Validation
-
Parsing request body
-
Error handling
-
Rate limiting
Normal Middleware Example
Error-Handling Middleware Example
Error middleware is special because it has 4 parameters: (err, req, res, next).
How middleware works internally:
-
Express receives request.
-
Checks middleware stack (ordered list).
-
Executes each middleware in sequence.
-
If a middleware does not call
next(), the request will hang. -
If
next(err)is called, Express skips normal middleware and goes to error-handling middleware.
4. How do you handle errors in async/await functions in Node.js and Express?
Answer:
In Node.js, when using async/await, errors can be handled using a try–catch block. However, in Express applications, we normally handle errors using a centralized error-handling middleware so the code stays clean and easy to maintain.
A. Basic try–catch Error Handling
B. Error Handling in Express Routes
C. Centralized Express Error-Handling Middleware
This middleware catches all errors from the entire app.
Why this is important?
-
Avoids repeating try-catch everywhere
-
Provides consistent error response
-
Helps in debugging
-
Makes production logs cleaner
5. How does JWT authentication work? Explain the complete flow.
Answer:
JWT (JSON Web Token) authentication is a stateless authentication mechanism used widely in backend APIs.
Complete Flow:
Step 1: User Login
-
User sends email & password to
/login. -
Backend verifies credentials with database.
Step 2: Server Generates JWT
If credentials are valid:
Token has 3 parts:
-
Header
-
Payload (user info)
-
Signature (important for security)
Step 3: Send Token to Client
Server returns token:
Step 4: Client Stores Token
Client stores token in:
-
LocalStorage / SecureStorage (mobile apps)
-
HTTP-only cookies (web)
Step 5: Client Sends Token with Every Request
Client adds token in Authorization Header:
Step 6: Server Verifies Token
Middleware validates token:
Step 7: Protected Routes
Only authenticated users can access certain endpoints.
6. What is the difference between process.nextTick() and setImmediate()?
Answer:
Both are used to schedule callbacks, but they run in different phases of the event loop.
process.nextTick()
-
Runs before the event loop continues.
-
Higher priority (executes immediately after current operation).
-
Used for microtasks.
-
Can cause event loop delay if overused.
setImmediate()
-
Executes callback in the check phase.
-
Runs after I/O events are processed.
-
Better for heavy tasks that should not block the loop.
Summary Table
| Feature | process.nextTick() | setImmediate() |
|---|---|---|
| Priority | Very High | Normal |
| Executes In | Before next event loop tick | Check phase |
| Use Case | Quick microtasks | IO-related tasks |
| Risk | Can block loop | No risk |
7. What is the role of libuv in Node.js?
Answer:
libuv is a C library that provides Node.js its asynchronous, non-blocking I/O capabilities. It acts as the backbone of Node.js's concurrency model.
Responsibilities of libuv:
-
Event Loop Management
Runs the event loop and manages all phases. -
Thread Pool Management
Used for:-
File system operations
-
DNS lookups
-
Crypto operations
-
Compression
-
-
Cross-platform Abstraction
Allows Node.js to run consistently on Windows, macOS, and Linux. -
Async I/O Handling
Manages:-
TCP
-
UDP
-
Pipes
-
File I/O
-
Why libuv is important?
Without libuv, Node.js would not be asynchronous. It allows Node.js to handle thousands of simultaneous connections efficiently.
8. How does clustering work in Node.js? Why do we use it?
Answer:
By default, Node.js runs on a single thread, even if your machine has 4, 8, or 16 CPU cores.
This limits performance for CPU-intensive applications.
To fix this, Node.js provides the cluster module.
How Clustering Works
-
The master process creates multiple worker processes.
-
Each worker runs a copy of your Node.js application.
-
All workers share the same server port.
-
The OS load-balances incoming requests between workers.
Example:
Benefits of Clustering
-
Uses all CPU cores → better performance.
-
Increases throughput under load.
-
Improves reliability (if one worker crashes, master replaces it).
Why Use Clustering?
-
Node.js by default uses only 1 core.
-
Production environments (like PM2) enable clustering for scalability.
✅ ROUND 2 – Detailed Answers (With Examples)
1. Difference Between Synchronous and Asynchronous Programming in Node.js
In Node.js, synchronous programming means that each operation is executed one after another; a task must finish before the next can begin. If a synchronous operation takes time (like reading a large file), it blocks the entire thread and prevents the server from handling other requests. For example:
This blocks the event loop until the file is fully read.
On the other hand, asynchronous programming allows operations to execute in the background while Node.js continues running other code. Node.js uses callbacks, promises, or async/await to handle asynchronous tasks. For example:
This allows the event loop to continue serving requests while the file is being read.
In backend applications, asynchronous programming is preferred because it enables Node.js to remain non-blocking and handle thousands of concurrent connections efficiently.
2. How the Node.js Thread Pool Works & Tasks That Use It
Node.js itself is single-threaded, but it uses libuv’s thread pool to handle operations that cannot be performed asynchronously at the OS level. The thread pool consists of 4 threads by default, although this can be increased.
Tasks executed in the thread pool include:
-
File system operations (
fs.readFile,fs.writeFile) -
Crypto-intensive tasks (
crypto.pbkdf2,scrypt) -
DNS operations (except DNS.lookup)
-
Compression (
zlib.gzip,deflate) -
Some network operations on Windows
Example:
This hash computation runs on a background thread, preventing the event loop from being blocked.
3. What Are Streams in Node.js? Types & Use Cases
Streams are objects in Node.js that allow reading or writing data sequentially instead of loading it completely into memory. This makes them ideal for large data processing.
Types of Streams:
-
Readable Stream – e.g., reading a file
-
Writable Stream – e.g., writing a log file
-
Duplex Stream – read + write, e.g., TCP sockets
-
Transform Stream – modify data while streaming, e.g., compression
Example of using a stream to read a file:
Use cases include file uploads, video streaming, compression, and real-time data processing.
4. What Is CORS in Express and How Does It Work?
CORS (Cross-Origin Resource Sharing) is a mechanism that allows browsers to permit or block requests made from one domain to another. By default, browsers restrict cross-origin requests for security reasons.
When a frontend (e.g., example.com) tries to call an API (api.example.org), the browser sends a preflight request (OPTIONS). The server needs to respond with headers like:
In Express, enabling CORS is simple:
Internally, Express sets the appropriate HTTP headers so browsers allow the request. Without proper CORS configuration, the browser blocks the call even if the server is running correctly.
5. Difference Between PUT and PATCH (With Examples)
Both PUT and PATCH update data, but they differ in purpose:
PUT
-
Replaces the entire resource
-
Requires full object
Example:
If the user previously had more fields, they may be overwritten.
PATCH
-
Updates only specific fields
-
More efficient for partial updates
Example:
PATCH is preferred in modern REST APIs because it avoids unnecessary data transfer and reduces risk of overwriting data.
6. What Is Rate Limiting and Why It Matters?
Rate limiting restricts how many requests a user or client can make within a certain time frame. It prevents:
-
DDoS attacks
-
API abuse
-
Excessive load on servers
-
Unlimited retry loops
Example using express-rate-limit:
This allows 100 requests per minute per IP.
Rate limiting is essential for API security and maintaining server performance.
7. How MongoDB Indexing Works & When It Can Slow Performance
Indexes in MongoDB work like indexes in a book. Instead of scanning the entire collection, MongoDB uses the index to jump directly to the desired document.
Example:
This speeds up queries like:
However, indexes can slow down write operations because MongoDB must update the index every time a document is inserted, updated, or deleted.
Indexes are great for read-heavy applications but may degrade performance in write-heavy systems if overused.
8. What Is the EventEmitter in Node.js?
EventEmitter is a core Node.js class that provides a way to publish and subscribe to events. Many built-in modules use it internally.
Example:
Modules that use EventEmitter:
-
HTTP server (
req,res) -
Streams
-
Sockets
-
Process module
-
FS watchers
EventEmitter helps create decoupled and event-driven systems.
9. Difference Between Passport.js and JWT Authentication
JWT
-
Stateless (no session storage)
-
Token stored on client
-
Ideal for REST APIs
-
Easy to scale horizontally
Passport.js
-
Middleware-based authentication framework
-
Supports strategies like:
-
Local (email/password)
-
OAuth (Google, Facebook)
-
LDAP
-
-
Uses sessions by default (stateful)
Passport.js is useful for traditional web apps, while JWT is better for modern APIs and mobile applications.
10. How Load Balancing Works for Node.js Apps
Load balancing distributes incoming requests across multiple Node.js instances to improve performance and reliability.
Common strategies:
-
Round Robin (most common)
-
Least Connections
-
IP Hash
In Node.js deployments, load balancing is often done using:
-
NGINX
-
HAProxy
-
Cloud Load Balancers (AWS, Azure, GCP)
-
PM2 clustering
Example with PM2 clustering:
This starts multiple worker processes to utilize all CPU cores.
Load balancing ensures no single instance becomes overloaded, improving performance and uptime.
🔥 ROUND 3 – Advanced Backend + System Design Interview Questions
1. How would you design a scalable file-upload service (like Google Drive) using Node.js?
A scalable file upload service must handle large files, parallel uploads, failures, and distributed storage.
Architecture
-
Client uploads in chunks (5–10 MB)
-
Split large files into chunks.
-
Upload each chunk independently → parallel & resumable.
-
-
Node.js Upload Server
-
Use
multer,busboy, orstreamAPI to handle uploads. -
Node.js should not buffer entire file in memory → use streams.
-
-
Temporary Storage
-
Upload chunks to:
-
AWS S3
-
Google Cloud Storage
-
Local disk (not recommended for production)
-
-
-
Database (MongoDB or PostgreSQL)
Store:-
File ID
-
Chunk numbers
-
Upload completion state
-
Metadata (owner, size, timestamps)
-
-
Chunk Merging
When all chunks are uploaded:-
A background worker (Bull / RabbitMQ) merges chunks into final file.
-
-
Security
-
JWT authentication
-
File type validation
-
Antivirus scanning
-
Signed URLs for download
-
Example Flow
-
User selects 1 GB file
-
File splits into 200 chunks (5 MB each)
-
Client uploads chunks:
/upload/:fileId/:chunkNumber -
Server stores chunks in S3
-
When all chunks arrive → worker merges them
-
Final file becomes downloadable from S3
2. Horizontal Scaling vs Vertical Scaling in Node.js
Vertical Scaling
→ Increasing server capacity
-
More RAM
-
More CPU
-
Faster SSD
Pros: simple
Cons: limited maximum capacity
Horizontal Scaling
→ Adding more Node.js servers
-
Behind a load balancer (NGINX, AWS ELB
-
Use Node.js clusters (multiple processes)
Pros: high availability
Cons: requires stateless apps & shared storage
Example
If your Node.js app is overloaded:
-
Vertical scaling: upgrade from 2 vCPUs → 8 vCPUs
-
Horizontal scaling: run 4 Node.js instances and load balance
3. Explain Database Transactions in MongoDB
MongoDB supports ACID transactions since version 4.x.
How they work
-
Multi-document transactions require replica set or sharded cluster.
-
All operations inside a transaction either commit or abort.
Example
Use cases:
-
Financial payments
-
Multi-step write operations
-
Inventory management
4. What is Redis? How do you use it in Node.js?
Redis is an in-memory data store used for:
-
Caching
-
Rate limiting
-
Pub/Sub
-
Queues
Caching Strategy
Store frequently accessed data:
Eviction Policies
-
LRU – Least recently used
-
LFU – Least frequently used
-
TTL – Auto expiry
Node.js Example
5. Design a rate-limited API Gateway (Node.js + Redis)
Goal: Limit each user to X requests per minute.
Architecture
-
Client → API Gateway (Express)
-
API Gateway checks Redis
-
If request count > limit → block
-
Otherwise → increment counter and allow
Example Algorithm (Token Bucket / Fixed Window)
Express Example
6. What is Message Queueing? How do RabbitMQ / Kafka help?
Message queues decouple services by asynchronous communication.
Benefits
-
Handles heavy load
-
Prevents downtime
-
Ensures reliable delivery
-
Enables microservices communication
Use case example
User uploads a video → API triggers “video processing job”
-
API sends message to queue
-
Worker reads message & processes video
RabbitMQ
Good for task queues, job processing
Kafka
Good for event streaming, real-time analytics
7. Designing a Background Job System in Node.js
Use libraries:
-
Bull (Redis-based)
-
Agenda (MongoDB-based)
-
Bree
Why background jobs?
-
Email sending
-
File processing
-
Notification scheduling
-
Data exports
Example using Bull
8. Securing an Express API in production
Steps
-
HTTPS using NGINX or Cloudflare
-
Helmet.js for secure headers
-
Rate limiting
-
Input validation using Joi / Zod
-
JWT authentication with rotation
-
CORS configuration
-
Avoid eval & insecure regex
-
Environment variables using dotenv
-
Database sanitization
-
Disable X-Powered-By header
Example
9. What is Data Modeling? Design schema for a Social Media Post + Comments
Post Schema
Comment Schema
Why separate models?
-
Efficient indexing
-
Fetch post separately
-
Scalable for millions of comments
Query Example
Get post + comments:
10. Debugging Performance Issues in Node.js
Tools
-
clinic.js
-
Chrome DevTools debugger
-
Node Inspector
-
Memory snapshots
-
CPU profiling
-
PM2 monitoring
-
Winston logs
Steps
-
Detect event loop blocking (
clinic flame) -
Check long-running sync operations
-
Analyze heap memory leaks
-
Check DB slow queries
-
Add logs for response-time profiling
Example Issue
If an API is slow because of a synchronous loop:
Solution: offload to worker threads.
11. What is CAP theorem? How does it apply to MongoDB?
CAP = Consistency, Availability, Partition Tolerance
Distributed systems can only guarantee two at a time.
MongoDB (in Replica Sets)
-
Prioritizes Availability + Partition Tolerance
-
Sacrifices Consistency (reads may be stale)
You can tune it using:
-
writeConcern -
readConcern
12. What is CQRS and Event Sourcing?
CQRS = Command Query Responsibility Segregation
-
Separate models for read and write operations.
-
Reads become faster and scalable.
Event Sourcing
-
Every change is stored as an event (not as final state).
-
System state = replay of events.
Example
Instead of storing:
We store events:
Final balance = sum of events.
13. How do you handle long-running tasks in Node.js without blocking the event loop?
Use:
-
Worker Threads
-
Message Queues
-
Background jobs
-
Offloading CPU-heavy tasks to separate services
Example: CPU-heavy hashing
Replace:
With:
14. What are WebSockets? How to design real-time chat?
WebSockets provide bi-directional communication.
Architecture
-
Client connects:
ws://server.com -
Server stores user socket ID
-
On message → broadcast to recipients
-
Save messages in DB for persistence
Example
Using Socket.IO:
15. How do you break a monolithic Node.js app into microservices?
Steps
-
Identify boundaries (Auth, Orders, Payments)
-
Create separate codebases
-
Each service has:
-
Its own DB
-
Its own deployment
-
Its own scaling
-
-
Use API Gateway for routing
-
Services communicate via:
-
REST
-
gRPC
-
Message Queues (Kafka/RabbitMQ)
-
Challenges
-
Network latency
-
Data consistency
-
Distributed logging
-
Distributed transactions
-
Versioning APIs
🔥 ROUND 4 – SYSTEM DESIGN + ARCHITECTURE + DEVOPS QUESTIONS
This document contains interview-grade, detailed answers to the Round 4 questions you requested, tailored to a 2–3 year Node.js backend developer. Each question includes: a clear explanation, practical examples, and architecture diagrams (Mermaid) where appropriate.
1. Design a URL Shortener (like Bitly)
Overview A URL shortener maps a long URL to a short code and redirects traffic to the original URL. Key elements: short-code generation, storage, redirect performance, analytics, and scaling.
Components
API layer (Node.js + Express)
Database (Postgres / MySQL / Redis for hot cache)
Unique ID generator (base62 encoding, hash, or snowflake)
Cache (Redis)
Analytics pipeline (event queue + data store)
Schema (SQL)
Short code generation
Option A: Base62 encoding of an auto-increment ID (simple, collision-free). Example:
encodeBase62(id).Option B: Hash (MD5/SHA + truncate) — requires collision handling.
Option C: NanoID/Snowflake — distributed ID.
Redirect Flow
Client requests
GET /:short_code.App checks Redis cache for
short_code→ if present, return long URL (HTTP 301). Otherwise, query DB and populate cache.Increment click counter asynchronously (send event to queue to update analytics).
Scaling & Availability
Use Redis as a read-through cache for hot keys.
Use multiple app instances behind a load balancer.
Use read replicas for analytics queries.
Shard DB if write throughput is huge.
Mermaid diagram
2. Notification Service (email, SMS, push) for millions
Requirements & Constraints
High throughput & reliability
Multiple channels with differing SLAs (email slower, push faster)
Retry & backoff
Personalization & templates
Opt-out & compliance (CAN-SPAM, GDPR)
Architecture
API Gateway (auth & throttling)
Ingestion service (Node.js) → validates + enqueues messages
Message Queue (Kafka / RabbitMQ / SQS) for durability
Worker fleet (autoscaled) for each channel (email, SMS, push)
Third-party providers (SES, Twilio, FCM) as downstream
Dedup & idempotency logic
Monitoring & DLQ (dead-letter queues)
Example flow
App enqueues message to Kafka topic
notifications.email.Consumer picks up message, renders template, calls SES.
On failure, retry with exponential backoff; after N attempts, move to DLQ.
Mermaid diagram
3. API Gateway vs Reverse Proxy
API Gateway
Higher-level features: routing, authentication, rate-limiting, API composition, request/response transformation, versioning, metrics, circuit breaking.
Examples: Kong, AWS API Gateway, Tyk, Apigee.
Reverse Proxy
Lower-level: simple HTTP proxy for load balancing and TLS offloading.
Examples: NGINX, HAProxy.
Key differences
API Gateway = application-aware (auth, routing rules, policies). Reverse proxy = transport-level (proxying & LB).
Use both: NGINX as edge TLS terminator + API Gateway for app logic.
Mermaid diagram
4. Secrets & Environment Variables in Production
Principles
Never check secrets into source control. Use least-privilege access. Rotate secrets regularly.
Solutions
Secrets Manager: AWS Secrets Manager, Azure Key Vault, HashiCorp Vault.
Container secrets: Kubernetes Secrets (backed by KMS), Docker secrets.
CI/CD secrets handling: store encrypted vars in pipeline provider (GitHub Actions secrets, GitLab CI variables).
Example
At runtime, app queries Vault using a short-lived token (via IAM role or Kubernetes service account) and retrieves DB credentials.
Mermaid diagram
5. CI/CD — Tools & How Pipelines Work
CI/CD Concepts
CI (Continuous Integration): run tests & builds on each commit.
CD (Continuous Delivery/Deployment): automate deployment to environments.
Common Tools
GitHub Actions, GitLab CI, Jenkins, CircleCI, Travis CI, Bitbucket Pipelines.
Container registries: Docker Hub, ECR.
CD tools: ArgoCD, Flux, Spinnaker.
Pipeline Example (GitHub Actions)
on: push→ install deps → run tests → build artifact → publish Docker image to ECR.deployjob triggered → update Kubernetes manifests → apply to cluster (kubectl / ArgoCD).
Mermaid diagram
6. Docker: Images, Containers, Volumes, Networks
Docker basics
Image: immutable filesystem snapshot (built from Dockerfile).
Container: runtime instance of an image.
Volumes: persist data outside container lifecycle.
Networks: connect containers.
Why Docker matters
Reproducible environments, faster onboarding, easier CI builds, consistent runtimes across environments.
Example
7. Deploy Node.js on AWS (EC2 / ECS / Elastic Beanstalk)
EC2 (manual)
Provision EC2 instance(s)
Install Node, PM2
Deploy artifacts (SCP/CI)
Use NGINX as reverse proxy
Use Auto Scaling Groups and Load Balancer
ECS (containerized)
Build Docker image → push to ECR
Define Task Definition & Service
Use ALB for load balancing
Auto scale based on CPU/memory
Elastic Beanstalk (PaaS)
Deploy app bundle → Beanstalk handles infra
Easy but less control
Mermaid diagram (ECS)
8. Load Balancing Strategies
Round Robin
Distributes requests sequentially across all servers.
Least Connections
Sends requests to server with fewest active connections.
IP Hash
Uses client IP to consistently route to the same backend.
When to use
Round robin: general purpose
Least connections: uneven request durations
IP hash: sticky sessions without a session store
9. Monitoring Node.js in Production
Key signals
Logs (structured JSON) — Winston, Bunyan
Metrics — Prometheus + Grafana (latency, request rate, error rate)
Traces — Jaeger / OpenTelemetry
APM — NewRelic, DataDog
Health checks & alerting (uptime)
Practical setup
Expose
/healthzand/metricsExport metrics via
prom-clientCentralized log storage (ELK / EFK / CloudWatch)
10. CDN and Performance
CDN purpose
Serve static assets from edge locations close to users.
Reduce latency and origin load.
Use cases
Images, JS/CSS, downloads, video streaming (with signed URLs).
Providers
CloudFront, Fastly, Cloudflare, Akamai.
11. Database Sharding
Sharding
Horizontal partitioning of data across multiple nodes.
When to shard
Data size exceeds single-node capacity
Write throughput limits
MongoDB
Use shard key with even distribution
Consider chunk migrations and balancing
Postgres
Use Citus or custom hash-based sharding
12. Analytics System for Millions of Events
Requirements
High ingest rate, durable, low cost, near real-time processing
Pipeline
Client → Event collector (stateless Node.js) → Kafka (or Kinesis)
Stream processors (Flink / Spark Streaming / Kafka Streams)
Storage: hot store (Elasticsearch / ClickHouse) + cold store (S3 / Parquet)
Dashboard & aggregation
Mermaid diagram
13. API Rate Limiter vs Throttling
Rate limiting
Caps number of requests allowed per client in a time window (e.g., 100/min).
Throttling
Slows down the request processing rate (e.g., delay or queue) rather than rejecting.
Use both
Use rate-limiter to prevent abuse; throttling to smooth bursts.
14. Multi-tenant SaaS: Shared DB vs Separate DB
Shared DB (schema per tenant or single schema)
Pros: cheaper, easier to manage
Cons: noisy neighbor, harder isolation
Separate DB per tenant
Pros: strong isolation, easy backup/restore per tenant
Cons: operational overhead, scaling many DBs
Hybrid
Small tenants in shared DB, large tenants on dedicated DBs
15. Zero-downtime Deployment
Strategies
Blue/Green deploys (switch traffic after verification)
Rolling updates with health checks
Use of readiness and liveness probes in Kubernetes
Practical steps (K8s)
Deploy new ReplicaSet with new image
Wait for readiness; then gradually scale down old RS
Use readinessProbe to avoid sending traffic to not-ready pods
16. Secure API Keys & Secrets in CI/CD
Approach
Store secrets in pipeline secret store (encrypted). Use Vault or cloud KMS.
Never echo secrets in logs. Use masked variables.
Use ephemeral credentials (short-lived tokens via IAM roles).
17. Blue-Green vs Rolling Deployment
Blue-Green
Two environments (blue = current, green = new). Switch router/traffic after validation.
Pros: instant rollback.
Rolling
Replace instances gradually. Fewer resources but slower rollback.
18. Idempotency in APIs
Definition
An idempotent operation can be applied multiple times without changing the result beyond the initial application.
Idempotent HTTP methods
GET, PUT, DELETE are idempotent. POST is not by default.
Idempotency keys
For POSTs that create resources, use idempotency-key header to ensure single side-effe
