InterviewTreedInterviewTreed

InterviewTreed Question Bank

System Design & Microservices Interview Questions and Answers

Prepare for system design and microservices interviews, covering scalable architecture, distributed systems, service communication, databases, caching, resilience, and real-world architecture decisions.

Total Questions

120

Beginner

30

Intermediate

49

Advanced

41

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Foundations

What is system design?

System design translates functional and quality requirements into components, interfaces, data models, and operational trade-offs.

Answer

System design translates functional and quality requirements into components, interfaces, data models, and operational trade-offs.

Example: GET /orders/{id} -> 200 {"id":"o1","status":"paid"}

Diagram / flow: Client -> API -> Service -> Database

Syntax

GET /orders/{id} -> 200 {"id":"o1","status":"paid"}

// Architecture flow
Client -> API -> Service -> Database

Example

GET /orders/{id} -> 200 {"id":"o1","status":"paid"} // Architecture flow Client -> API -> Service -> Database

Code example

GET /orders/{id} -> 200 {"id":"o1","status":"paid"}

// Architecture flow
Client -> API -> Service -> Database

Diagram

Example: GET /orders/{id} -> 200 {"id":"o1","status":"paid"}

Key Points

  • System design translates functional and quality requirements into components, interfaces, data models, and operational trade-offs.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q2Foundations

Functional vs non-functional requirements?

Functional requirements describe behavior

Answer

Functional requirements describe behavior; non-functional requirements specify latency, availability, scale, security, and durability targets.

Example: Functional: place order; SLO: p95 < 250 ms at 2k RPS

Diagram / flow: Requirements -> Constraints -> Architecture

Syntax

Functional: place order; SLO: p95 < 250 ms at 2k RPS

// Architecture flow
Requirements -> Constraints -> Architecture

Example

Functional: place order; SLO: p95 < 250 ms at 2k RPS // Architecture flow Requirements -> Constraints -> Architecture

Code example

Functional: place order; SLO: p95 < 250 ms at 2k RPS

// Architecture flow
Requirements -> Constraints -> Architecture

Diagram

Diagram / flow: Requirements -> Constraints -> Architecture

Key Points

  • Functional requirements describe behavior; non-functional requirements specify latency, availability, scale, security, and durability targets.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q3Scalability

What is scalability?

Scalability is the ability to sustain growing load by adding resources or improving efficiency without violating SLOs.

Answer

Scalability is the ability to sustain growing load by adding resources or improving efficiency without violating SLOs.

Example: Capacity = replicas * sustainable_RPS_per_replica

Diagram / flow: Traffic -> Load Balancer -> N replicas

Syntax

Capacity = replicas * sustainable_RPS_per_replica

// Architecture flow
Traffic -> Load Balancer -> N replicas

Example

Capacity = replicas * sustainable_RPS_per_replica // Architecture flow Traffic -> Load Balancer -> N replicas

Code example

Capacity = replicas * sustainable_RPS_per_replica

// Architecture flow
Traffic -> Load Balancer -> N replicas

Diagram

Diagram / flow: Traffic -> Load Balancer -> N replicas

Key Points

  • Scalability is the ability to sustain growing load by adding resources or improving efficiency without violating SLOs.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q4Scalability

Vertical vs horizontal scaling?

Vertical scaling upgrades a node and has hardware limits

Answer

Vertical scaling upgrades a node and has hardware limits; horizontal scaling adds nodes and requires coordination and statelessness where possible.

Example: scale up: 4 CPU -> 16 CPU; scale out: 2 pods -> 8 pods

Diagram / flow: Load Balancer -> Pod A / Pod B / Pod C

Syntax

scale up: 4 CPU -> 16 CPU; scale out: 2 pods -> 8 pods

// Architecture flow
Load Balancer -> Pod A / Pod B / Pod C

Example

scale up: 4 CPU -> 16 CPU; scale out: 2 pods -> 8 pods // Architecture flow Load Balancer -> Pod A / Pod B / Pod C

Code example

scale up: 4 CPU -> 16 CPU; scale out: 2 pods -> 8 pods

// Architecture flow
Load Balancer -> Pod A / Pod B / Pod C

Diagram

Example: scale up: 4 CPU -> 16 CPU; scale out: 2 pods -> 8 pods

Key Points

  • Vertical scaling upgrades a node and has hardware limits; horizontal scaling adds nodes and requires coordination and statelessness where possible.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q5Performance

What is latency vs throughput?

Latency is time per operation

Answer

Latency is time per operation; throughput is completed operations per time unit. Increasing throughput may raise latency near saturation.

Example: p95_latency_ms=180; throughput_rps=1200

Diagram / flow: Requests -> Queue -> Workers -> Responses

Syntax

p95_latency_ms=180; throughput_rps=1200

// Architecture flow
Requests -> Queue -> Workers -> Responses

Example

p95_latency_ms=180; throughput_rps=1200 // Architecture flow Requests -> Queue -> Workers -> Responses

Code example

p95_latency_ms=180; throughput_rps=1200

// Architecture flow
Requests -> Queue -> Workers -> Responses

Diagram

Diagram / flow: Requests -> Queue -> Workers -> Responses

Key Points

  • Latency is time per operation; throughput is completed operations per time unit.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q6Reliability

What is availability?

Availability is the proportion of time a service can successfully serve requests. Define it from the user perspective and track with an SLI.

Answer

Availability is the proportion of time a service can successfully serve requests. Define it from the user perspective and track with an SLI.

Example: availability = successful_requests / valid_requests

Diagram / flow: Client -> Zone A OR Zone B

Syntax

availability = successful_requests / valid_requests

// Architecture flow
Client -> Zone A OR Zone B

Example

availability = successful_requests / valid_requests // Architecture flow Client -> Zone A OR Zone B

Code example

availability = successful_requests / valid_requests

// Architecture flow
Client -> Zone A OR Zone B

Diagram

Diagram / flow: Client -> Zone A OR Zone B

Key Points

  • Availability is the proportion of time a service can successfully serve requests.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q7Networking

What is a load balancer?

A load balancer distributes traffic across healthy instances using algorithms such as round robin or least connections.

Answer

A load balancer distributes traffic across healthy instances using algorithms such as round robin or least connections.

Example: upstream orders { server orders1:8080; server orders2:8080; }

Diagram / flow: Client -> LB -> S1 / S2

Syntax

upstream orders { server orders1:8080; server orders2:8080; }

// Architecture flow
Client -> LB -> S1 / S2

Example

upstream orders { server orders1:8080; server orders2:8080; } // Architecture flow Client -> LB -> S1 / S2

Code example

upstream orders { server orders1:8080; server orders2:8080; }

// Architecture flow
Client -> LB -> S1 / S2

Diagram

Diagram / flow: Client -> LB -> S1 / S2

Key Points

  • A load balancer distributes traffic across healthy instances using algorithms such as round robin or least connections.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q8Caching

What is caching?

Caching stores frequently reused data closer to consumers to reduce latency and backend load

Answer

Caching stores frequently reused data closer to consumers to reduce latency and backend load; define TTL and invalidation explicitly.

Example: SET product:42 '{"price":99}' EX 60

Diagram / flow: Client -> Cache (hit) OR DB (miss)

Syntax

SET product:42 '{"price":99}' EX 60

// Architecture flow
Client -> Cache (hit) OR DB (miss)

Example

SET product:42 '{"price":99}' EX 60 // Architecture flow Client -> Cache (hit) OR DB (miss)

Code example

SET product:42 '{"price":99}' EX 60

// Architecture flow
Client -> Cache (hit) OR DB (miss)

Diagram

Diagram / flow: Client -> Cache (hit) OR DB (miss)

Key Points

  • Caching stores frequently reused data closer to consumers to reduce latency and backend load; define TTL and invalidation explicitly.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q9Caching

Cache-aside vs write-through?

Cache-aside reads cache first and fills on miss

Answer

Cache-aside reads cache first and fills on miss; write-through updates cache on each write, trading write overhead for fresher reads.

Example: value = cache.get(key) ?? db.read(key); cache.set(key,value,ttl)

Diagram / flow: Read -> Cache miss -> DB -> Cache

Syntax

value = cache.get(key) ?? db.read(key); cache.set(key,value,ttl)

// Architecture flow
Read -> Cache miss -> DB -> Cache

Example

value = cache.get(key) ?? db.read(key); cache.set(key,value,ttl) // Architecture flow Read -> Cache miss -> DB -> Cache

Code example

value = cache.get(key) ?? db.read(key); cache.set(key,value,ttl)

// Architecture flow
Read -> Cache miss -> DB -> Cache

Diagram

Diagram / flow: Read -> Cache miss -> DB -> Cache

Key Points

  • Cache-aside reads cache first and fills on miss; write-through updates cache on each write, trading write overhead for fresher reads.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q10Networking

What is a CDN?

A CDN serves cacheable assets from geographically distributed edge locations to reduce origin traffic and improve user latency.

Answer

A CDN serves cacheable assets from geographically distributed edge locations to reduce origin traffic and improve user latency.

Example: Cache-Control: public, max-age=86400

Diagram / flow: User -> Edge POP -> Origin on miss

Syntax

Cache-Control: public, max-age=86400

// Architecture flow
User -> Edge POP -> Origin on miss

Example

Cache-Control: public, max-age=86400 // Architecture flow User -> Edge POP -> Origin on miss

Code example

Cache-Control: public, max-age=86400

// Architecture flow
User -> Edge POP -> Origin on miss

Diagram

Diagram / flow: User -> Edge POP -> Origin on miss

Key Points

  • A CDN serves cacheable assets from geographically distributed edge locations to reduce origin traffic and improve user latency.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q11Data

What is database indexing?

An index accelerates selected queries at the cost of extra storage and write amplification

Answer

An index accelerates selected queries at the cost of extra storage and write amplification; align index order with query predicates.

Example: CREATE INDEX ix_orders_user_created ON orders(user_id, created_at DESC);

Diagram / flow: Query -> B-tree index -> Matching rows

Syntax

CREATE INDEX ix_orders_user_created ON orders(user_id, created_at DESC);

// Architecture flow
Query -> B-tree index -> Matching rows

Example

CREATE INDEX ix_orders_user_created ON orders(user_id, created_at DESC); // Architecture flow Query -> B-tree index -> Matching rows

Code example

CREATE INDEX ix_orders_user_created ON orders(user_id, created_at DESC);

// Architecture flow
Query -> B-tree index -> Matching rows

Diagram

Diagram / flow: Query -> B-tree index -> Matching rows

Key Points

  • An index accelerates selected queries at the cost of extra storage and write amplification; align index order with query predicates.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q12Data

SQL vs NoSQL databases?

Relational stores favor joins, constraints, and transactions

Answer

Relational stores favor joins, constraints, and transactions; non-relational models can favor flexible schemas or key-based access. Choose from access patterns.

Example: SQL: SELECT * FROM orders WHERE user_id=7;

Diagram / flow: Service -> SQL / Document / Key-value

Syntax

SQL: SELECT * FROM orders WHERE user_id=7;

// Architecture flow
Service -> SQL / Document / Key-value

Example

SQL: SELECT * FROM orders WHERE user_id=7; // Architecture flow Service -> SQL / Document / Key-value

Code example

SQL: SELECT * FROM orders WHERE user_id=7;

// Architecture flow
Service -> SQL / Document / Key-value

Diagram

Diagram / flow: Service -> SQL / Document / Key-value

Key Points

  • Relational stores favor joins, constraints, and transactions; non-relational models can favor flexible schemas or key-based access.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q13Data

What is database replication?

Replication copies data across nodes for read scale or resilience

Answer

Replication copies data across nodes for read scale or resilience; asynchronous replicas may lag, so route read-after-write carefully.

Example: primary -> replica1, replica2 (async)

Diagram / flow: Writes -> Primary -> Replicas -> Reads

Syntax

primary -> replica1, replica2 (async)

// Architecture flow
Writes -> Primary -> Replicas -> Reads

Example

primary -> replica1, replica2 (async) // Architecture flow Writes -> Primary -> Replicas -> Reads

Code example

primary -> replica1, replica2 (async)

// Architecture flow
Writes -> Primary -> Replicas -> Reads

Diagram

Example: primary -> replica1, replica2 (async)

Key Points

  • Replication copies data across nodes for read scale or resilience; asynchronous replicas may lag, so route read-after-write carefully.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q14Data

What is database sharding?

Sharding partitions rows across databases by a key

Answer

Sharding partitions rows across databases by a key; it scales storage but makes rebalancing and cross-shard queries harder.

Example: shard = hash(customer_id) % 8

Diagram / flow: Router -> Shard 0 / Shard 1 / Shard 2

Syntax

shard = hash(customer_id) % 8

// Architecture flow
Router -> Shard 0 / Shard 1 / Shard 2

Example

shard = hash(customer_id) % 8 // Architecture flow Router -> Shard 0 / Shard 1 / Shard 2

Code example

shard = hash(customer_id) % 8

// Architecture flow
Router -> Shard 0 / Shard 1 / Shard 2

Diagram

Diagram / flow: Router -> Shard 0 / Shard 1 / Shard 2

Key Points

  • Sharding partitions rows across databases by a key; it scales storage but makes rebalancing and cross-shard queries harder.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q15Messaging

What is a message queue?

A queue buffers work between producers and consumers, smoothing spikes and decoupling request latency from processing time.

Answer

A queue buffers work between producers and consumers, smoothing spikes and decoupling request latency from processing time.

Example: publish('email-jobs', {userId:42})

Diagram / flow: Producer -> Queue -> Worker

Syntax

publish('email-jobs', {userId:42})

// Architecture flow
Producer -> Queue -> Worker

Example

publish('email-jobs', {userId:42}) // Architecture flow Producer -> Queue -> Worker

Code example

publish('email-jobs', {userId:42})

// Architecture flow
Producer -> Queue -> Worker

Diagram

Diagram / flow: Producer -> Queue -> Worker

Key Points

  • A queue buffers work between producers and consumers, smoothing spikes and decoupling request latency from processing time.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q16Communication

Synchronous vs asynchronous communication?

Synchronous calls return a direct response and couple availability

Answer

Synchronous calls return a direct response and couple availability; asynchronous messaging decouples timing but introduces eventual consistency.

Example: sync: POST /payments; async: publish PaymentRequested

Diagram / flow: API -> Payment API OR Broker -> Worker

Syntax

sync: POST /payments; async: publish PaymentRequested

// Architecture flow
API -> Payment API OR Broker -> Worker

Example

sync: POST /payments; async: publish PaymentRequested // Architecture flow API -> Payment API OR Broker -> Worker

Code example

sync: POST /payments; async: publish PaymentRequested

// Architecture flow
API -> Payment API OR Broker -> Worker

Diagram

Diagram / flow: API -> Payment API OR Broker -> Worker

Key Points

  • Synchronous calls return a direct response and couple availability; asynchronous messaging decouples timing but introduces eventual consistency.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q17API

What is an API gateway?

An API gateway provides a unified entry point for routing, authentication integration, quotas, and observability

Answer

An API gateway provides a unified entry point for routing, authentication integration, quotas, and observability; avoid placing domain logic there.

Example: /api/orders/* -> orders-service

Diagram / flow: Client -> Gateway -> Orders / Users

Syntax

/api/orders/* -> orders-service

// Architecture flow
Client -> Gateway -> Orders / Users

Example

/api/orders/* -> orders-service // Architecture flow Client -> Gateway -> Orders / Users

Code example

/api/orders/* -> orders-service

// Architecture flow
Client -> Gateway -> Orders / Users

Diagram

Example: /api/orders/* -> orders-service

Key Points

  • An API gateway provides a unified entry point for routing, authentication integration, quotas, and observability; avoid placing domain logic there.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q18API

What is rate limiting?

Rate limiting protects shared capacity by bounding requests per identity or tenant

Answer

Rate limiting protects shared capacity by bounding requests per identity or tenant; return explicit retry guidance when possible.

Example: HTTP 429; Retry-After: 30

Diagram / flow: Client -> Limiter -> API

Syntax

HTTP 429; Retry-After: 30

// Architecture flow
Client -> Limiter -> API

Example

HTTP 429; Retry-After: 30 // Architecture flow Client -> Limiter -> API

Code example

HTTP 429; Retry-After: 30

// Architecture flow
Client -> Limiter -> API

Diagram

Diagram / flow: Client -> Limiter -> API

Key Points

  • Rate limiting protects shared capacity by bounding requests per identity or tenant; return explicit retry guidance when possible.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q19API

What is idempotency?

An idempotent operation has the same intended effect when repeated

Answer

An idempotent operation has the same intended effect when repeated; idempotency keys help safely retry payment or order creation.

Example: Idempotency-Key: 8f8c...

Diagram / flow: Retry -> Key store -> One mutation

Syntax

Idempotency-Key: 8f8c...

// Architecture flow
Retry -> Key store -> One mutation

Example

Idempotency-Key: 8f8c... // Architecture flow Retry -> Key store -> One mutation

Code example

Idempotency-Key: 8f8c...

// Architecture flow
Retry -> Key store -> One mutation

Diagram

Diagram / flow: Retry -> Key store -> One mutation

Key Points

  • An idempotent operation has the same intended effect when repeated; idempotency keys help safely retry payment or order creation.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q20Architecture

What is a monolith?

A monolith deploys business capabilities as one application

Answer

A monolith deploys business capabilities as one application; it simplifies local transactions and operations but can increase release coupling.

Example: app = auth + catalog + orders + billing

Diagram / flow: Clients -> Monolith -> DB

Syntax

app = auth + catalog + orders + billing

// Architecture flow
Clients -> Monolith -> DB

Example

app = auth + catalog + orders + billing // Architecture flow Clients -> Monolith -> DB

Code example

app = auth + catalog + orders + billing

// Architecture flow
Clients -> Monolith -> DB

Diagram

Diagram / flow: Clients -> Monolith -> DB

Key Points

  • A monolith deploys business capabilities as one application; it simplifies local transactions and operations but can increase release coupling.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q21Architecture

What are microservices?

Microservices are independently deployable services aligned to business capabilities, each owning its behavior and ideally its data.

Answer

Microservices are independently deployable services aligned to business capabilities, each owning its behavior and ideally its data.

Example: orders-service: POST /orders

Diagram / flow: Gateway -> Orders / Inventory / Billing

Syntax

orders-service: POST /orders

// Architecture flow
Gateway -> Orders / Inventory / Billing

Example

orders-service: POST /orders // Architecture flow Gateway -> Orders / Inventory / Billing

Code example

orders-service: POST /orders

// Architecture flow
Gateway -> Orders / Inventory / Billing

Diagram

Diagram / flow: Gateway -> Orders / Inventory / Billing

Key Points

  • Microservices are independently deployable services aligned to business capabilities, each owning its behavior and ideally its data.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q22Architecture

Monolith vs microservices trade-offs?

Microservices improve independent scaling and team autonomy but add distributed failures, network overhead, and operational complexity. Start with a modular monolith when appropria

Answer

Microservices improve independent scaling and team autonomy but add distributed failures, network overhead, and operational complexity. Start with a modular monolith when appropriate.

Example: modular monolith -> extract bounded context when justified

Diagram / flow: Monolith -> [Orders] [Billing] [Users]

Syntax

modular monolith -> extract bounded context when justified

// Architecture flow
Monolith -> [Orders] [Billing] [Users]

Example

modular monolith -> extract bounded context when justified // Architecture flow Monolith -> [Orders] [Billing] [Users]

Code example

modular monolith -> extract bounded context when justified

// Architecture flow
Monolith -> [Orders] [Billing] [Users]

Diagram

Example: modular monolith -> extract bounded context when justified

Key Points

  • Microservices improve independent scaling and team autonomy but add distributed failures, network overhead, and operational complexity.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q23Domain-Driven Design

What is a bounded context?

A bounded context defines where a domain model and its language are consistent

Answer

A bounded context defines where a domain model and its language are consistent; service boundaries often follow these business boundaries.

Example: Order in Sales != Order in Shipping

Diagram / flow: Sales Context / Shipping Context

Syntax

Order in Sales != Order in Shipping

// Architecture flow
Sales Context / Shipping Context

Example

Order in Sales != Order in Shipping // Architecture flow Sales Context / Shipping Context

Code example

Order in Sales != Order in Shipping

// Architecture flow
Sales Context / Shipping Context

Diagram

Diagram / flow: Sales Context / Shipping Context

Key Points

  • A bounded context defines where a domain model and its language are consistent; service boundaries often follow these business boundaries.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q24Networking

What is service discovery?

Service discovery resolves logical service names to healthy instances, avoiding hard-coded IP addresses in dynamic environments.

Answer

Service discovery resolves logical service names to healthy instances, avoiding hard-coded IP addresses in dynamic environments.

Example: http://inventory.default.svc.cluster.local

Diagram / flow: Orders -> DNS/Registry -> Inventory pods

Syntax

http://inventory.default.svc.cluster.local

// Architecture flow
Orders -> DNS/Registry -> Inventory pods

Example

http://inventory.default.svc.cluster.local // Architecture flow Orders -> DNS/Registry -> Inventory pods

Code example

http://inventory.default.svc.cluster.local

// Architecture flow
Orders -> DNS/Registry -> Inventory pods

Diagram

Diagram / flow: Orders -> DNS/Registry -> Inventory pods

Key Points

  • Service discovery resolves logical service names to healthy instances, avoiding hard-coded IP addresses in dynamic environments.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q25Deployment

What is containerization?

Containers package an application and its runtime dependencies into a portable image while sharing the host kernel.

Answer

Containers package an application and its runtime dependencies into a portable image while sharing the host kernel.

Example: docker build -t orders:1.0 .

Diagram / flow: Image -> Container -> Host

Syntax

docker build -t orders:1.0 .

// Architecture flow
Image -> Container -> Host

Example

docker build -t orders:1.0 . // Architecture flow Image -> Container -> Host

Code example

docker build -t orders:1.0 .

// Architecture flow
Image -> Container -> Host

Diagram

Diagram / flow: Image -> Container -> Host

Key Points

  • Containers package an application and its runtime dependencies into a portable image while sharing the host kernel.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q81Architecture

How does an API gateway differ from a load balancer?

A load balancer distributes traffic across instances. An API gateway commonly provides API-level routing and cross-cutting concerns such as authe

Answer

A load balancer distributes traffic across instances. An API gateway commonly provides API-level routing and cross-cutting concerns such as authentication, quotas, and request transformation; products can overlap.

Example: GET /orders → gateway validates token and routes /orders → load balancer selects healthy instance.

Diagram / flow: Client → API Gateway → Orders Service Load Balancer → Orders instances

Syntax

Client → gateway (API policy/routing) → service load balancer → service instances

Example

GET /orders → gateway validates token and routes /orders → load balancer selects healthy instance.

Code example

Client → gateway (API policy/routing) → service load balancer → service instances

Diagram

Client → API Gateway → Orders Service Load Balancer → Orders instances

Key Points

  • A load balancer distributes traffic across instances.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q83Caching

How does the cache-aside pattern work?

The application checks the cache first. On a miss, it reads the source of truth, populates the cache, and returns the value. Writes usually updat

Answer

The application checks the cache first. On a miss, it reads the source of truth, populates the cache, and returns the value. Writes usually update the database and invalidate or refresh the cache.

Example: Request product → cache miss → read Products table → cache result for 60 seconds.

Diagram / flow: Client → cache? hit: return; miss: database → populate cache → return

Syntax

GET key; if miss: read DB → SET key with TTL

Example

Request product → cache miss → read Products table → cache result for 60 seconds.

Code example

GET key; if miss: read DB → SET key with TTL

Diagram

Client → cache? hit: return; miss: database → populate cache → return

Key Points

  • The application checks the cache first.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q88Scalability

Compare horizontal and vertical scaling.

Vertical scaling adds resources to one machine; horizontal scaling adds instances. Horizontal scaling can improve capacity and failure isolation

Answer

Vertical scaling adds resources to one machine; horizontal scaling adds instances. Horizontal scaling can improve capacity and failure isolation but introduces coordination, state distribution, and network overhead.

Example: Add two stateless API instances behind a load balancer to increase request capacity.

Diagram / flow: One larger machine vs multiple instances behind load balancing

Syntax

capacity ≈ instanceCount × perInstanceCapacity (rough estimate)

Example

Add two stateless API instances behind a load balancer to increase request capacity.

Code example

capacity ≈ instanceCount × perInstanceCapacity (rough estimate)

Diagram

One larger machine vs multiple instances behind load balancing

Key Points

  • Vertical scaling adds resources to one machine; horizontal scaling adds instances.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q89Architecture

Why are stateless service instances easier to scale?

Stateless instances do not keep durable user session state locally between requests. Shared state is externalized to a database, cache, or token

Answer

Stateless instances do not keep durable user session state locally between requests. Shared state is externalized to a database, cache, or token so any healthy instance can handle the next request.

Example: Store shopping-cart state in Redis or a durable store instead of local process memory.

Diagram / flow: Load balancer → instance A/B/C; shared state is external

Syntax

request → any healthy instance

Example

Store shopping-cart state in Redis or a durable store instead of local process memory.

Code example

request → any healthy instance

Diagram

Load balancer → instance A/B/C; shared state is external

Key Points

  • Stateless instances do not keep durable user session state locally between requests.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q97Distributed systems

What is eventual consistency?

Replicas or services may temporarily return different values after a write, but converge if updates stop and propagation succeeds. Design UI and

Answer

Replicas or services may temporarily return different values after a write, but converge if updates stop and propagation succeeds. Design UI and business flows around stale reads, retries, and reconciliation.

Example: An order confirmation appears immediately while analytics updates seconds later.

Diagram / flow: Write service → event stream → projections update → eventual convergence

Syntax

write accepted → asynchronous propagation → replicas converge

Example

An order confirmation appears immediately while analytics updates seconds later.

Code example

write accepted → asynchronous propagation → replicas converge

Diagram

Write service → event stream → projections update → eventual convergence

Key Points

  • Replicas or services may temporarily return different values after a write, but converge if updates stop and propagation succeeds.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q26Deployment

What is orchestration with Kubernetes?

Kubernetes schedules containers, reconciles desired replicas, and provides service networking, rollout, and health checks.

Answer

Kubernetes schedules containers, reconciles desired replicas, and provides service networking, rollout, and health checks.

Example: kubectl scale deployment/orders --replicas=4

Diagram / flow: Deployment -> ReplicaSet -> Pods

Syntax

kubectl scale deployment/orders --replicas=4

// Architecture flow
Deployment -> ReplicaSet -> Pods

Example

kubectl scale deployment/orders --replicas=4 // Architecture flow Deployment -> ReplicaSet -> Pods

Code example

kubectl scale deployment/orders --replicas=4

// Architecture flow
Deployment -> ReplicaSet -> Pods

Diagram

Diagram / flow: Deployment -> ReplicaSet -> Pods

Key Points

  • Kubernetes schedules containers, reconciles desired replicas, and provides service networking, rollout, and health checks.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q27Deployment

What are liveness and readiness probes?

Readiness determines whether a pod receives traffic

Answer

Readiness determines whether a pod receives traffic; liveness detects a stuck process and can trigger a restart. Avoid failing liveness on transient dependencies.

Example: readinessProbe: {httpGet: {path: /ready, port: 8080}}

Diagram / flow: LB -> Ready Pods only

Syntax

readinessProbe: {httpGet: {path: /ready, port: 8080}}

// Architecture flow
LB -> Ready Pods only

Example

readinessProbe: {httpGet: {path: /ready, port: 8080}} // Architecture flow LB -> Ready Pods only

Code example

readinessProbe: {httpGet: {path: /ready, port: 8080}}

// Architecture flow
LB -> Ready Pods only

Diagram

Diagram / flow: LB -> Ready Pods only

Key Points

  • Readiness determines whether a pod receives traffic; liveness detects a stuck process and can trigger a restart.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q28Resilience

What is a circuit breaker?

A circuit breaker stops calls to a failing dependency after a threshold and probes recovery after a cool-down, preventing cascading failures.

Answer

A circuit breaker stops calls to a failing dependency after a threshold and probes recovery after a cool-down, preventing cascading failures.

Example: Closed -> Open -> HalfOpen -> Closed

Diagram / flow: Caller -> Breaker -X-> Failed Service

Syntax

Closed -> Open -> HalfOpen -> Closed

// Architecture flow
Caller -> Breaker -X-> Failed Service

Example

Closed -> Open -> HalfOpen -> Closed // Architecture flow Caller -> Breaker -X-> Failed Service

Code example

Closed -> Open -> HalfOpen -> Closed

// Architecture flow
Caller -> Breaker -X-> Failed Service

Diagram

Example: Closed -> Open -> HalfOpen -> Closed

Key Points

  • A circuit breaker stops calls to a failing dependency after a threshold and probes recovery after a cool-down, preventing cascading failures.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q29Resilience

What are retries and exponential backoff?

Retries handle transient failures, but require bounded attempts, jitter, and idempotent operations to avoid amplifying overload.

Answer

Retries handle transient failures, but require bounded attempts, jitter, and idempotent operations to avoid amplifying overload.

Example: delay_ms = min(5000, 100 * 2**attempt) + jitter

Diagram / flow: Call -> Fail -> Wait -> Retry

Syntax

delay_ms = min(5000, 100 * 2**attempt) + jitter

// Architecture flow
Call -> Fail -> Wait -> Retry

Example

delay_ms = min(5000, 100 * 2**attempt) + jitter // Architecture flow Call -> Fail -> Wait -> Retry

Code example

delay_ms = min(5000, 100 * 2**attempt) + jitter

// Architecture flow
Call -> Fail -> Wait -> Retry

Diagram

Diagram / flow: Call -> Fail -> Wait -> Retry

Key Points

  • Retries handle transient failures, but require bounded attempts, jitter, and idempotent operations to avoid amplifying overload.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q30Resilience

What is a timeout budget?

A timeout caps how long a dependency can hold resources

Answer

A timeout caps how long a dependency can hold resources; propagate an end-to-end deadline and reserve time for upstream processing.

Example: request_deadline_ms = 800; db_timeout_ms = 150

Diagram / flow: Gateway 800ms -> API 500ms -> DB 150ms

Syntax

request_deadline_ms = 800; db_timeout_ms = 150

// Architecture flow
Gateway 800ms -> API 500ms -> DB 150ms

Example

request_deadline_ms = 800; db_timeout_ms = 150 // Architecture flow Gateway 800ms -> API 500ms -> DB 150ms

Code example

request_deadline_ms = 800; db_timeout_ms = 150

// Architecture flow
Gateway 800ms -> API 500ms -> DB 150ms

Diagram

Diagram / flow: Gateway 800ms -> API 500ms -> DB 150ms

Key Points

  • A timeout caps how long a dependency can hold resources; propagate an end-to-end deadline and reserve time for upstream processing.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q31Resilience

What is bulkhead isolation?

Bulkheads allocate separate concurrency pools or resources per dependency or tenant, preventing one failing path from exhausting all capacity.

Answer

Bulkheads allocate separate concurrency pools or resources per dependency or tenant, preventing one failing path from exhausting all capacity.

Example: payment_pool=20; recommendation_pool=10

Diagram / flow: API -> Pool A / Pool B

Syntax

payment_pool=20; recommendation_pool=10

// Architecture flow
API -> Pool A / Pool B

Example

payment_pool=20; recommendation_pool=10 // Architecture flow API -> Pool A / Pool B

Code example

payment_pool=20; recommendation_pool=10

// Architecture flow
API -> Pool A / Pool B

Diagram

Diagram / flow: API -> Pool A / Pool B

Key Points

  • Bulkheads allocate separate concurrency pools or resources per dependency or tenant, preventing one failing path from exhausting all capacity.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q32Consistency

What is eventual consistency?

Eventual consistency means replicas or services may temporarily disagree but converge if updates stop

Answer

Eventual consistency means replicas or services may temporarily disagree but converge if updates stop; design UX and workflows around staleness.

Example: OrderCreated -> InventoryReserved (later)

Diagram / flow: Orders -> Event -> Inventory

Syntax

OrderCreated -> InventoryReserved (later)

// Architecture flow
Orders -> Event -> Inventory

Example

OrderCreated -> InventoryReserved (later) // Architecture flow Orders -> Event -> Inventory

Code example

OrderCreated -> InventoryReserved (later)

// Architecture flow
Orders -> Event -> Inventory

Diagram

Example: OrderCreated -> InventoryReserved (later)

Key Points

  • Eventual consistency means replicas or services may temporarily disagree but converge if updates stop; design UX and workflows around staleness.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q33Consistency

What is strong consistency?

Strong consistency ensures operations observe a single agreed order under the chosen model, often increasing coordination costs.

Answer

Strong consistency ensures operations observe a single agreed order under the chosen model, often increasing coordination costs.

Example: transaction { debit(); credit(); }

Diagram / flow: Client -> Leader/Quorum -> Commit

Syntax

transaction { debit(); credit(); }

// Architecture flow
Client -> Leader/Quorum -> Commit

Example

transaction { debit(); credit(); } // Architecture flow Client -> Leader/Quorum -> Commit

Code example

transaction { debit(); credit(); }

// Architecture flow
Client -> Leader/Quorum -> Commit

Diagram

Diagram / flow: Client -> Leader/Quorum -> Commit

Key Points

  • Strong consistency ensures operations observe a single agreed order under the chosen model, often increasing coordination costs.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q34Distributed Systems

What is the CAP theorem?

Under a network partition, a distributed data system must trade off availability of responses against linearizable consistency

Answer

Under a network partition, a distributed data system must trade off availability of responses against linearizable consistency; CAP does not say choose only two in normal operation.

Example: partition: choose reject stale writes OR accept divergent writes

Diagram / flow: Node A -X- Node B (partition)

Syntax

partition: choose reject stale writes OR accept divergent writes

// Architecture flow
Node A -X- Node B (partition)

Example

partition: choose reject stale writes OR accept divergent writes // Architecture flow Node A -X- Node B (partition)

Code example

partition: choose reject stale writes OR accept divergent writes

// Architecture flow
Node A -X- Node B (partition)

Diagram

Diagram / flow: Node A -X- Node B (partition)

Key Points

  • Under a network partition, a distributed data system must trade off availability of responses against linearizable consistency; CAP does not say choose only two in normal operation.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q35Transactions

What is a distributed transaction?

A distributed transaction coordinates changes across independent participants

Answer

A distributed transaction coordinates changes across independent participants; it adds latency and failure complexity, so prefer local transactions plus workflows when feasible.

Example: prepare -> vote -> commit/abort

Diagram / flow: Coordinator -> DB A + DB B

Syntax

prepare -> vote -> commit/abort

// Architecture flow
Coordinator -> DB A + DB B

Example

prepare -> vote -> commit/abort // Architecture flow Coordinator -> DB A + DB B

Code example

prepare -> vote -> commit/abort

// Architecture flow
Coordinator -> DB A + DB B

Diagram

Example: prepare -> vote -> commit/abort

Key Points

  • A distributed transaction coordinates changes across independent participants; it adds latency and failure complexity, so prefer local transactions plus workflows when feasible.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q36Transactions

What is the Saga pattern?

A saga coordinates local transactions through events or commands and uses compensating actions to recover from partial failure.

Answer

A saga coordinates local transactions through events or commands and uses compensating actions to recover from partial failure.

Example: ReserveStock -> ChargeCard -> Ship; failure -> Refund

Diagram / flow: Order -> Stock -> Payment -> Shipping

Syntax

ReserveStock -> ChargeCard -> Ship; failure -> Refund

// Architecture flow
Order -> Stock -> Payment -> Shipping

Example

ReserveStock -> ChargeCard -> Ship; failure -> Refund // Architecture flow Order -> Stock -> Payment -> Shipping

Code example

ReserveStock -> ChargeCard -> Ship; failure -> Refund

// Architecture flow
Order -> Stock -> Payment -> Shipping

Diagram

Example: ReserveStock -> ChargeCard -> Ship; failure -> Refund

Key Points

  • A saga coordinates local transactions through events or commands and uses compensating actions to recover from partial failure.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q37Transactions

Choreography vs orchestration in sagas?

Choreography reacts to events without a central controller

Answer

Choreography reacts to events without a central controller; orchestration uses a workflow coordinator, improving visibility at the cost of central coordination.

Example: on OrderCreated -> ReserveInventory

Diagram / flow: Events <-> Services OR Orchestrator -> Services

Syntax

on OrderCreated -> ReserveInventory

// Architecture flow
Events <-> Services OR Orchestrator -> Services

Example

on OrderCreated -> ReserveInventory // Architecture flow Events <-> Services OR Orchestrator -> Services

Code example

on OrderCreated -> ReserveInventory

// Architecture flow
Events <-> Services OR Orchestrator -> Services

Diagram

Example: on OrderCreated -> ReserveInventory

Key Points

  • Choreography reacts to events without a central controller; orchestration uses a workflow coordinator, improving visibility at the cost of central coordination.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q38Messaging

What is the outbox pattern?

The transactional outbox stores an event in the same database transaction as business state

Answer

The transactional outbox stores an event in the same database transaction as business state; a relay later publishes it, preventing dual-write gaps.

Example: BEGIN; UPDATE orders ...; INSERT INTO outbox ...; COMMIT;

Diagram / flow: Service -> DB(order + outbox) -> Relay -> Broker

Syntax

BEGIN; UPDATE orders ...; INSERT INTO outbox ...; COMMIT;

// Architecture flow
Service -> DB(order + outbox) -> Relay -> Broker

Example

BEGIN; UPDATE orders ...; INSERT INTO outbox ...; COMMIT; // Architecture flow Service -> DB(order + outbox) -> Relay -> Broker

Code example

BEGIN; UPDATE orders ...; INSERT INTO outbox ...; COMMIT;

// Architecture flow
Service -> DB(order + outbox) -> Relay -> Broker

Diagram

Diagram / flow: Service -> DB(order + outbox) -> Relay -> Broker

Key Points

  • The transactional outbox stores an event in the same database transaction as business state; a relay later publishes it, preventing dual-write gaps.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q39Messaging

What is the inbox pattern?

An inbox records processed message identifiers so a consumer can ignore redeliveries and apply business changes once per key.

Answer

An inbox records processed message identifiers so a consumer can ignore redeliveries and apply business changes once per key.

Example: INSERT INTO inbox(message_id) ON CONFLICT DO NOTHING;

Diagram / flow: Broker -> Consumer -> Inbox dedupe -> DB

Syntax

INSERT INTO inbox(message_id) ON CONFLICT DO NOTHING;

// Architecture flow
Broker -> Consumer -> Inbox dedupe -> DB

Example

INSERT INTO inbox(message_id) ON CONFLICT DO NOTHING; // Architecture flow Broker -> Consumer -> Inbox dedupe -> DB

Code example

INSERT INTO inbox(message_id) ON CONFLICT DO NOTHING;

// Architecture flow
Broker -> Consumer -> Inbox dedupe -> DB

Diagram

Diagram / flow: Broker -> Consumer -> Inbox dedupe -> DB

Key Points

  • An inbox records processed message identifiers so a consumer can ignore redeliveries and apply business changes once per key.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q40Messaging

At-most-once vs at-least-once delivery?

At-most-once may lose messages but avoids redelivery

Answer

At-most-once may lose messages but avoids redelivery; at-least-once retries and can duplicate, so consumers must be idempotent.

Example: ack after durable commit => at-least-once behavior

Diagram / flow: Broker -> Delivery -> Ack / Retry

Syntax

ack after durable commit => at-least-once behavior

// Architecture flow
Broker -> Delivery -> Ack / Retry

Example

ack after durable commit => at-least-once behavior // Architecture flow Broker -> Delivery -> Ack / Retry

Code example

ack after durable commit => at-least-once behavior

// Architecture flow
Broker -> Delivery -> Ack / Retry

Diagram

Diagram / flow: Broker -> Delivery -> Ack / Retry

Key Points

  • At-most-once may lose messages but avoids redelivery; at-least-once retries and can duplicate, so consumers must be idempotent.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q41Messaging

Exactly-once processing: what does it mean?

Exactly-once is scoped to a system boundary

Answer

Exactly-once is scoped to a system boundary; end-to-end effects usually require transactions, deduplication, and idempotency rather than trusting a broker label.

Example: unique(event_id) + business transaction

Diagram / flow: Message -> Dedupe -> Transaction -> Effect

Syntax

unique(event_id) + business transaction

// Architecture flow
Message -> Dedupe -> Transaction -> Effect

Example

unique(event_id) + business transaction // Architecture flow Message -> Dedupe -> Transaction -> Effect

Code example

unique(event_id) + business transaction

// Architecture flow
Message -> Dedupe -> Transaction -> Effect

Diagram

Diagram / flow: Message -> Dedupe -> Transaction -> Effect

Key Points

  • Exactly-once is scoped to a system boundary; end-to-end effects usually require transactions, deduplication, and idempotency rather than trusting a broker label.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q42Architecture

What is event-driven architecture?

Services publish facts about completed state changes and subscribe to relevant events, reducing temporal coupling but complicating tracing and schema evolution.

Answer

Services publish facts about completed state changes and subscribe to relevant events, reducing temporal coupling but complicating tracing and schema evolution.

Example: event: {type:'OrderPlaced',version:1,orderId:'o1'}

Diagram / flow: Orders -> Event Bus -> Billing / Analytics

Syntax

event: {type:'OrderPlaced',version:1,orderId:'o1'}

// Architecture flow
Orders -> Event Bus -> Billing / Analytics

Example

event: {type:'OrderPlaced',version:1,orderId:'o1'} // Architecture flow Orders -> Event Bus -> Billing / Analytics

Code example

event: {type:'OrderPlaced',version:1,orderId:'o1'}

// Architecture flow
Orders -> Event Bus -> Billing / Analytics

Diagram

Diagram / flow: Orders -> Event Bus -> Billing / Analytics

Key Points

  • Services publish facts about completed state changes and subscribe to relevant events, reducing temporal coupling but complicating tracing and schema evolution.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q43Data

What is event sourcing?

Event sourcing stores an append-only history of state-changing events and derives current state by replay

Answer

Event sourcing stores an append-only history of state-changing events and derives current state by replay; projections and schema evolution require care.

Example: AccountOpened; MoneyDeposited; MoneyWithdrawn

Diagram / flow: Events -> Projection -> Read Model

Syntax

AccountOpened; MoneyDeposited; MoneyWithdrawn

// Architecture flow
Events -> Projection -> Read Model

Example

AccountOpened; MoneyDeposited; MoneyWithdrawn // Architecture flow Events -> Projection -> Read Model

Code example

AccountOpened; MoneyDeposited; MoneyWithdrawn

// Architecture flow
Events -> Projection -> Read Model

Diagram

Diagram / flow: Events -> Projection -> Read Model

Key Points

  • Event sourcing stores an append-only history of state-changing events and derives current state by replay; projections and schema evolution require care.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q44Data

What is CQRS?

CQRS separates command handling from query models when read and write needs differ

Answer

CQRS separates command handling from query models when read and write needs differ; it adds synchronization and operational complexity.

Example: POST /orders -> write; GET /orders -> read projection

Diagram / flow: Commands -> Write DB -> Events -> Read DB

Syntax

POST /orders -> write; GET /orders -> read projection

// Architecture flow
Commands -> Write DB -> Events -> Read DB

Example

POST /orders -> write; GET /orders -> read projection // Architecture flow Commands -> Write DB -> Events -> Read DB

Code example

POST /orders -> write; GET /orders -> read projection

// Architecture flow
Commands -> Write DB -> Events -> Read DB

Diagram

Example: POST /orders -> write; GET /orders -> read projection

Key Points

  • CQRS separates command handling from query models when read and write needs differ; it adds synchronization and operational complexity.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q45API

What is API versioning?

Versioning manages breaking changes while supporting existing consumers

Answer

Versioning manages breaking changes while supporting existing consumers; prefer additive changes and a published deprecation policy.

Example: GET /v2/orders/{id}

Diagram / flow: v1 clients -> v1 API; v2 clients -> v2 API

Syntax

GET /v2/orders/{id}

// Architecture flow
v1 clients -> v1 API; v2 clients -> v2 API

Example

GET /v2/orders/{id} // Architecture flow v1 clients -> v1 API; v2 clients -> v2 API

Code example

GET /v2/orders/{id}

// Architecture flow
v1 clients -> v1 API; v2 clients -> v2 API

Diagram

Diagram / flow: v1 clients -> v1 API; v2 clients -> v2 API

Key Points

  • Versioning manages breaking changes while supporting existing consumers; prefer additive changes and a published deprecation policy.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q46Communication

REST vs gRPC?

REST commonly uses HTTP resources and JSON

Answer

REST commonly uses HTTP resources and JSON; gRPC uses protobuf contracts and HTTP/2, often suited to internal typed RPC and streaming.

Example: rpc GetOrder(GetOrderRequest) returns (Order);

Diagram / flow: Client -> REST/JSON OR gRPC/Protobuf

Syntax

rpc GetOrder(GetOrderRequest) returns (Order);

// Architecture flow
Client -> REST/JSON OR gRPC/Protobuf

Example

rpc GetOrder(GetOrderRequest) returns (Order); // Architecture flow Client -> REST/JSON OR gRPC/Protobuf

Code example

rpc GetOrder(GetOrderRequest) returns (Order);

// Architecture flow
Client -> REST/JSON OR gRPC/Protobuf

Diagram

Diagram / flow: Client -> REST/JSON OR gRPC/Protobuf

Key Points

  • REST commonly uses HTTP resources and JSON; gRPC uses protobuf contracts and HTTP/2, often suited to internal typed RPC and streaming.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q47Networking

What is service mesh?

A service mesh uses proxies and a control plane to standardize service-to-service traffic security, telemetry, and routing

Answer

A service mesh uses proxies and a control plane to standardize service-to-service traffic security, telemetry, and routing; it adds operational overhead.

Example: mTLS between service sidecars

Diagram / flow: Service A -> Proxy A -> Proxy B -> Service B

Syntax

mTLS between service sidecars

// Architecture flow
Service A -> Proxy A -> Proxy B -> Service B

Example

mTLS between service sidecars // Architecture flow Service A -> Proxy A -> Proxy B -> Service B

Code example

mTLS between service sidecars

// Architecture flow
Service A -> Proxy A -> Proxy B -> Service B

Diagram

Diagram / flow: Service A -> Proxy A -> Proxy B -> Service B

Key Points

  • A service mesh uses proxies and a control plane to standardize service-to-service traffic security, telemetry, and routing; it adds operational overhead.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q48Security

What is zero-trust security?

Zero trust authenticates and authorizes each access regardless of network location

Answer

Zero trust authenticates and authorizes each access regardless of network location; use identity, least privilege, and short-lived credentials.

Example: allow if principal=orders && action=inventory.read

Diagram / flow: Identity -> Policy -> Service

Syntax

allow if principal=orders && action=inventory.read

// Architecture flow
Identity -> Policy -> Service

Example

allow if principal=orders && action=inventory.read // Architecture flow Identity -> Policy -> Service

Code example

allow if principal=orders && action=inventory.read

// Architecture flow
Identity -> Policy -> Service

Diagram

Diagram / flow: Identity -> Policy -> Service

Key Points

  • Zero trust authenticates and authorizes each access regardless of network location; use identity, least privilege, and short-lived credentials.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q49Security

OAuth 2.0 vs OpenID Connect?

OAuth 2.0 delegates API authorization

Answer

OAuth 2.0 delegates API authorization; OpenID Connect adds identity authentication with an ID token on top of OAuth.

Example: Authorization: Bearer <access_token>

Diagram / flow: User -> IdP -> Access Token -> API

Syntax

Authorization: Bearer <access_token>

// Architecture flow
User -> IdP -> Access Token -> API

Example

Authorization: Bearer <access_token> // Architecture flow User -> IdP -> Access Token -> API

Code example

Authorization: Bearer <access_token>

// Architecture flow
User -> IdP -> Access Token -> API

Diagram

Diagram / flow: User -> IdP -> Access Token -> API

Key Points

  • OAuth 2.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q50Security

What is JWT validation?

Validate signature, issuer, audience, expiry, and allowed algorithm before trusting claims

Answer

Validate signature, issuer, audience, expiry, and allowed algorithm before trusting claims; do not treat a decoded token as verified.

Example: verify(jwt,{issuer:'https://idp',audience:'orders-api'})

Diagram / flow: Client -> JWT Validator -> Endpoint

Syntax

verify(jwt,{issuer:'https://idp',audience:'orders-api'})

// Architecture flow
Client -> JWT Validator -> Endpoint

Example

verify(jwt,{issuer:'https://idp',audience:'orders-api'}) // Architecture flow Client -> JWT Validator -> Endpoint

Code example

verify(jwt,{issuer:'https://idp',audience:'orders-api'})

// Architecture flow
Client -> JWT Validator -> Endpoint

Diagram

Diagram / flow: Client -> JWT Validator -> Endpoint

Key Points

  • Validate signature, issuer, audience, expiry, and allowed algorithm before trusting claims; do not treat a decoded token as verified.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q51Security

What is mTLS?

Mutual TLS authenticates both ends of a connection using certificates, useful for workload identity inside a trusted PKI.

Answer

Mutual TLS authenticates both ends of a connection using certificates, useful for workload identity inside a trusted PKI.

Example: client cert + server cert -> TLS handshake

Diagram / flow: Service A <== mTLS ==> Service B

Syntax

client cert + server cert -> TLS handshake

// Architecture flow
Service A <== mTLS ==> Service B

Example

client cert + server cert -> TLS handshake // Architecture flow Service A <== mTLS ==> Service B

Code example

client cert + server cert -> TLS handshake

// Architecture flow
Service A <== mTLS ==> Service B

Diagram

Example: client cert + server cert -> TLS handshake

Key Points

  • Mutual TLS authenticates both ends of a connection using certificates, useful for workload identity inside a trusted PKI.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q52Security

What is secrets management?

Store credentials in a managed secret store, restrict access, rotate secrets, and avoid embedding them in images or source control.

Answer

Store credentials in a managed secret store, restrict access, rotate secrets, and avoid embedding them in images or source control.

Example: DB_PASSWORD <- secret manager at runtime

Diagram / flow: Pod -> Identity -> Secret Store

Syntax

DB_PASSWORD <- secret manager at runtime

// Architecture flow
Pod -> Identity -> Secret Store

Example

DB_PASSWORD <- secret manager at runtime // Architecture flow Pod -> Identity -> Secret Store

Code example

DB_PASSWORD <- secret manager at runtime

// Architecture flow
Pod -> Identity -> Secret Store

Diagram

Diagram / flow: Pod -> Identity -> Secret Store

Key Points

  • Store credentials in a managed secret store, restrict access, rotate secrets, and avoid embedding them in images or source control.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q53Observability

What is observability?

Observability combines metrics, logs, and traces to explain internal behavior from outputs

Answer

Observability combines metrics, logs, and traces to explain internal behavior from outputs; correlate using trace and request IDs.

Example: trace_id=abc123 span=payment.charge duration_ms=42

Diagram / flow: Service -> Metrics / Logs / Traces

Syntax

trace_id=abc123 span=payment.charge duration_ms=42

// Architecture flow
Service -> Metrics / Logs / Traces

Example

trace_id=abc123 span=payment.charge duration_ms=42 // Architecture flow Service -> Metrics / Logs / Traces

Code example

trace_id=abc123 span=payment.charge duration_ms=42

// Architecture flow
Service -> Metrics / Logs / Traces

Diagram

Diagram / flow: Service -> Metrics / Logs / Traces

Key Points

  • Observability combines metrics, logs, and traces to explain internal behavior from outputs; correlate using trace and request IDs.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q54Observability

What is distributed tracing?

Distributed tracing links spans across service boundaries to reveal critical path latency and failures

Answer

Distributed tracing links spans across service boundaries to reveal critical path latency and failures; propagate trace context.

Example: traceparent: 00-<traceid>-<spanid>-01

Diagram / flow: Gateway -> Orders(span) -> Billing(span)

Syntax

traceparent: 00-<traceid>-<spanid>-01

// Architecture flow
Gateway -> Orders(span) -> Billing(span)

Example

traceparent: 00-<traceid>-<spanid>-01 // Architecture flow Gateway -> Orders(span) -> Billing(span)

Code example

traceparent: 00-<traceid>-<spanid>-01

// Architecture flow
Gateway -> Orders(span) -> Billing(span)

Diagram

Diagram / flow: Gateway -> Orders(span) -> Billing(span)

Key Points

  • Distributed tracing links spans across service boundaries to reveal critical path latency and failures; propagate trace context.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q55Reliability

What are SLI, SLO, and SLA?

SLI is a measured indicator, SLO its target, and SLA a contractual commitment with consequences

Answer

SLI is a measured indicator, SLO its target, and SLA a contractual commitment with consequences; define an error budget for SLO breaches.

Example: SLO: 99.9% successful requests over 30 days

Diagram / flow: Requests -> SLI -> SLO -> Error budget

Syntax

SLO: 99.9% successful requests over 30 days

// Architecture flow
Requests -> SLI -> SLO -> Error budget

Example

SLO: 99.9% successful requests over 30 days // Architecture flow Requests -> SLI -> SLO -> Error budget

Code example

SLO: 99.9% successful requests over 30 days

// Architecture flow
Requests -> SLI -> SLO -> Error budget

Diagram

Diagram / flow: Requests -> SLI -> SLO -> Error budget

Key Points

  • SLI is a measured indicator, SLO its target, and SLA a contractual commitment with consequences; define an error budget for SLO breaches.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q82Distributed services

What is service discovery in a microservices system?

Service discovery lets clients or proxies locate healthy service instances without hardcoding ephemeral addresses. Discovery may be client-side o

Answer

Service discovery lets clients or proxies locate healthy service instances without hardcoding ephemeral addresses. Discovery may be client-side or server-side and is often integrated with a platform or service mesh.

Example: Orders API → DNS/service registry → currently healthy Payments endpoint.

Diagram / flow: Caller → service name → discovery layer → healthy instance

Syntax

service-name → registry/DNS → healthy endpoint

Example

Orders API → DNS/service registry → currently healthy Payments endpoint.

Code example

service-name → registry/DNS → healthy endpoint

Diagram

Caller → service name → discovery layer → healthy instance

Key Points

  • Service discovery lets clients or proxies locate healthy service instances without hardcoding ephemeral addresses.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q85Caching

Why is cache invalidation difficult in distributed systems?

Cached copies can become stale after writes, and invalidation messages can be delayed or lost. Define freshness requirements, use bounded TTLs an

Answer

Cached copies can become stale after writes, and invalidation messages can be delayed or lost. Define freshness requirements, use bounded TTLs and versioning, and consider outbox-driven invalidation when stronger delivery guarantees are needed.

Example: Update product price → commit DB and outbox event → consumer invalidates product key.

Diagram / flow: Database commit → event delivery → cache eviction; TTL bounds stale lifetime

Syntax

write DB → publish invalidation event → evict/update cache

Example

Update product price → commit DB and outbox event → consumer invalidates product key.

Code example

write DB → publish invalidation event → evict/update cache

Diagram

Database commit → event delivery → cache eviction; TTL bounds stale lifetime

Key Points

  • Cached copies can become stale after writes, and invalidation messages can be delayed or lost.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q86Caching

How do you choose Redis data structures?

Strings suit simple values/counters, hashes suit field collections, sets suit uniqueness, sorted sets suit ranking, and streams support append-or

Answer

Strings suit simple values/counters, hashes suit field collections, sets suit uniqueness, sorted sets suit ranking, and streams support append-oriented event consumption. Select by operations and memory behavior, not familiarity alone.

Example: Use a sorted set for a leaderboard ranked by score.

Diagram / flow: Application operation → appropriate Redis structure → query/update

Syntax

SET key value; HSET user:1 name Ava; ZADD rank 10 user1

Example

Use a sorted set for a leaderboard ranked by score.

Code example

SET key value; HSET user:1 name Ava; ZADD rank 10 user1

Diagram

Application operation → appropriate Redis structure → query/update

Key Points

  • Strings suit simple values/counters, hashes suit field collections, sets suit uniqueness, sorted sets suit ranking, and streams support append-oriented event consumption.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q90Resilience

Explain the Bulkhead pattern.

Bulkheads isolate resource pools or dependencies so saturation in one area does not consume all capacity. Separate connection pools, concurrency

Answer

Bulkheads isolate resource pools or dependencies so saturation in one area does not consume all capacity. Separate connection pools, concurrency limits, and queues can prevent cascading failures.

Example: Limit report-generation concurrency separately from checkout traffic.

Diagram / flow: Checkout pool isolated from reporting pool; reporting saturation does not exhaust checkout

Syntax

perDependencyConcurrencyLimit = N

Example

Limit report-generation concurrency separately from checkout traffic.

Code example

perDependencyConcurrencyLimit = N

Diagram

Checkout pool isolated from reporting pool; reporting saturation does not exhaust checkout

Key Points

  • Bulkheads isolate resource pools or dependencies so saturation in one area does not consume all capacity.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q91Resilience

How should retries with exponential backoff be designed?

Retry only transient failures and operations safe to repeat, cap attempts, add jitter, and honor deadlines/cancellation. Unbounded or synchronize

Answer

Retry only transient failures and operations safe to repeat, cap attempts, add jitter, and honor deadlines/cancellation. Unbounded or synchronized retries can amplify an outage.

Example: Retry a transient 503 up to three times with randomized increasing delay.

Diagram / flow: Transient error → bounded backoff+jitter → retry until success or budget exhausted

Syntax

delay = min(cap, base × 2^attempt) + jitter

Example

Retry a transient 503 up to three times with randomized increasing delay.

Code example

delay = min(cap, base × 2^attempt) + jitter

Diagram

Transient error → bounded backoff+jitter → retry until success or budget exhausted

Key Points

  • Retry only transient failures and operations safe to repeat, cap attempts, add jitter, and honor deadlines/cancellation.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q93Resilience

What are the states of a circuit breaker?

Closed allows calls while tracking failures; open rejects calls temporarily; half-open permits limited probes. Configure thresholds and recovery

Answer

Closed allows calls while tracking failures; open rejects calls temporarily; half-open permits limited probes. Configure thresholds and recovery windows using observed dependency behavior.

Example: Repeated payment provider failures open the circuit; a later probe tests recovery.

Diagram / flow: Failures exceed threshold → Open → wait → Half-open probe → recover or reopen

Syntax

Closed → Open → Half-open → Closed/Open

Example

Repeated payment provider failures open the circuit; a later probe tests recovery.

Code example

Closed → Open → Half-open → Closed/Open

Diagram

Failures exceed threshold → Open → wait → Half-open probe → recover or reopen

Key Points

  • Closed allows calls while tracking failures; open rejects calls temporarily; half-open permits limited probes.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q96Messaging

How can a consumer safely handle duplicate messages?

Assign a stable message ID and record processed IDs atomically with the business change. If the ID has already been applied, acknowledge without

Answer

Assign a stable message ID and record processed IDs atomically with the business change. If the ID has already been applied, acknowledge without repeating the side effect.

Example: Unique constraint on ProcessedMessages.MessageId prevents duplicate application.

Diagram / flow: Message → deduplication check → apply transaction once → acknowledge

Syntax

if processed(messageId) then ack else apply + record atomically

Example

Unique constraint on ProcessedMessages.MessageId prevents duplicate application.

Code example

if processed(messageId) then ack else apply + record atomically

Diagram

Message → deduplication check → apply transaction once → acknowledge

Key Points

  • Assign a stable message ID and record processed IDs atomically with the business change.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q99Resilience

How should distributed APIs implement rate limiting?

Choose a key such as API consumer, user, or tenant; select fixed-window, sliding-window, token-bucket, or leaky-bucket semantics; return 429 with

Answer

Choose a key such as API consumer, user, or tenant; select fixed-window, sliding-window, token-bucket, or leaky-bucket semantics; return 429 with retry guidance. Multi-instance systems need shared or coordinated state when global limits matter.

Example: Tenant A has 100 requests/minute across all API instances, not 100 per instance.

Diagram / flow: Request identity → shared limiter state → allow or HTTP 429

Syntax

token bucket: tokens = min(capacity, tokens + elapsed × refillRate)

Example

Tenant A has 100 requests/minute across all API instances, not 100 per instance.

Code example

token bucket: tokens = min(capacity, tokens + elapsed × refillRate)

Diagram

Request identity → shared limiter state → allow or HTTP 429

Key Points

  • Choose a key such as API consumer, user, or tenant; select fixed-window, sliding-window, token-bucket, or leaky-bucket semantics; return 429 with retry guidance.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q101Scalability

What is backpressure in a distributed service?

Backpressure communicates that a consumer cannot safely accept more work. Bounded queues, demand-aware streams, and producer throttling keep memo

Answer

Backpressure communicates that a consumer cannot safely accept more work. Bounded queues, demand-aware streams, and producer throttling keep memory and latency from growing without bound.

Example: A worker pool slows message intake when its queue reaches capacity.

Diagram / flow: Producer → bounded queue → workers; full queue slows or rejects producer

Syntax

boundedQueue(capacity=N); producer waits or rejects when full

Example

A worker pool slows message intake when its queue reaches capacity.

Code example

boundedQueue(capacity=N); producer waits or rejects when full

Diagram

Producer → bounded queue → workers; full queue slows or rejects producer

Key Points

  • Backpressure communicates that a consumer cannot safely accept more work.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q102Architecture

What problems can a service mesh solve, and what are its trade-offs?

A service mesh can centralize service-to-service mTLS, traffic policy, telemetry, and retries at the proxy layer. It adds sidecar/proxy resources

Answer

A service mesh can centralize service-to-service mTLS, traffic policy, telemetry, and retries at the proxy layer. It adds sidecar/proxy resources, configuration complexity, and another operational control plane.

Example: Apply mTLS and traffic shifting consistently without duplicating all transport code in services.

Diagram / flow: Service A → proxy/control policies → proxy → Service B

Syntax

service A proxy ⇄ mTLS ⇄ service B proxy

Example

Apply mTLS and traffic shifting consistently without duplicating all transport code in services.

Code example

service A proxy ⇄ mTLS ⇄ service B proxy

Diagram

Service A → proxy/control policies → proxy → Service B

Key Points

  • A service mesh can centralize service-to-service mTLS, traffic policy, telemetry, and retries at the proxy layer.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q104Microservices

Why do microservices often own their databases?

Database ownership limits schema coupling and lets services evolve independently. Cross-service queries and transactions become harder, so use AP

Answer

Database ownership limits schema coupling and lets services evolve independently. Cross-service queries and transactions become harder, so use APIs, events, and read projections rather than direct shared-table access.

Example: Orders publishes OrderCreated; Analytics builds its own read projection.

Diagram / flow: Orders Service → Orders DB; Billing Service → Billing DB; events connect them

Syntax

Service A → database A; Service B → database B

Example

Orders publishes OrderCreated; Analytics builds its own read projection.

Code example

Service A → database A; Service B → database B

Diagram

Orders Service → Orders DB; Billing Service → Billing DB; events connect them

Key Points

  • Database ownership limits schema coupling and lets services evolve independently.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q105Observability

How does distributed tracing help debug latency?

Trace context connects spans across service boundaries. Traces reveal where time is spent and which dependency adds latency; sampling, propagatio

Answer

Trace context connects spans across service boundaries. Traces reveal where time is spent and which dependency adds latency; sampling, propagation, and sensitive-data controls must be configured.

Example: Gateway span contains order, inventory, and payment child spans; payment span shows delay.

Diagram / flow: Gateway span → Orders span → Inventory/Payment spans

Syntax

traceId + parentSpanId propagated in request context

Example

Gateway span contains order, inventory, and payment child spans; payment span shows delay.

Code example

traceId + parentSpanId propagated in request context

Diagram

Gateway span → Orders span → Inventory/Payment spans

Key Points

  • Trace context connects spans across service boundaries.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q107Resilience

How should a service shut down gracefully?

Stop accepting new work, mark the instance unready, allow in-flight requests or messages to finish within a deadline, then release resources. Han

Answer

Stop accepting new work, mark the instance unready, allow in-flight requests or messages to finish within a deadline, then release resources. Handle cancellation and forced termination as fallbacks.

Example: Worker stops pulling messages, finishes current handler, commits acknowledgement, and exits.

Diagram / flow: Termination signal → stop intake → drain in-flight work → shutdown

Syntax

SIGTERM → readiness false → drain → dispose resources

Example

Worker stops pulling messages, finishes current handler, commits acknowledgement, and exits.

Code example

SIGTERM → readiness false → drain → dispose resources

Diagram

Termination signal → stop intake → drain in-flight work → shutdown

Key Points

  • Stop accepting new work, mark the instance unready, allow in-flight requests or messages to finish within a deadline, then release resources.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q109API design

How should API versioning be handled in distributed systems?

Version public contracts deliberately and keep old and new versions compatible during migration. Versioning can use URL paths, headers, or media

Answer

Version public contracts deliberately and keep old and new versions compatible during migration. Versioning can use URL paths, headers, or media types; communicate deprecation and monitor old-version usage.

Example: Deploy v2 alongside v1, migrate clients gradually, then retire v1 after usage falls.

Diagram / flow: Client versions → routing/compatibility layer → matching API contract

Syntax

GET /v2/orders or version header

Example

Deploy v2 alongside v1, migrate clients gradually, then retire v1 after usage falls.

Code example

GET /v2/orders or version header

Diagram

Client versions → routing/compatibility layer → matching API contract

Key Points

  • Version public contracts deliberately and keep old and new versions compatible during migration.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q111Messaging

When would you choose a work queue versus an event stream?

A work queue distributes tasks among workers, often with one successful consumer per message. A retained event stream supports replay and multipl

Answer

A work queue distributes tasks among workers, often with one successful consumer per message. A retained event stream supports replay and multiple independent consumer groups; semantics depend on the platform.

Example: Send image-resize jobs to a queue; publish OrderCreated to a retained event stream for multiple projections.

Diagram / flow: Producer → queue/workers OR append-only stream → independent consumer groups

Syntax

Queue: task → worker; Stream: event log → consumer groups

Example

Send image-resize jobs to a queue; publish OrderCreated to a retained event stream for multiple projections.

Code example

Queue: task → worker; Stream: event log → consumer groups

Diagram

Producer → queue/workers OR append-only stream → independent consumer groups

Key Points

  • A work queue distributes tasks among workers, often with one successful consumer per message.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q114Data architecture

What trade-offs come with database read replicas?

Read replicas can scale read-heavy workloads but may lag behind the primary. Route consistency-sensitive reads to the primary or use an explicit

Answer

Read replicas can scale read-heavy workloads but may lag behind the primary. Route consistency-sensitive reads to the primary or use an explicit read-your-writes strategy when replica lag is unacceptable.

Example: After changing profile data, read from primary until replication catches up.

Diagram / flow: Write → primary DB → replication lag → read replica

Syntax

write primary → async replication → read replica

Example

After changing profile data, read from primary until replication catches up.

Code example

write primary → async replication → read replica

Diagram

Write → primary DB → replication lag → read replica

Key Points

  • Read replicas can scale read-heavy workloads but may lag behind the primary.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q116Scalability

How do you estimate service capacity?

Measure representative throughput and latency under realistic load, identify bottlenecks, and apply headroom for bursts and failures. Little's La

Answer

Measure representative throughput and latency under realistic load, identify bottlenecks, and apply headroom for bursts and failures. Little's Law relates concurrency, throughput, and latency; estimates must be validated by load tests.

Example: At 200 requests/s and 0.15s average latency, expected in-flight requests are about 30.

Diagram / flow: Load test → measure throughput/latency/resource use → capacity model → headroom

Syntax

concurrency ≈ throughput × average latency

Example

At 200 requests/s and 0.15s average latency, expected in-flight requests are about 30.

Code example

concurrency ≈ throughput × average latency

Diagram

Load test → measure throughput/latency/resource use → capacity model → headroom

Key Points

  • Measure representative throughput and latency under realistic load, identify bottlenecks, and apply headroom for bursts and failures.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q117Resilience

What is graceful degradation?

The system preserves core functionality when optional dependencies fail, such as hiding recommendations while checkout remains available. Define

Answer

The system preserves core functionality when optional dependencies fail, such as hiding recommendations while checkout remains available. Define criticality and fallback behavior in advance; avoid silently returning misleading data.

Example: Checkout returns order confirmation even when a non-critical personalization service is unavailable.

Diagram / flow: Dependency fails → fallback/default for optional feature → core flow continues

Syntax

if recommendation service fails → omit recommendation panel

Example

Checkout returns order confirmation even when a non-critical personalization service is unavailable.

Code example

if recommendation service fails → omit recommendation panel

Diagram

Dependency fails → fallback/default for optional feature → core flow continues

Key Points

  • The system preserves core functionality when optional dependencies fail, such as hiding recommendations while checkout remains available.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q119Architecture

What is an anti-corruption layer?

An anti-corruption layer translates an external or legacy model into the domain model so upstream concepts and inconsistencies do not leak into a

Answer

An anti-corruption layer translates an external or legacy model into the domain model so upstream concepts and inconsistencies do not leak into a new service. It adds code but protects domain boundaries.

Example: Convert legacy status codes and date formats at the integration boundary.

Diagram / flow: Legacy API → translation layer → clean domain model

Syntax

Legacy DTO → mapper/adapter → domain command

Example

Convert legacy status codes and date formats at the integration boundary.

Code example

Legacy DTO → mapper/adapter → domain command

Diagram

Legacy API → translation layer → clean domain model

Key Points

  • An anti-corruption layer translates an external or legacy model into the domain model so upstream concepts and inconsistencies do not leak into a new service.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q56Scalability

What is autoscaling?

Autoscaling adjusts replicas or resources from demand signals

Answer

Autoscaling adjusts replicas or resources from demand signals; CPU alone may miss queue or I/O saturation, so scale from workload-specific metrics.

Example: HPA target CPU=65%; min=3 max=20

Diagram / flow: Metrics -> Autoscaler -> Pods +/-

Syntax

HPA target CPU=65%; min=3 max=20

// Architecture flow
Metrics -> Autoscaler -> Pods +/-

Example

HPA target CPU=65%; min=3 max=20 // Architecture flow Metrics -> Autoscaler -> Pods +/-

Code example

HPA target CPU=65%; min=3 max=20

// Architecture flow
Metrics -> Autoscaler -> Pods +/-

Diagram

Diagram / flow: Metrics -> Autoscaler -> Pods +/-

Key Points

  • Autoscaling adjusts replicas or resources from demand signals; CPU alone may miss queue or I/O saturation, so scale from workload-specific metrics.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q57Deployment

What is blue-green deployment?

Blue-green keeps two production environments and switches traffic after validating the new one, enabling rapid rollback but doubling temporary capacity.

Answer

Blue-green keeps two production environments and switches traffic after validating the new one, enabling rapid rollback but doubling temporary capacity.

Example: LB target: blue -> green

Diagram / flow: LB -> Blue OR Green

Syntax

LB target: blue -> green

// Architecture flow
LB -> Blue OR Green

Example

LB target: blue -> green // Architecture flow LB -> Blue OR Green

Code example

LB target: blue -> green

// Architecture flow
LB -> Blue OR Green

Diagram

Example: LB target: blue -> green

Key Points

  • Blue-green keeps two production environments and switches traffic after validating the new one, enabling rapid rollback but doubling temporary capacity.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q58Deployment

What is canary deployment?

Canary routes a small percentage to a new version, monitors guardrails, and gradually increases traffic if healthy.

Answer

Canary routes a small percentage to a new version, monitors guardrails, and gradually increases traffic if healthy.

Example: v1:95%; v2:5%

Diagram / flow: Router -> v1 95% / v2 5%

Syntax

v1:95%; v2:5%

// Architecture flow
Router -> v1 95% / v2 5%

Example

v1:95%; v2:5% // Architecture flow Router -> v1 95% / v2 5%

Code example

v1:95%; v2:5%

// Architecture flow
Router -> v1 95% / v2 5%

Diagram

Diagram / flow: Router -> v1 95% / v2 5%

Key Points

  • Canary routes a small percentage to a new version, monitors guardrails, and gradually increases traffic if healthy.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q59Messaging

What is backpressure?

Backpressure slows producers or rejects work when consumers cannot keep up, protecting memory and latency.

Answer

Backpressure slows producers or rejects work when consumers cannot keep up, protecting memory and latency.

Example: HTTP 429 or bounded_queue.tryEnqueue(job)

Diagram / flow: Producer -> Bounded Queue -> Consumers

Syntax

HTTP 429 or bounded_queue.tryEnqueue(job)

// Architecture flow
Producer -> Bounded Queue -> Consumers

Example

HTTP 429 or bounded_queue.tryEnqueue(job) // Architecture flow Producer -> Bounded Queue -> Consumers

Code example

HTTP 429 or bounded_queue.tryEnqueue(job)

// Architecture flow
Producer -> Bounded Queue -> Consumers

Diagram

Diagram / flow: Producer -> Bounded Queue -> Consumers

Key Points

  • Backpressure slows producers or rejects work when consumers cannot keep up, protecting memory and latency.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q60Messaging

What is a dead-letter queue?

A dead-letter queue holds messages that repeatedly fail processing for inspection, repair, and replay with safeguards.

Answer

A dead-letter queue holds messages that repeatedly fail processing for inspection, repair, and replay with safeguards.

Example: maxRetries=5 -> DLQ

Diagram / flow: Main Queue -> Worker -> DLQ on poison

Syntax

maxRetries=5 -> DLQ

// Architecture flow
Main Queue -> Worker -> DLQ on poison

Example

maxRetries=5 -> DLQ // Architecture flow Main Queue -> Worker -> DLQ on poison

Code example

maxRetries=5 -> DLQ

// Architecture flow
Main Queue -> Worker -> DLQ on poison

Diagram

Example: maxRetries=5 -> DLQ

Key Points

  • A dead-letter queue holds messages that repeatedly fail processing for inspection, repair, and replay with safeguards.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q61Messaging

What is schema evolution for events?

Evolve events compatibly by adding optional fields, maintaining versioned contracts, and validating consumers before removing fields.

Answer

Evolve events compatibly by adding optional fields, maintaining versioned contracts, and validating consumers before removing fields.

Example: {type:'OrderPlaced',version:2,currency:'USD'}

Diagram / flow: Producer v2 -> Schema Registry -> Consumers

Syntax

{type:'OrderPlaced',version:2,currency:'USD'}

// Architecture flow
Producer v2 -> Schema Registry -> Consumers

Example

{type:'OrderPlaced',version:2,currency:'USD'} // Architecture flow Producer v2 -> Schema Registry -> Consumers

Code example

{type:'OrderPlaced',version:2,currency:'USD'}

// Architecture flow
Producer v2 -> Schema Registry -> Consumers

Diagram

Diagram / flow: Producer v2 -> Schema Registry -> Consumers

Key Points

  • Evolve events compatibly by adding optional fields, maintaining versioned contracts, and validating consumers before removing fields.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q62Concurrency

What is a distributed lock?

A distributed lock coordinates exclusive work across nodes but requires lease expiry and fencing tokens to prevent stale owners acting after pause.

Answer

A distributed lock coordinates exclusive work across nodes but requires lease expiry and fencing tokens to prevent stale owners acting after pause.

Example: SET lock:job token NX PX 30000

Diagram / flow: Worker A -> Lock Store <- Worker B

Syntax

SET lock:job token NX PX 30000

// Architecture flow
Worker A -> Lock Store <- Worker B

Example

SET lock:job token NX PX 30000 // Architecture flow Worker A -> Lock Store <- Worker B

Code example

SET lock:job token NX PX 30000

// Architecture flow
Worker A -> Lock Store <- Worker B

Diagram

Diagram / flow: Worker A -> Lock Store <- Worker B

Key Points

  • A distributed lock coordinates exclusive work across nodes but requires lease expiry and fencing tokens to prevent stale owners acting after pause.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q63Concurrency

What is optimistic concurrency control?

Optimistic concurrency uses a version or compare-and-swap to reject stale updates without holding long-lived locks.

Answer

Optimistic concurrency uses a version or compare-and-swap to reject stale updates without holding long-lived locks.

Example: UPDATE items SET qty=qty-1,version=version+1 WHERE id=1 AND version=7;

Diagram / flow: Read v7 -> Conditional write -> Success/Conflict

Syntax

UPDATE items SET qty=qty-1,version=version+1 WHERE id=1 AND version=7;

// Architecture flow
Read v7 -> Conditional write -> Success/Conflict

Example

UPDATE items SET qty=qty-1,version=version+1 WHERE id=1 AND version=7; // Architecture flow Read v7 -> Conditional write -> Success/Conflict

Code example

UPDATE items SET qty=qty-1,version=version+1 WHERE id=1 AND version=7;

// Architecture flow
Read v7 -> Conditional write -> Success/Conflict

Diagram

Diagram / flow: Read v7 -> Conditional write -> Success/Conflict

Key Points

  • Optimistic concurrency uses a version or compare-and-swap to reject stale updates without holding long-lived locks.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q64Distributed Systems

What is leader election?

Leader election chooses one coordinator for a task

Answer

Leader election chooses one coordinator for a task; leadership requires leases or consensus and fencing to handle split-brain risks.

Example: lease(owner='node-2',term=18)

Diagram / flow: Nodes -> Election -> Leader

Syntax

lease(owner='node-2',term=18)

// Architecture flow
Nodes -> Election -> Leader

Example

lease(owner='node-2',term=18) // Architecture flow Nodes -> Election -> Leader

Code example

lease(owner='node-2',term=18)

// Architecture flow
Nodes -> Election -> Leader

Diagram

Diagram / flow: Nodes -> Election -> Leader

Key Points

  • Leader election chooses one coordinator for a task; leadership requires leases or consensus and fencing to handle split-brain risks.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q65Scalability

What is consistent hashing?

Consistent hashing maps keys and nodes to a ring, reducing key movement when membership changes

Answer

Consistent hashing maps keys and nodes to a ring, reducing key movement when membership changes; virtual nodes improve distribution.

Example: node = ring.successor(hash(key))

Diagram / flow: Hash ring: N1 -> K -> N2 -> N3

Syntax

node = ring.successor(hash(key))

// Architecture flow
Hash ring: N1 -> K -> N2 -> N3

Example

node = ring.successor(hash(key)) // Architecture flow Hash ring: N1 -> K -> N2 -> N3

Code example

node = ring.successor(hash(key))

// Architecture flow
Hash ring: N1 -> K -> N2 -> N3

Diagram

Diagram / flow: Hash ring: N1 -> K -> N2 -> N3

Key Points

  • Consistent hashing maps keys and nodes to a ring, reducing key movement when membership changes; virtual nodes improve distribution.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q66Data

What is the hot partition problem?

A hot partition occurs when a skewed key receives disproportionate load

Answer

A hot partition occurs when a skewed key receives disproportionate load; mitigate with better keys, salting, caching, or isolated capacity.

Example: partition_key = tenant_id + ':' + bucket

Diagram / flow: Traffic -> Hot Shard (overload)

Syntax

partition_key = tenant_id + ':' + bucket

// Architecture flow
Traffic -> Hot Shard (overload)

Example

partition_key = tenant_id + ':' + bucket // Architecture flow Traffic -> Hot Shard (overload)

Code example

partition_key = tenant_id + ':' + bucket

// Architecture flow
Traffic -> Hot Shard (overload)

Diagram

Diagram / flow: Traffic -> Hot Shard (overload)

Key Points

  • A hot partition occurs when a skewed key receives disproportionate load; mitigate with better keys, salting, caching, or isolated capacity.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q67Design Exercise

How do you design a URL shortener?

Generate collision-resistant short codes, persist code-to-URL mapping, cache popular redirects, and add abuse controls and expiration.

Answer

Generate collision-resistant short codes, persist code-to-URL mapping, cache popular redirects, and add abuse controls and expiration.

Example: POST /links {url:'https://example.com'} -> {code:'aB92x'}

Diagram / flow: Client -> API -> ID generator -> DB -> Cache -> Redirect

Syntax

POST /links {url:'https://example.com'} -> {code:'aB92x'}

// Architecture flow
Client -> API -> ID generator -> DB -> Cache -> Redirect

Example

POST /links {url:'https://example.com'} -> {code:'aB92x'} // Architecture flow Client -> API -> ID generator -> DB -> Cache -> Redirect

Code example

POST /links {url:'https://example.com'} -> {code:'aB92x'}

// Architecture flow
Client -> API -> ID generator -> DB -> Cache -> Redirect

Diagram

Example: POST /links {url:'https://example.com'} -> {code:'aB92x'}

Key Points

  • Generate collision-resistant short codes, persist code-to-URL mapping, cache popular redirects, and add abuse controls and expiration.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q68Design Exercise

How do you design a notification system?

Accept requests durably, fan out to channels asynchronously, enforce user preferences, deduplicate sends, and monitor provider failures.

Answer

Accept requests durably, fan out to channels asynchronously, enforce user preferences, deduplicate sends, and monitor provider failures.

Example: NotificationRequested -> EmailWorker / PushWorker

Diagram / flow: API -> Queue -> Email / SMS / Push

Syntax

NotificationRequested -> EmailWorker / PushWorker

// Architecture flow
API -> Queue -> Email / SMS / Push

Example

NotificationRequested -> EmailWorker / PushWorker // Architecture flow API -> Queue -> Email / SMS / Push

Code example

NotificationRequested -> EmailWorker / PushWorker

// Architecture flow
API -> Queue -> Email / SMS / Push

Diagram

Example: NotificationRequested -> EmailWorker / PushWorker

Key Points

  • Accept requests durably, fan out to channels asynchronously, enforce user preferences, deduplicate sends, and monitor provider failures.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q69Design Exercise

How do you design an API rate limiter?

Use token bucket for controlled bursts

Answer

Use token bucket for controlled bursts; store counters or tokens atomically in a shared store when enforcing across instances.

Example: tokens=min(capacity,tokens+rate*elapsed); allow=tokens>=1

Diagram / flow: Client -> Gateway -> Redis tokens -> API

Syntax

tokens=min(capacity,tokens+rate*elapsed); allow=tokens>=1

// Architecture flow
Client -> Gateway -> Redis tokens -> API

Example

tokens=min(capacity,tokens+rate*elapsed); allow=tokens>=1 // Architecture flow Client -> Gateway -> Redis tokens -> API

Code example

tokens=min(capacity,tokens+rate*elapsed); allow=tokens>=1

// Architecture flow
Client -> Gateway -> Redis tokens -> API

Diagram

Diagram / flow: Client -> Gateway -> Redis tokens -> API

Key Points

  • Use token bucket for controlled bursts; store counters or tokens atomically in a shared store when enforcing across instances.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q70Design Exercise

How do you design an e-commerce order workflow?

Use an order state machine, inventory reservations, payment idempotency, and saga compensation

Answer

Use an order state machine, inventory reservations, payment idempotency, and saga compensation; make fulfillment asynchronous.

Example: PENDING -> RESERVED -> PAID -> SHIPPED

Diagram / flow: Order -> Inventory -> Payment -> Fulfillment

Syntax

PENDING -> RESERVED -> PAID -> SHIPPED

// Architecture flow
Order -> Inventory -> Payment -> Fulfillment

Example

PENDING -> RESERVED -> PAID -> SHIPPED // Architecture flow Order -> Inventory -> Payment -> Fulfillment

Code example

PENDING -> RESERVED -> PAID -> SHIPPED

// Architecture flow
Order -> Inventory -> Payment -> Fulfillment

Diagram

Example: PENDING -> RESERVED -> PAID -> SHIPPED

Key Points

  • Use an order state machine, inventory reservations, payment idempotency, and saga compensation; make fulfillment asynchronous.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q71Design Exercise

How do you design a chat service?

Use persistent connections for delivery, partition conversations, persist messages before acknowledging, and track offline delivery cursors.

Answer

Use persistent connections for delivery, partition conversations, persist messages before acknowledging, and track offline delivery cursors.

Example: WS SEND {conversationId:'c1',message:'hi',clientId:'m1'}

Diagram / flow: Clients <-> WebSocket Gateway -> Chat Service -> Store

Syntax

WS SEND {conversationId:'c1',message:'hi',clientId:'m1'}

// Architecture flow
Clients <-> WebSocket Gateway -> Chat Service -> Store

Example

WS SEND {conversationId:'c1',message:'hi',clientId:'m1'} // Architecture flow Clients <-> WebSocket Gateway -> Chat Service -> Store

Code example

WS SEND {conversationId:'c1',message:'hi',clientId:'m1'}

// Architecture flow
Clients <-> WebSocket Gateway -> Chat Service -> Store

Diagram

Diagram / flow: Clients <-> WebSocket Gateway -> Chat Service -> Store

Key Points

  • Use persistent connections for delivery, partition conversations, persist messages before acknowledging, and track offline delivery cursors.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q72Design Exercise

How do you design a file upload service?

Issue short-lived signed upload URLs, upload directly to object storage, validate asynchronously, and store metadata separately.

Answer

Issue short-lived signed upload URLs, upload directly to object storage, validate asynchronously, and store metadata separately.

Example: POST /uploads -> {presignedUrl,objectKey}

Diagram / flow: Client -> API -> Signed URL -> Object Store -> Scanner

Syntax

POST /uploads -> {presignedUrl,objectKey}

// Architecture flow
Client -> API -> Signed URL -> Object Store -> Scanner

Example

POST /uploads -> {presignedUrl,objectKey} // Architecture flow Client -> API -> Signed URL -> Object Store -> Scanner

Code example

POST /uploads -> {presignedUrl,objectKey}

// Architecture flow
Client -> API -> Signed URL -> Object Store -> Scanner

Diagram

Example: POST /uploads -> {presignedUrl,objectKey}

Key Points

  • Issue short-lived signed upload URLs, upload directly to object storage, validate asynchronously, and store metadata separately.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q73Design Exercise

How do you design a search autocomplete service?

Precompute popular prefixes or use a search index, rank by relevance and popularity, and cache common queries under strict latency budgets.

Answer

Precompute popular prefixes or use a search index, rank by relevance and popularity, and cache common queries under strict latency budgets.

Example: GET /suggest?q=mic -> ['microservices','microphone']

Diagram / flow: Client -> Suggest API -> Cache -> Trie/Index

Syntax

GET /suggest?q=mic -> ['microservices','microphone']

// Architecture flow
Client -> Suggest API -> Cache -> Trie/Index

Example

GET /suggest?q=mic -> ['microservices','microphone'] // Architecture flow Client -> Suggest API -> Cache -> Trie/Index

Code example

GET /suggest?q=mic -> ['microservices','microphone']

// Architecture flow
Client -> Suggest API -> Cache -> Trie/Index

Diagram

Example: GET /suggest?q=mic -> ['microservices','microphone']

Key Points

  • Precompute popular prefixes or use a search index, rank by relevance and popularity, and cache common queries under strict latency budgets.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q74Design Exercise

How do you design a real-time leaderboard?

Use sorted sets or a ranked index for top-N queries, and durable events to rebuild state

Answer

Use sorted sets or a ranked index for top-N queries, and durable events to rebuild state; specify tie-breaking and update consistency.

Example: ZADD leaderboard 145 user42; ZREVRANGE leaderboard 0 9 WITHSCORES

Diagram / flow: Score Event -> Worker -> Sorted Set -> Top N

Syntax

ZADD leaderboard 145 user42; ZREVRANGE leaderboard 0 9 WITHSCORES

// Architecture flow
Score Event -> Worker -> Sorted Set -> Top N

Example

ZADD leaderboard 145 user42; ZREVRANGE leaderboard 0 9 WITHSCORES // Architecture flow Score Event -> Worker -> Sorted Set -> Top N

Code example

ZADD leaderboard 145 user42; ZREVRANGE leaderboard 0 9 WITHSCORES

// Architecture flow
Score Event -> Worker -> Sorted Set -> Top N

Diagram

Diagram / flow: Score Event -> Worker -> Sorted Set -> Top N

Key Points

  • Use sorted sets or a ranked index for top-N queries, and durable events to rebuild state; specify tie-breaking and update consistency.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q75Design Exercise

How do you design multi-tenant SaaS isolation?

Choose shared tables, separate schemas, or separate databases based on compliance and scale

Answer

Choose shared tables, separate schemas, or separate databases based on compliance and scale; enforce tenant scope in every query and auth check.

Example: SELECT * FROM orders WHERE tenant_id = :tenantId;

Diagram / flow: Gateway -> Tenant Context -> Tenant Data

Syntax

SELECT * FROM orders WHERE tenant_id = :tenantId;

// Architecture flow
Gateway -> Tenant Context -> Tenant Data

Example

SELECT * FROM orders WHERE tenant_id = :tenantId; // Architecture flow Gateway -> Tenant Context -> Tenant Data

Code example

SELECT * FROM orders WHERE tenant_id = :tenantId;

// Architecture flow
Gateway -> Tenant Context -> Tenant Data

Diagram

Diagram / flow: Gateway -> Tenant Context -> Tenant Data

Key Points

  • Choose shared tables, separate schemas, or separate databases based on compliance and scale; enforce tenant scope in every query and auth check.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q76Design Exercise

How do you design a resilient payment service?

Use idempotency keys, durable payment intents, provider timeouts, webhook verification, reconciliation, and explicit state transitions.

Answer

Use idempotency keys, durable payment intents, provider timeouts, webhook verification, reconciliation, and explicit state transitions.

Example: CREATED -> AUTHORIZED -> CAPTURED / FAILED

Diagram / flow: Checkout -> Payment Service -> PSP -> Webhook -> Ledger

Syntax

CREATED -> AUTHORIZED -> CAPTURED / FAILED

// Architecture flow
Checkout -> Payment Service -> PSP -> Webhook -> Ledger

Example

CREATED -> AUTHORIZED -> CAPTURED / FAILED // Architecture flow Checkout -> Payment Service -> PSP -> Webhook -> Ledger

Code example

CREATED -> AUTHORIZED -> CAPTURED / FAILED

// Architecture flow
Checkout -> Payment Service -> PSP -> Webhook -> Ledger

Diagram

Example: CREATED -> AUTHORIZED -> CAPTURED / FAILED

Key Points

  • Use idempotency keys, durable payment intents, provider timeouts, webhook verification, reconciliation, and explicit state transitions.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q77Capacity Planning

How do you estimate system capacity?

Estimate peak RPS, data growth, network bandwidth, and headroom from assumptions

Answer

Estimate peak RPS, data growth, network bandwidth, and headroom from assumptions; measure real workloads to validate the model.

Example: 10M requests/day / 86400 = ~116 avg RPS; peak x10 = ~1160 RPS

Diagram / flow: Demand -> RPS -> Instances / Storage / Network

Syntax

10M requests/day / 86400 = ~116 avg RPS; peak x10 = ~1160 RPS

// Architecture flow
Demand -> RPS -> Instances / Storage / Network

Example

10M requests/day / 86400 = ~116 avg RPS; peak x10 = ~1160 RPS // Architecture flow Demand -> RPS -> Instances / Storage / Network

Code example

10M requests/day / 86400 = ~116 avg RPS; peak x10 = ~1160 RPS

// Architecture flow
Demand -> RPS -> Instances / Storage / Network

Diagram

Diagram / flow: Demand -> RPS -> Instances / Storage / Network

Key Points

  • Estimate peak RPS, data growth, network bandwidth, and headroom from assumptions; measure real workloads to validate the model.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q78Reliability

How do you run disaster recovery?

Define RPO and RTO, automate backups and restores, replicate to a second region if required, and rehearse failover regularly.

Answer

Define RPO and RTO, automate backups and restores, replicate to a second region if required, and rehearse failover regularly.

Example: RPO=5min; RTO=30min

Diagram / flow: Region A -> Backups/Replication -> Region B

Syntax

RPO=5min; RTO=30min

// Architecture flow
Region A -> Backups/Replication -> Region B

Example

RPO=5min; RTO=30min // Architecture flow Region A -> Backups/Replication -> Region B

Code example

RPO=5min; RTO=30min

// Architecture flow
Region A -> Backups/Replication -> Region B

Diagram

Diagram / flow: Region A -> Backups/Replication -> Region B

Key Points

  • Define RPO and RTO, automate backups and restores, replicate to a second region if required, and rehearse failover regularly.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q79Resilience

How do you prevent cascading failures?

Combine deadlines, circuit breakers, bulkheads, bounded queues, load shedding, and graceful degradation to contain dependency failures.

Answer

Combine deadlines, circuit breakers, bulkheads, bounded queues, load shedding, and graceful degradation to contain dependency failures.

Example: if dependency_unhealthy: return cached_response

Diagram / flow: Client -> API -> Breaker -> Dependency

Syntax

if dependency_unhealthy: return cached_response

// Architecture flow
Client -> API -> Breaker -> Dependency

Example

if dependency_unhealthy: return cached_response // Architecture flow Client -> API -> Breaker -> Dependency

Code example

if dependency_unhealthy: return cached_response

// Architecture flow
Client -> API -> Breaker -> Dependency

Diagram

Diagram / flow: Client -> API -> Breaker -> Dependency

Key Points

  • Combine deadlines, circuit breakers, bulkheads, bounded queues, load shedding, and graceful degradation to contain dependency failures.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q80Deployment

How do you handle zero-downtime schema migrations?

Use expand-migrate-contract: add compatible fields, deploy dual-compatible code, backfill, then remove old fields only after all consumers migrate.

Answer

Use expand-migrate-contract: add compatible fields, deploy dual-compatible code, backfill, then remove old fields only after all consumers migrate.

Example: ALTER TABLE users ADD COLUMN display_name TEXT NULL;

Diagram / flow: Expand -> Dual-read/write -> Backfill -> Contract

Syntax

ALTER TABLE users ADD COLUMN display_name TEXT NULL;

// Architecture flow
Expand -> Dual-read/write -> Backfill -> Contract

Example

ALTER TABLE users ADD COLUMN display_name TEXT NULL; // Architecture flow Expand -> Dual-read/write -> Backfill -> Contract

Code example

ALTER TABLE users ADD COLUMN display_name TEXT NULL;

// Architecture flow
Expand -> Dual-read/write -> Backfill -> Contract

Diagram

Diagram / flow: Expand -> Dual-read/write -> Backfill -> Contract

Key Points

  • Use expand-migrate-contract: add compatible fields, deploy dual-compatible code, backfill, then remove old fields only after all consumers migrate.
  • Discuss trade-offs, failure modes, and operational impact.
  • Validate assumptions against latency, throughput, and reliability requirements.
Q84Caching

How can you prevent a cache stampede?

When a hot key expires, many callers can recompute the same value simultaneously. Use request coalescing/single-flight, jittered TTLs, stale-whil

Answer

When a hot key expires, many callers can recompute the same value simultaneously. Use request coalescing/single-flight, jittered TTLs, stale-while-revalidate, or distributed locks where justified.

Example: Several requests for key K share one refresh task instead of all querying the database.

Diagram / flow: Hot key expires → many requests → one refresh leader → shared result

Syntax

TTL = baseTTL + randomJitter; single-flight(key)

Example

Several requests for key K share one refresh task instead of all querying the database.

Code example

TTL = baseTTL + randomJitter; single-flight(key)

Diagram

Hot key expires → many requests → one refresh leader → shared result

Key Points

  • When a hot key expires, many callers can recompute the same value simultaneously.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q87Scalability

What is consistent hashing and why is it used?

Consistent hashing maps keys and nodes onto a ring so adding or removing a node remaps only a subset of keys. Virtual nodes can improve balance;

Answer

Consistent hashing maps keys and nodes onto a ring so adding or removing a node remaps only a subset of keys. Virtual nodes can improve balance; replication and failure handling still need explicit design.

Example: Cache key hashes to a ring position and is assigned to the next available node.

Diagram / flow: Hash key → ring position → successor node; node changes remap limited keys

Syntax

node = ring.successor(hash(key))

Example

Cache key hashes to a ring position and is assigned to the next available node.

Code example

node = ring.successor(hash(key))

Diagram

Hash key → ring position → successor node; node changes remap limited keys

Key Points

  • Consistent hashing maps keys and nodes onto a ring so adding or removing a node remaps only a subset of keys.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q92Resilience

How do you set timeouts across a service call chain?

A downstream timeout must fit within the caller's remaining deadline, leaving time for processing and response. Propagate deadlines and avoid ret

Answer

A downstream timeout must fit within the caller's remaining deadline, leaving time for processing and response. Propagate deadlines and avoid retries that exceed the end-to-end budget.

Example: For a 2-second request budget, give the database call a smaller budget and reserve response time.

Diagram / flow: 2s end-to-end budget → gateway/service/database budgets shrink at each hop

Syntax

downstreamTimeout < remainingRequestDeadline

Example

For a 2-second request budget, give the database call a smaller budget and reserve response time.

Code example

downstreamTimeout < remainingRequestDeadline

Diagram

2s end-to-end budget → gateway/service/database budgets shrink at each hop

Key Points

  • A downstream timeout must fit within the caller's remaining deadline, leaving time for processing and response.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q94Distributed transactions

How does a Saga manage a multi-service business transaction?

A Saga coordinates local transactions and compensating actions instead of one global ACID transaction. Compensation is a new business action, may

Answer

A Saga coordinates local transactions and compensating actions instead of one global ACID transaction. Compensation is a new business action, may fail, and requires idempotency and operational visibility.

Example: If shipment creation fails after payment authorization, void authorization and release inventory.

Diagram / flow: Order → reserve stock → authorize payment → ship; failure → compensation steps

Syntax

Reserve inventory → authorize payment → create shipment; compensate on failure

Example

If shipment creation fails after payment authorization, void authorization and release inventory.

Code example

Reserve inventory → authorize payment → create shipment; compensate on failure

Diagram

Order → reserve stock → authorize payment → ship; failure → compensation steps

Key Points

  • A Saga coordinates local transactions and compensating actions instead of one global ACID transaction.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q95Messaging

How does the transactional outbox pattern improve event reliability?

Store the business change and an outbox event in the same local database transaction. A publisher sends pending events asynchronously; consumers

Answer

Store the business change and an outbox event in the same local database transaction. A publisher sends pending events asynchronously; consumers must handle duplicates because delivery is generally at least once.

Example: Order and OrderCreated outbox row commit together; publisher retries until broker accepts the event.

Diagram / flow: Service DB transaction → outbox table → publisher → broker → idempotent consumer

Syntax

BEGIN; UPDATE business data; INSERT outbox; COMMIT

Example

Order and OrderCreated outbox row commit together; publisher retries until broker accepts the event.

Code example

BEGIN; UPDATE business data; INSERT outbox; COMMIT

Diagram

Service DB transaction → outbox table → publisher → broker → idempotent consumer

Key Points

  • Store the business change and an outbox event in the same local database transaction.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q98Architecture

When is CQRS useful and what does it cost?

CQRS separates command handling from read models when write rules and read/query needs differ significantly. It adds projection lag, operational

Answer

CQRS separates command handling from read models when write rules and read/query needs differ significantly. It adds projection lag, operational complexity, and consistency considerations, so it is not the default for simple CRUD.

Example: Order writes go to the command database; a projection builds a query-optimized customer order view.

Diagram / flow: Commands → write model → events → read-model projection → queries

Syntax

Command model → events/outbox → read projection

Example

Order writes go to the command database; a projection builds a query-optimized customer order view.

Code example

Command model → events/outbox → read projection

Diagram

Commands → write model → events → read-model projection → queries

Key Points

  • CQRS separates command handling from read models when write rules and read/query needs differ significantly.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q100Resilience

What is load shedding and when should a service use it?

Load shedding rejects low-priority or excess work before queues and latency grow without bound. Pair it with admission control, bounded queues, a

Answer

Load shedding rejects low-priority or excess work before queues and latency grow without bound. Pair it with admission control, bounded queues, and clear overload responses.

Example: During overload, preserve checkout and reject optional recommendation requests.

Diagram / flow: Incoming load > safe capacity → reject low-priority work → protect critical paths

Syntax

if inFlight >= limit: return 503/429

Example

During overload, preserve checkout and reject optional recommendation requests.

Code example

if inFlight >= limit: return 503/429

Diagram

Incoming load > safe capacity → reject low-priority work → protect critical paths

Key Points

  • Load shedding rejects low-priority or excess work before queues and latency grow without bound.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q103Scalability

What trade-offs arise in active-active multi-region architecture?

Active-active can reduce latency and improve regional availability but complicates writes, conflict resolution, data replication, and failover. C

Answer

Active-active can reduce latency and improve regional availability but complicates writes, conflict resolution, data replication, and failover. Choose consistency and recovery objectives explicitly per data domain.

Example: Serve reads locally while routing single-writer account mutations to a home region.

Diagram / flow: Clients → nearest region; data replication and conflict policy connect regions

Syntax

region A ↔ replication/conflict policy ↔ region B

Example

Serve reads locally while routing single-writer account mutations to a home region.

Code example

region A ↔ replication/conflict policy ↔ region B

Diagram

Clients → nearest region; data replication and conflict policy connect regions

Key Points

  • Active-active can reduce latency and improve regional availability but complicates writes, conflict resolution, data replication, and failover.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q106Reliability

How do SLOs and error budgets guide reliability decisions?

An SLO sets a target for a service-level indicator over a window. The error budget is the allowed unreliability; budget burn can guide release pa

Answer

An SLO sets a target for a service-level indicator over a window. The error budget is the allowed unreliability; budget burn can guide release pace and whether to prioritize reliability work.

Example: A 99.9% monthly availability target permits about 0.1% eligible failures.

Diagram / flow: SLI measurements → SLO comparison → error budget → release/reliability decisions

Syntax

availability SLI = successful eligible requests / total eligible requests

Example

A 99.9% monthly availability target permits about 0.1% eligible failures.

Code example

availability SLI = successful eligible requests / total eligible requests

Diagram

SLI measurements → SLO comparison → error budget → release/reliability decisions

Key Points

  • An SLO sets a target for a service-level indicator over a window.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q108Architecture

How do you design tenant isolation in a multi-tenant service?

Enforce tenant identity on every data access path, scope cache keys and queues, and consider per-tenant quotas. Stronger isolation may require se

Answer

Enforce tenant identity on every data access path, scope cache keys and queues, and consider per-tenant quotas. Stronger isolation may require separate schemas, databases, or deployments depending on risk and regulation.

Example: A repository always filters records by the authenticated tenant ID.

Diagram / flow: Authenticated tenant context → authorization → tenant-scoped storage

Syntax

tenantId from trusted auth context → scoped query/cache key

Example

A repository always filters records by the authenticated tenant ID.

Code example

tenantId from trusted auth context → scoped query/cache key

Diagram

Authenticated tenant context → authorization → tenant-scoped storage

Key Points

  • Enforce tenant identity on every data access path, scope cache keys and queues, and consider per-tenant quotas.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q110Messaging

How do you evolve event schemas safely?

Prefer additive, optional fields and tolerant consumers; define schema compatibility rules and versioning. Avoid changing field meaning or removi

Answer

Prefer additive, optional fields and tolerant consumers; define schema compatibility rules and versioning. Avoid changing field meaning or removing fields until all consumers have migrated.

Example: Deploy consumers that accept both payloads before producers begin sending the new field.

Diagram / flow: Consumer compatibility first → producer adds field → old consumers retire

Syntax

OrderCreated v1 → add optional currency field → consumers tolerate absent/present field

Example

Deploy consumers that accept both payloads before producers begin sending the new field.

Code example

OrderCreated v1 → add optional currency field → consumers tolerate absent/present field

Diagram

Consumer compatibility first → producer adds field → old consumers retire

Key Points

  • Prefer additive, optional fields and tolerant consumers; define schema compatibility rules and versioning.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q112Distributed systems

What risks should you consider when using a distributed lock?

Locks can expire while a slow holder continues, and network partitions can make ownership ambiguous. Use fencing tokens or version checks when st

Answer

Locks can expire while a slow holder continues, and network partitions can make ownership ambiguous. Use fencing tokens or version checks when stale holders could corrupt state; prefer atomic database constraints where suitable.

Example: Worker A's lease expires; worker B gets a newer fencing token so stale writes from A are rejected.

Diagram / flow: Lease holder A → expiry → holder B/token N+1; storage rejects stale token N

Syntax

acquire lease → fencing token N → write accepted only if token is current

Example

Worker A's lease expires; worker B gets a newer fencing token so stale writes from A are rejected.

Code example

acquire lease → fencing token N → write accepted only if token is current

Diagram

Lease holder A → expiry → holder B/token N+1; storage rejects stale token N

Key Points

  • Locks can expire while a slow holder continues, and network partitions can make ownership ambiguous.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q113Resilience

How can retries create a retry storm?

Retries multiply traffic when a dependency is already overloaded. Use bounded retries, exponential backoff with jitter, retry budgets, circuit br

Answer

Retries multiply traffic when a dependency is already overloaded. Use bounded retries, exponential backoff with jitter, retry budgets, circuit breakers, and end-to-end deadlines; avoid retrying at every layer simultaneously.

Example: Gateway and service both retrying three times can multiply a single request into many downstream calls.

Diagram / flow: Dependency slows → retries amplify load → more failures; budgets/backoff break the cycle

Syntax

retryBudget + maxAttempts + jitter + deadline

Example

Gateway and service both retrying three times can multiply a single request into many downstream calls.

Code example

retryBudget + maxAttempts + jitter + deadline

Diagram

Dependency slows → retries amplify load → more failures; budgets/backoff break the cycle

Key Points

  • Retries multiply traffic when a dependency is already overloaded.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q115Caching

How do you choose cache consistency guarantees?

Define whether stale reads are acceptable and for how long. Cache-aside with TTL is simple but can be stale; write-through, versioned keys, inval

Answer

Define whether stale reads are acceptable and for how long. Cache-aside with TTL is simple but can be stale; write-through, versioned keys, invalidation events, or bypassing cache for critical reads trade complexity for freshness.

Example: Display product catalog from cache but verify inventory at checkout.

Diagram / flow: Read path policy depends on freshness requirement and source of truth

Syntax

freshness SLO → cache policy → invalidation/TTL/versioning

Example

Display product catalog from cache but verify inventory at checkout.

Code example

freshness SLO → cache policy → invalidation/TTL/versioning

Diagram

Read path policy depends on freshness requirement and source of truth

Key Points

  • Define whether stale reads are acceptable and for how long.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q118Architecture

How does the Strangler Fig pattern modernize a legacy system?

A routing layer gradually directs selected capabilities to new services while the legacy system continues serving remaining behavior. Migration r

Answer

A routing layer gradually directs selected capabilities to new services while the legacy system continues serving remaining behavior. Migration requires clear data ownership, observability, rollback paths, and a plan to retire duplicated functionality.

Example: Move customer profile reads first, then writes, while keeping other workflows on the monolith.

Diagram / flow: Client → routing layer → legacy or new service; migrate capability by capability

Syntax

route capability A → new service; other routes → legacy

Example

Move customer profile reads first, then writes, while keeping other workflows on the monolith.

Code example

route capability A → new service; other routes → legacy

Diagram

Client → routing layer → legacy or new service; migrate capability by capability

Key Points

  • A routing layer gradually directs selected capabilities to new services while the legacy system continues serving remaining behavior.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.
Q120Scalability

How can you control fan-out in a microservice request?

A request that calls many downstream services increases tail latency and failure probability. Reduce serial calls, parallelize only independent w

Answer

A request that calls many downstream services increases tail latency and failure probability. Reduce serial calls, parallelize only independent work, cache or precompute where appropriate, and impose concurrency and deadline limits.

Example: Fetch independent inventory and shipping estimates concurrently with a shared deadline.

Diagram / flow: Request → bounded parallel fan-out → aggregate before deadline

Syntax

total latency ≈ max(parallel calls) + local overhead

Example

Fetch independent inventory and shipping estimates concurrently with a shared deadline.

Code example

total latency ≈ max(parallel calls) + local overhead

Diagram

Request → bounded parallel fan-out → aggregate before deadline

Key Points

  • A request that calls many downstream services increases tail latency and failure probability.
  • Make trade-offs explicit and test failure scenarios.
  • Monitor behavior under representative load.

Share this question bank

Send this page to someone preparing for an interview.