System Design for QA

Distributed systems, chaos engineering, observability, CAP theorem, contract testing at scale, and testing architectures.

Overview #

System Design for QA is one of the most differentiating skills for senior QA engineers. Unlike developers who design systems for functionality, senior QA engineers must evaluate architectures for testability, observability, failure modes, and resilience. This chapter covers 30 system design scenarios that test your ability to reason about distributed systems, identify failure injection points, and build comprehensive test strategies across every layer.

What Interviewers Evaluate

Dimension What They Look For
Architectural Thinking Can you decompose a system into testable components?
Failure Mode Analysis Can you identify what can go wrong in distributed systems?
Test Strategy Design Can you layer unit, integration, E2E, and chaos tests?
Distributed Systems Knowledge Do you understand CAP theorem, eventual consistency, idempotency?
Tooling Awareness Do you know chaos engineering, contract testing, load testing tools?
Observability Mindset Can you verify systems through metrics, logs, and traces?

Key Distributed Systems Concepts for QA

┌─────────────────────────────────────────────────────────────┐
│                    CAP Theorem                                │
│                                                              │
│   Consistency ◄──────► Availability ◄──────► Partition       │
│                                              Tolerance       │
│                                                              │
│   Pick 2 of 3 (in practice: CP or AP during partitions)     │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│              Testing Pyramid for Distributed Systems          │
│                                                              │
│                    ┌───────────┐                             │
│                    │  Chaos    │  ← Production/Staging       │
│                   ┌┴───────────┴┐                            │
│                   │   E2E Tests  │  ← Cross-service          │
│                  ┌┴──────────────┴┐                          │
│                  │ Contract Tests  │  ← Service boundaries   │
│                 ┌┴────────────────┴┐                         │
│                 │ Integration Tests │  ← With real deps      │
│                ┌┴──────────────────┴┐                        │
│                │    Unit Tests       │  ← Business logic     │
│                └────────────────────┘                        │
└─────────────────────────────────────────────────────────────┘

Framework for Answering System Design QA Questions

  1. Clarify scope — Ask about scale, SLAs, consistency requirements
  2. Draw architecture — Identify components, data flows, boundaries
  3. Identify failure modes — Network, disk, clock, dependency failures
  4. Layer test strategy — Unit → Integration → Contract → E2E → Chaos
  5. Define observability — Metrics, logs, traces, alerts to verify
  6. Specify tools — Name concrete tools for each testing layer

Q1How would you test a distributed chat system? #

Objective

Demonstrate ability to test real-time, eventually consistent systems with high concurrency, message ordering guarantees, and presence management.

Interview Answer

A distributed chat system must handle real-time message delivery, ordering, presence (online/offline), and persistence across multiple data centers. My testing strategy addresses each layer:

Architecture:

┌──────────┐     ┌──────────────┐     ┌─────────────────┐
│  Client  │────▶│  WebSocket   │────▶│  Message Router  │
│  (App)   │◀────│  Gateway     │◀────│  (Pub/Sub)       │
└──────────┘     └──────────────┘     └────────┬────────┘
                                                │
                       ┌────────────────────────┼────────────────┐
                       │                        │                │
                 ┌─────▼─────┐          ┌──────▼──────┐  ┌─────▼──────┐
                 │  Presence  │          │  Message    │  │  Media     │
                 │  Service   │          │  Store      │  │  Service   │
                 │  (Redis)   │          │  (Cassandra)│  │  (S3+CDN)  │
                 └────────────┘          └─────────────┘  └────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Message serialization, ordering logic, deduplication JUnit, pytest
Integration WebSocket connection lifecycle, pub/sub routing Testcontainers, embedded Redis
Contract API contracts between gateway and router Pact, Spring Cloud Contract
E2E Multi-user conversations, media sharing flows Selenium + WebSocket clients
Chaos Network partitions between data centers Chaos Monkey, Toxiproxy
Load 100K concurrent connections, message throughput Gatling, k6 with WebSocket

Specific Test Cases:

  1. Message ordering — Send 1000 messages rapidly; verify all clients see same order
  2. Delivery guarantee — Kill a gateway mid-delivery; verify message is not lost
  3. Presence accuracy — Disconnect client abruptly; verify presence updates within SLA
  4. Split-brain — Partition two data centers; verify messages reconcile after healing
  5. Duplicate detection — Retry same message with same idempotency key; verify single delivery
  6. Offline sync — Client reconnects after 24h; verify message backfill is complete and ordered

Failure Injection Scenarios:

Scenario: Network partition between DC-East and DC-West
Given: Users A (DC-East) and B (DC-West) are in the same chat room
When: Network partition occurs between data centers
Then: Both users can still send messages to local DC
When: Partition heals
Then: Messages from both sides are merged with correct causal ordering
And: No duplicate messages appear in either client

Observability Testing:

  • Verify message latency metrics (p50, p95, p99) are emitted per hop
  • Confirm dead-letter queue alerts fire when messages fail delivery 3x
  • Validate distributed traces span from client → gateway → router → store
  • Test that presence heartbeat timeouts trigger correct status transitions

Distributed Systems Concepts:

  • Eventual consistency: Messages may arrive out of order across DCs; test reconciliation
  • Idempotency: Clients retry with message IDs; server must deduplicate
  • Vector clocks: Test causal ordering when multiple users edit simultaneously

Common Mistakes

  • Testing only happy-path message delivery without network failures
  • Ignoring message ordering under concurrent writes
  • Not testing reconnection scenarios with message gaps
  • Overlooking presence state becoming stale under partition

Follow-up Questions

  • How would you test end-to-end encryption in this system?
  • What SLA would you set for message delivery latency and how would you verify it?
  • How would you test typing indicators at scale?

Q2How would you test a payment platform? #

Objective

Demonstrate understanding of testing financial systems with strict consistency requirements, idempotency, regulatory compliance, and fraud detection.

Interview Answer

Payment platforms demand the highest testing rigor because failures mean financial loss. The system must be exactly-once, auditable, and compliant with PCI-DSS.

Architecture:

┌──────────┐     ┌──────────────┐     ┌─────────────────┐     ┌──────────────┐
│  Client  │────▶│  API Gateway │────▶│  Payment        │────▶│  Payment     │
│  (App)   │◀────│  (Auth+Rate) │◀────│  Orchestrator   │◀────│  Processor   │
└──────────┘     └──────────────┘     └────────┬────────┘     │  (Stripe/    │
                                                │              │   Adyen)     │
                       ┌────────────────────────┼──────┐       └──────────────┘
                       │                        │      │
                 ┌─────▼─────┐          ┌──────▼──┐  ┌▼───────────┐
                 │  Fraud    │          │  Ledger │  │  Webhook    │
                 │  Engine   │          │  (ACID) │  │  Handler    │
                 │  (ML+Rules)│         │  (PG)   │  │  (Idempotent)│
                 └────────────┘          └─────────┘  └─────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Amount calculations, currency conversion, fee logic JUnit with BigDecimal assertions
Integration Ledger double-entry bookkeeping, fraud rule evaluation Testcontainers (PostgreSQL)
Contract Payment processor API contract stability Pact, WireMock
E2E Full payment flow: authorize → capture → settle Stripe test mode, sandbox environments
Chaos Processor timeout mid-transaction, DB failover Toxiproxy, LitmusChaos
Load Black Friday spike: 10x normal transaction volume Gatling, Locust

Specific Test Cases:

  1. Idempotency — Submit same payment request twice with same key; verify single charge
  2. Double-entry ledger — After every transaction, verify debits = credits
  3. Partial failure — Processor approves but DB write fails; verify reconciliation
  4. Webhook replay — Send same webhook 5 times; verify single state transition
  5. Currency precision — Test JPY (0 decimals), USD (2), BHD (3) all calculate correctly
  6. Timeout handling — Processor takes 30s to respond; verify no duplicate charges
  7. Refund integrity — Refund amount cannot exceed original charge amount
  8. PCI compliance — Verify card numbers never appear in logs, metrics, or error messages

Failure Injection Scenarios:

Scenario: Database failure after processor approval
Given: Customer submits $100 payment
And: Payment processor successfully authorizes the charge
When: Database connection drops before ledger write
Then: System queues a reconciliation event
And: No duplicate charge is created when DB recovers
And: Customer sees "processing" status (not "failed")
And: Reconciliation job matches processor records with ledger within 5 minutes

Observability Testing:

  • Verify payment state machine transitions emit metrics (authorized, captured, failed, refunded)
  • Confirm alerting fires when settlement mismatch exceeds $0.01
  • Test that distributed traces include processor response times
  • Validate PCI audit logs record all access to cardholder data

Distributed Systems Concepts:

  • ACID transactions: Ledger must be strongly consistent; test isolation levels
  • Idempotency keys: Every mutation must be safely retryable
  • Saga pattern: Multi-step payments use compensating transactions; test rollback paths
  • Exactly-once semantics: Webhooks + retries must not create duplicate records

Common Mistakes

  • Using floating-point arithmetic for monetary calculations
  • Not testing the unhappy path where processor approves but internal state fails
  • Ignoring currency-specific decimal handling
  • Testing only with small amounts (missing overflow/precision issues at scale)

Follow-up Questions

  • How would you test a payment system's compliance with PCI-DSS?
  • How would you verify that no sensitive card data leaks into logs?
  • How would you test a multi-currency payment split?

Q3How would you test a notification service? #

Objective

Demonstrate ability to test multi-channel delivery systems with rate limiting, user preferences, deduplication, and delivery guarantees.

Interview Answer

Notification services must deliver messages across multiple channels (push, email, SMS, in-app) while respecting user preferences, avoiding spam, and guaranteeing delivery.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Event       │────▶│  Notification│────▶│  Channel Router  │
│  Producers   │     │  Aggregator  │     │  (Preferences)   │
│  (Services)  │     │  (Dedup+     │     └────────┬─────────┘
└──────────────┘     │   Throttle)  │              │
                     └──────────────┘     ┌────────┼────────────────┐
                                          │        │                │
                                    ┌─────▼──┐ ┌──▼────────┐ ┌────▼─────┐
                                    │  Push  │ │  Email     │ │  SMS     │
                                    │  (FCM/ │ │  (SES/     │ │  (Twilio/│
                                    │  APNs) │ │  SendGrid) │ │  SNS)    │
                                    └────────┘ └────────────┘ └──────────┘
                                          │        │                │
                                    ┌─────▼────────▼────────────────▼─────┐
                                    │       Delivery Status Tracker        │
                                    │       (DynamoDB + Dead Letter Q)     │
                                    └─────────────────────────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Template rendering, preference matching, throttle logic JUnit, pytest
Integration Channel routing with real preferences DB Testcontainers
Contract Provider API contracts (FCM, SES, Twilio) Pact, WireMock
E2E User receives notification across all subscribed channels Mailhog, mock push server
Chaos Push provider outage, email bounce storms Toxiproxy, Gremlin
Load 1M notifications/minute burst (Black Friday alerts) k6, Locust

Specific Test Cases:

  1. Preference honoring — User opts out of email; verify no email sent, other channels active
  2. Deduplication — Same event fires twice within 5 minutes; only one notification delivered
  3. Rate limiting — User would receive 50 notifications/hour; verify batching/throttling
  4. Fallback channels — Push delivery fails; verify SMS fallback within configured timeout
  5. Template rendering — Test with special characters, long names, missing variables
  6. Quiet hours — Notification arrives at 2 AM user-local-time; verify held until morning
  7. Delivery tracking — Verify bounce, open, click events update delivery status correctly

Failure Injection Scenarios:

Scenario: Push notification provider outage
Given: FCM is unreachable (connection timeout)
When: 10,000 push notifications are queued
Then: System retries with exponential backoff (1s, 2s, 4s, 8s)
And: After 3 retries, messages move to dead-letter queue
And: Alert fires for "push_delivery_failure_rate > 50%"
And: Fallback to in-app notification is triggered per configuration

Observability Testing:

  • Verify delivery rate metrics per channel (sent, delivered, bounced, opened)
  • Confirm latency histograms from event ingestion to delivery per channel
  • Test that dead-letter queue depth alerts fire at configured threshold
  • Validate audit trail records who received what notification and when

Distributed Systems Concepts:

  • At-least-once delivery: Notifications may retry; test deduplication at client
  • Eventual consistency: Preference updates may not apply immediately to in-flight messages
  • Backpressure: Test system behavior when downstream providers are slow

Common Mistakes

  • Not testing timezone-aware quiet hours across DST transitions
  • Ignoring notification fatigue and rate limiting logic
  • Testing providers in isolation without end-to-end delivery verification
  • Not verifying idempotency when events are replayed from message queues

Follow-up Questions

  • How would you test notification priority levels (critical vs. marketing)?
  • How would you verify GDPR consent is checked before sending?
  • How would you load test push notifications without hitting real FCM/APNs?

Q4How would you test a file-storage service? #

Objective

Demonstrate ability to test a system with large binary payloads, eventual consistency, access control, and data durability requirements.

Interview Answer

File storage services handle uploads, downloads, metadata management, and access control at scale. Key challenges include large file handling, concurrent access, and durability guarantees.

Architecture:

┌──────────┐     ┌──────────────┐     ┌─────────────────┐     ┌──────────────┐
│  Client  │────▶│  API Gateway │────▶│  Upload Service  │────▶│  Object      │
│          │◀────│  (Auth+      │◀────│  (Chunked/       │     │  Store       │
└──────────┘     │   Presigned) │     │   Multipart)     │     │  (S3/GCS)    │
                 └──────────────┘     └────────┬─────────┘     └──────────────┘
                                               │
                       ┌───────────────────────┼──────────────┐
                       │                       │              │
                 ┌─────▼─────┐         ┌──────▼──────┐ ┌────▼──────────┐
                 │  Metadata │         │  Virus      │ │  Thumbnail    │
                 │  Service  │         │  Scanner    │ │  Generator    │
                 │  (PostgreSQL)│      │  (ClamAV)   │ │  (Lambda)     │
                 └────────────┘        └─────────────┘ └───────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Chunk assembly, hash verification, ACL evaluation JUnit, pytest
Integration Multipart upload with real object store LocalStack, MinIO
Contract Pre-signed URL generation, metadata API Pact
E2E Upload → scan → thumbnail → share → download Cypress, Playwright
Chaos Storage node failure mid-upload, network timeouts Toxiproxy, Chaos Mesh
Load 10K concurrent uploads of 1GB files k6, custom upload clients

Specific Test Cases:

  1. Chunked upload resume — Upload 80% of a 5GB file, disconnect, resume; verify completion
  2. Concurrent access — Two users upload same filename simultaneously; verify no data corruption
  3. Access control — Shared link expires after 24h; verify 403 after expiry
  4. Virus scanning — Upload EICAR test file; verify quarantine and user notification
  5. Storage quotas — User at 99% quota; verify appropriate error and no partial writes
  6. Content-type validation — Upload .exe renamed to .jpg; verify server-side type detection
  7. Cross-region replication — Upload in US-East; verify accessible from EU-West within SLA
  8. Integrity verification — Download file; verify SHA-256 matches upload checksum

Failure Injection Scenarios:

Scenario: Storage backend failure during multipart upload
Given: User is uploading a 2GB file in 10MB chunks
And: 150 of 200 chunks have been stored successfully
When: Object store returns 503 for subsequent chunk uploads
Then: Client retries failed chunks with exponential backoff
And: Successfully uploaded chunks are not re-uploaded (resume from last)
And: If failure persists > 1 hour, incomplete upload is cleaned up
And: User receives actionable error with resume capability

Observability Testing:

  • Verify upload/download latency percentiles per file size bucket
  • Confirm storage utilization metrics per tenant align with actual usage
  • Test that failed virus scan alerts include file hash and upload source
  • Validate that orphaned chunk cleanup job metrics report cleaned vs. skipped

Distributed Systems Concepts:

  • Eventual consistency: Newly uploaded files may not be immediately listable (S3 model)
  • Idempotency: Re-uploading same content with same key should be safe
  • CAP trade-off: Prefer availability for reads, consistency for metadata updates

Common Mistakes

  • Testing only with small files (missing chunked upload edge cases)
  • Not testing concurrent uploads to the same path
  • Ignoring cleanup of failed/incomplete uploads
  • Not verifying that deleted files are actually purged from storage (not just metadata)

Follow-up Questions

  • How would you test file versioning and rollback?
  • How would you verify data durability (11 9's) in testing?
  • How would you test file sharing permissions across organizational boundaries?

Q5How would you test a search index? #

Objective

Demonstrate ability to test systems with eventual consistency between source-of-truth and index, relevance ranking, and performance under load.

Interview Answer

Search systems have a fundamental testing challenge: the index is eventually consistent with the source data, relevance is subjective, and performance degrades non-linearly with data volume.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Source DB   │────▶│  Change Data │────▶│  Index Builder   │
│  (PostgreSQL)│     │  Capture     │     │  (Transformer)   │
└──────────────┘     │  (Debezium)  │     └────────┬─────────┘
                     └──────────────┘              │
                                            ┌──────▼──────────┐
┌──────────┐     ┌──────────────┐          │  Search Index    │
│  Client  │────▶│  Search API  │─────────▶│  (Elasticsearch/ │
│          │◀────│  (Query      │◀─────────│   OpenSearch)    │
└──────────┘     │   Parser)    │          └─────────────────┘
                 └──────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Query parsing, tokenization, filter logic JUnit, pytest
Integration CDC pipeline with real Elasticsearch Testcontainers (ES + PG)
Contract Search API response schema stability OpenAPI validation
E2E Create document → wait → search → find Playwright, REST clients
Chaos Index node failure, CDC lag spike Chaos Mesh, Toxiproxy
Load 10K queries/sec with 100M documents Rally (ES benchmark), k6

Specific Test Cases:

  1. Indexing lag — Create document; measure time until searchable (SLA: <5s)
  2. Relevance regression — Maintain golden queries with expected top-5 results; alert on drift
  3. Partial matching — Search "javascrip" finds "JavaScript" (typo tolerance)
  4. Faceted search — Filter by category + price range; verify counts match source DB
  5. Index rebuild — Trigger full reindex; verify zero-downtime with alias swap
  6. Deleted content — Delete document from source; verify removed from index within SLA
  7. Multi-language — Search in Chinese, Arabic, German; verify tokenization correctness
  8. Permission filtering — User A cannot see User B's private documents in results

Failure Injection Scenarios:

Scenario: CDC pipeline lag causes stale search results
Given: Normal indexing lag is <2 seconds
When: Database experiences high write throughput (10x normal)
And: CDC pipeline consumer lag exceeds 60 seconds
Then: Search results show stale data (acceptable within SLA)
And: Lag metric alert fires at 30s threshold
And: System does NOT serve completely empty results
And: When lag recovers, all documents eventually appear in index

Observability Testing:

  • Verify indexing lag metric (time between DB write and index availability)
  • Confirm query latency percentiles (p50 < 100ms, p99 < 500ms)
  • Test relevance metrics (NDCG, MRR) are computed and tracked over time
  • Validate that index size and shard health metrics are emitted

Distributed Systems Concepts:

  • Eventual consistency: Index always lags source; test acceptable staleness windows
  • CAP theorem: Search favors availability; stale results preferred over no results
  • Idempotency: Re-indexing same document must be safe (upsert semantics)

Common Mistakes

  • Only testing search with small datasets (relevance changes at scale)
  • Not establishing relevance baselines before making ranking changes
  • Ignoring the indexing lag in E2E tests (flaky tests from race conditions)
  • Testing exact match only, missing fuzzy/partial/synonym scenarios

Follow-up Questions

  • How would you implement relevance regression testing in CI/CD?
  • How would you test search personalization without bias?
  • How would you verify that search respects real-time permission changes?

Q6How would you test a recommendation service? #

Objective

Demonstrate ability to test ML-driven systems with non-deterministic outputs, A/B testing requirements, and feedback loop verification.

Interview Answer

Recommendation engines combine ML models with real-time signals to produce personalized results. Testing is challenging because outputs are probabilistic, relevance is subjective, and feedback loops can create filter bubbles.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  User        │────▶│  Reco API    │────▶│  Model Serving   │
│  Activity    │     │  (Feature    │     │  (TensorFlow     │
│  Stream      │     │   Assembly)  │     │   Serving/       │
└──────────────┘     └──────┬───────┘     │   SageMaker)     │
                            │             └────────┬─────────┘
                     ┌──────▼───────┐              │
                     │  Feature     │       ┌──────▼──────────┐
                     │  Store       │       │  Candidate      │
                     │  (Redis +    │       │  Generator      │
                     │   Offline)   │       │  (Collaborative │
                     └──────────────┘       │   Filtering)    │
                                            └─────────────────┘
                            │
                     ┌──────▼───────┐
                     │  A/B Test    │
                     │  Framework   │
                     │  (Bucketing) │
                     └──────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Feature transformation, candidate filtering logic pytest, JUnit
Integration Feature store retrieval, model inference pipeline Testcontainers, LocalStack
Contract Model input/output schema between training and serving Great Expectations, Pact
E2E User interacts → recommendations update within SLA Selenium, API tests
Chaos Model serving timeout, feature store unavailability Toxiproxy, Gremlin
Load 50K reco requests/sec with <100ms p99 latency Locust, k6

Specific Test Cases:

  1. Cold start — New user with zero history; verify fallback to popular/trending items
  2. Model freshness — Train new model; verify A/B framework routes traffic correctly
  3. Diversity — Recommendations don't show 10 items from same category (filter bubble)
  4. Exclusion rules — Previously purchased items don't appear in recommendations
  5. Feature staleness — Feature store returns stale data; verify graceful degradation
  6. Bias detection — Verify recommendations don't discriminate by protected attributes
  7. Feedback loop — Click on recommendation; verify it influences future results within SLA

Failure Injection Scenarios:

Scenario: Model serving latency spike
Given: Normal model inference takes 20ms
When: Model serving latency exceeds 200ms (10x degradation)
Then: System falls back to pre-computed recommendations (cache)
And: Fallback metric increments
And: User sees recommendations within 300ms total (SLA maintained)
And: When model recovers, system returns to real-time inference

Observability Testing:

  • Verify CTR (click-through rate) metrics per model version
  • Confirm feature freshness metrics (age of features used in inference)
  • Test A/B experiment metrics are correctly attributed to variants
  • Validate model inference latency and error rate dashboards

Distributed Systems Concepts:

  • Eventual consistency: User activity may not be reflected immediately in features
  • Idempotency: Same request with same features must return same recommendations
  • CAP trade-off: Prefer availability; stale recommendations over no recommendations

Common Mistakes

  • Testing recommendations only for accuracy, ignoring diversity and fairness
  • Not verifying that A/B bucketing is deterministic and consistent per user
  • Ignoring cold-start scenarios in test plans
  • Not establishing offline evaluation metrics before online A/B testing

Follow-up Questions

  • How would you detect and test for recommendation bias?
  • How would you verify that model retraining doesn't degrade quality?
  • How would you test recommendation explanations ("Because you watched...")?

Q7How would you test a multi-tenant SaaS product? #

Objective

Demonstrate understanding of tenant isolation testing, data segregation, configuration management, and performance fairness across tenants.

Interview Answer

Multi-tenant SaaS requires rigorous testing of data isolation, performance isolation (noisy neighbor), tenant-specific configuration, and compliance boundaries.

Architecture:

┌───────────┐ ┌───────────┐ ┌───────────┐
│  Tenant A │ │  Tenant B │ │  Tenant C │
│  (Free)   │ │  (Pro)    │ │  (Ent.)   │
└─────┬─────┘ └─────┬─────┘ └─────┬─────┘
      │              │              │
      └──────────────┼──────────────┘
                     │
              ┌──────▼──────┐
              │  API Gateway │
              │  (Tenant ID  │
              │   extraction)│
              └──────┬──────┘
                     │
         ┌───────────┼───────────┐
         │           │           │
   ┌─────▼─────┐ ┌──▼────┐ ┌───▼──────┐
   │  App      │ │ Queue │ │  Billing │
   │  Service  │ │ (SQS) │ │  Service │
   │  (Tenant  │ └───────┘ └──────────┘
   │   Context)│
   └─────┬─────┘
         │
   ┌─────▼─────────────────────────────┐
   │  Database (Shared schema with     │
   │  tenant_id column / Schema-per-   │
   │  tenant / DB-per-tenant)          │
   └───────────────────────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Tenant context propagation, feature flag evaluation JUnit, pytest
Integration Data isolation across tenants in shared DB Testcontainers
Contract API behavior per tier (Free vs. Pro vs. Enterprise) Pact
E2E Full workflow per tenant tier with correct limits Playwright
Chaos One tenant causing high load; verify others unaffected Gremlin, custom
Load Noisy neighbor: 1 tenant at 100x while others at 1x Gatling

Specific Test Cases:

  1. Data isolation — Tenant A queries; verify zero rows from Tenant B visible
  2. Cross-tenant API — Forge Tenant B's ID in headers; verify 403 rejection
  3. Noisy neighbor — Tenant A runs expensive query; verify Tenant B's latency unaffected
  4. Tier enforcement — Free tenant hits API rate limit; Pro tenant same volume succeeds
  5. Tenant provisioning — Create new tenant; verify isolated resources within 30s
  6. Tenant deletion — Delete tenant; verify all data purged (including backups per policy)
  7. Config isolation — Tenant A enables feature X; verify Tenant B doesn't see it
  8. Billing accuracy — Each API call attributed to correct tenant's usage meter

Failure Injection Scenarios:

Scenario: Noisy neighbor resource exhaustion
Given: 100 tenants sharing the same database cluster
When: Tenant A executes a query that scans 10M rows (no index)
Then: Query governor kills Tenant A's query after 5s timeout
And: Other tenants' query latency stays within p99 SLA
And: Tenant A receives 429 or timeout error with guidance
And: Alert fires for "tenant_query_timeout" with tenant context

Observability Testing:

  • Verify all metrics are tagged with tenant_id dimension
  • Confirm per-tenant resource usage dashboards are accurate
  • Test that alerts fire per-tenant (not global aggregates hiding tenant issues)
  • Validate tenant-specific SLA compliance reports

Distributed Systems Concepts:

  • Isolation guarantees: Test both logical (row-level) and physical (resource) isolation
  • Fairness: Rate limiting and resource quotas prevent starvation
  • Consistency: Tenant config changes must propagate consistently across all nodes

Common Mistakes

  • Testing only data isolation, ignoring performance isolation
  • Not testing tenant context propagation through async workflows (queues)
  • Assuming shared-nothing architecture when shared-something is used
  • Not testing what happens when tenant_id is missing from a request

Follow-up Questions

  • How would you test tenant data migration between isolation models?
  • How would you verify that logs never mix tenant data?
  • How would you test SSO integration per tenant with different IdPs?

Q8How would you test an audit trail? #

Objective

Demonstrate ability to test immutable, tamper-evident logging systems that satisfy compliance requirements (SOX, HIPAA, SOC 2).

Interview Answer

Audit trails must be immutable, complete, tamper-evident, and queryable. They're critical for compliance and incident investigation. Testing must verify that no action goes unrecorded and no record can be altered.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Application │────▶│  Audit Event │────▶│  Audit Store     │
│  Services    │     │  Publisher   │     │  (Append-only    │
│  (All CRUD)  │     │  (Async)     │     │   Ledger/QLDB)   │
└──────────────┘     └──────────────┘     └────────┬─────────┘
                                                   │
                                          ┌────────▼─────────┐
                                          │  Audit Query API  │
                                          │  (Read-only,      │
                                          │   Role-gated)     │
                                          └────────┬─────────┘
                                                   │
                                          ┌────────▼─────────┐
                                          │  Compliance       │
                                          │  Reports &        │
                                          │  Dashboards       │
                                          └──────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Event serialization, field completeness, timestamp accuracy JUnit, pytest
Integration Async publish → store → query round-trip Testcontainers (QLDB/PG)
Contract Audit event schema versioning JSON Schema validation
E2E Perform action → query audit log → verify complete record API tests
Chaos Audit publisher failure; verify no silent event loss Toxiproxy
Security Attempt to modify/delete audit records Penetration testing

Specific Test Cases:

  1. Completeness — Perform every CRUD operation; verify each generates audit event
  2. Immutability — Attempt UPDATE/DELETE on audit store; verify rejection
  3. Tamper evidence — Verify cryptographic hash chain; detect gaps in sequence
  4. Who-what-when — Every event has: actor, action, resource, timestamp, IP, session
  5. Before/after values — Update user email; audit shows old and new value
  6. Retention — Verify records accessible at 7 years; verify auto-archive works
  7. Query performance — Search 100M audit records by actor+date range in <2s
  8. Failure handling — If audit write fails, verify primary action is blocked (fail-closed)

Failure Injection Scenarios:

Scenario: Audit store unavailable during critical operation
Given: Audit store is configured as fail-closed (action blocked if audit fails)
When: User attempts to delete a customer record
And: Audit store connection times out
Then: Delete operation is rejected with appropriate error
And: No data is deleted from the primary store
And: System alert fires for "audit_store_unavailable"
And: Retry mechanism attempts audit write before allowing future operations

Observability Testing:

  • Verify audit event count matches application operation count (completeness ratio)
  • Confirm audit write latency does not degrade application response time beyond SLA
  • Test that audit pipeline lag alerts fire when events are delayed >10s
  • Validate integrity check jobs detect hash chain breaks

Distributed Systems Concepts:

  • Immutability: Append-only stores; no updates or deletes ever
  • Ordering: Events must reflect causal order, not just wall-clock order
  • Exactly-once: Duplicate application events must not create duplicate audit entries

Common Mistakes

  • Testing audit trail in isolation without verifying completeness against all actions
  • Not testing the fail-closed behavior (should action proceed if audit write fails?)
  • Ignoring audit event ordering in distributed systems
  • Not verifying that audit records survive backup/restore cycles

Follow-up Questions

  • How would you test that audit trails satisfy SOC 2 requirements?
  • How would you verify completeness without manually testing every operation?
  • How would you test audit trail integrity after a database migration?

Q9How would you test data retention policies? #

Objective

Demonstrate ability to test time-based data lifecycle management including archival, deletion, and compliance verification.

Interview Answer

Data retention testing verifies that data is kept exactly as long as required (no shorter for business needs, no longer for compliance) and that deletion is thorough and verifiable.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Application │     │  Retention   │────▶│  Archive Store   │
│  Database    │◀───▶│  Policy      │     │  (S3 Glacier/    │
│  (Hot Data)  │     │  Engine      │     │   Cold Storage)  │
└──────────────┘     │  (Scheduled) │     └─────────────────┘
                     └──────┬───────┘
                            │
                     ┌──────▼───────┐     ┌─────────────────┐
                     │  Deletion    │────▶│  Deletion        │
                     │  Executor    │     │  Verification    │
                     │  (Batch)     │     │  Report          │
                     └──────────────┘     └─────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Policy evaluation logic (age calculation, category matching) JUnit, pytest
Integration Actual data movement: hot → archive → delete Testcontainers, time manipulation
Contract Retention API response schemas OpenAPI validation
E2E Full lifecycle: create → age → archive → delete → verify gone Custom framework with time simulation
Chaos Deletion job failure mid-execution; verify resumability Chaos Mesh
Compliance Verify data doesn't exist past retention period Custom audit queries

Specific Test Cases:

  1. Age calculation — Data created 365 days ago with 1-year policy; verify eligible for deletion
  2. Category-specific — Financial records: 7 years; session logs: 90 days; verify each
  3. Legal hold — Data under litigation hold; verify exempt from deletion regardless of age
  4. Cascade deletion — Delete user; verify all child records (orders, messages) also deleted
  5. Archive integrity — Archive data; restore after 6 months; verify identical to original
  6. Timezone handling — Retention calculated in UTC regardless of user timezone
  7. Partial failure — Deletion job crashes at 50%; verify resumes from checkpoint, no gaps
  8. Cross-system — Data in DB, cache, search index, backups; verify deleted from ALL stores

Failure Injection Scenarios:

Scenario: Retention job encounters locked records
Given: 10,000 records are eligible for deletion
And: 500 records are locked by active transactions
When: Retention deletion job executes
Then: 9,500 unlocked records are deleted successfully
And: 500 locked records are skipped and logged
And: Job is marked partial-success with skip count
And: Next execution retries the 500 skipped records
And: No record is partially deleted (atomicity per record)

Observability Testing:

  • Verify retention job execution metrics (records scanned, archived, deleted, skipped)
  • Confirm SLA metrics for time-to-delete after policy trigger
  • Test compliance dashboard shows zero over-retained records
  • Validate that deletion certificate/report is generated per execution

Distributed Systems Concepts:

  • Eventual deletion: Data may persist in replicas/caches after primary delete
  • Consistency: All copies (replicas, backups, CDN caches) must eventually be purged
  • Idempotency: Re-running retention job must be safe (already-deleted = no-op)

Common Mistakes

  • Testing retention only in primary database, ignoring replicas, caches, and backups
  • Not testing legal hold exemption scenarios
  • Using production time instead of simulated time (tests take years to validate)
  • Not verifying that archived data is actually restorable

Follow-up Questions

  • How would you verify data is deleted from all backup tapes?
  • How would you test retention policy changes apply retroactively?
  • How would you test cross-border data residency requirements?

Q10How would you test a feature rollout at 1%, 10%, and 100%? #

Objective

Demonstrate ability to test progressive delivery systems including feature flags, canary analysis, and automated rollback.

Interview Answer

Progressive rollout requires testing the flag evaluation logic, traffic splitting accuracy, metric collection per cohort, and automated rollback triggers.

Architecture:

┌──────────┐     ┌──────────────┐     ┌─────────────────┐
│  Client  │────▶│  App Server  │────▶│  Feature Flag    │
│  (SDK)   │     │  (Flag       │     │  Service         │
└──────────┘     │   Evaluation)│     │  (LaunchDarkly/  │
                 └──────┬───────┘     │   custom)        │
                        │             └────────┬─────────┘
                        │                      │
                 ┌──────▼───────┐     ┌────────▼─────────┐
                 │  Metrics     │     │  Rollout Config  │
                 │  Pipeline    │     │  (% + targeting  │
                 │  (per cohort)│     │   rules + kill   │
                 └──────┬───────┘     │   switch)        │
                        │             └──────────────────┘
                 ┌──────▼───────┐
                 │  Automated   │
                 │  Rollback    │
                 │  (Canary     │
                 │   Analysis)  │
                 └──────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Flag evaluation, hashing consistency, targeting rules JUnit, pytest
Integration SDK ↔ flag service communication, caching behavior Testcontainers
Contract Flag service API contract Pact
E2E User in 1% cohort sees new feature; 99% sees old Playwright with flag overrides
Chaos Flag service outage; verify fallback behavior Toxiproxy
Statistical Verify traffic split accuracy (chi-squared test) Custom analysis scripts

Specific Test Cases:

  1. Sticky bucketing — Same user always gets same variant (no flickering)
  2. Distribution accuracy — At 10% rollout, verify 9.5-10.5% of traffic gets new feature
  3. Targeting rules — Internal employees see feature at 100% while external at 1%
  4. Kill switch — Flag disabled; verify ALL users see old behavior within 30 seconds
  5. Gradual ramp — Move 1% → 10% → 50% → 100%; verify no user switches from new → old
  6. Metric isolation — Error rates computed separately for control vs. treatment groups
  7. Flag dependency — Feature B requires Feature A; verify B can't enable without A
  8. Offline resilience — Flag service unavailable; verify SDK uses cached/default values

Failure Injection Scenarios:

Scenario: Automated rollback triggered by error rate spike
Given: Feature X is rolled out to 10% of users
And: Canary analysis monitors error rate and latency
When: Error rate for treatment group exceeds 2x control group
Then: Automated rollback triggers within 60 seconds
And: All users revert to control experience
And: Alert fires with rollback reason and metrics
And: No user in treatment group is stuck on broken experience > 2 minutes

Observability Testing:

  • Verify per-variant metrics: error rate, latency, conversion per flag state
  • Confirm rollout percentage matches actual traffic distribution (within ±1%)
  • Test that flag evaluation latency does not add >5ms to request path
  • Validate that rollback events are recorded with before/after state

Distributed Systems Concepts:

  • Consistency: Flag evaluation must be consistent per user across all service instances
  • Eventual consistency: Flag changes propagate to all nodes; test propagation delay
  • Idempotency: Flag evaluation is a pure function of (user, flag, config)

Common Mistakes

  • Not testing that users don't "flicker" between variants during rollout changes
  • Testing flags only in isolation, missing interactions between multiple flags
  • Not verifying that metrics are correctly attributed to flag variants
  • Ignoring the propagation delay when flag values change across distributed nodes

Follow-up Questions

  • How would you test feature flags in a microservices architecture where multiple services check the same flag?
  • How would you verify statistical significance of A/B test results?
  • How would you test flag cleanup (removing dead flags from code)?

Q11How would you test disaster recovery? #

Objective

Demonstrate ability to validate that systems can recover from catastrophic failures within defined RTO (Recovery Time Objective) and RPO (Recovery Point Objective).

Interview Answer

Disaster recovery testing verifies that when everything goes wrong — entire regions fail, databases corrupt, or ransomware encrypts systems — you can recover within business-acceptable timeframes with minimal data loss.

Architecture:

┌─────────────────────────────────────────────────────────────┐
│                     PRIMARY REGION (us-east-1)               │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐   │
│  │ App Tier │  │ DB Primary│  │ Cache    │  │ Object   │   │
│  │ (ECS)    │  │ (RDS)    │  │ (Redis)  │  │ Store(S3)│   │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘   │
└──────────────────────┬──────────────────────────────────────┘
                       │ Replication
┌──────────────────────▼──────────────────────────────────────┐
│                     DR REGION (us-west-2)                     │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐   │
│  │ App Tier │  │ DB Replica│  │ Cache    │  │ Object   │   │
│  │ (Standby)│  │ (Read    │  │ (Cold)   │  │ Store    │   │
│  │          │  │  Replica)│  │          │  │ (Replicated)│ │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘   │
└─────────────────────────────────────────────────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Failover decision logic, health check evaluation JUnit, pytest
Integration Database promotion, DNS failover, cache warming Terraform, AWS CLI
Runbook Full DR procedure execution with timing Game day exercises
Chaos Region-level failure simulation AWS FIS, Gremlin, Chaos Monkey
Validation Data integrity post-recovery, transaction consistency Custom verification scripts
Timing RTO measurement (time to recover), RPO measurement (data loss) Stopwatch + automated metrics

Specific Test Cases:

  1. RTO verification — Simulate primary region failure; measure time to full recovery (<4h)
  2. RPO verification — Check last replicated transaction in DR; verify data loss <5 min
  3. DNS failover — Primary health check fails; verify DNS routes to DR within TTL
  4. Data integrity — After failover, run checksums on critical tables; verify no corruption
  5. Application state — In-flight transactions during failover; verify none are lost silently
  6. Failback — After recovery, fail back to primary; verify no data conflicts
  7. Partial failure — Only database fails (not compute); verify targeted recovery
  8. Communication — Verify status page updates and team notifications fire correctly

Failure Injection Scenarios:

Scenario: Complete primary region outage
Given: Production is running in us-east-1 with DR in us-west-2
And: Continuous replication lag is <30 seconds
When: All us-east-1 availability zones become unreachable
Then: Health checks fail within 30 seconds
And: DNS failover initiates within 60 seconds
And: DR database is promoted to primary within 5 minutes
And: Application tier in DR scales up within 10 minutes
And: Full service restoration achieved within RTO (4 hours)
And: Data loss does not exceed RPO (5 minutes)

Observability Testing:

  • Verify replication lag metrics are emitted and alerting is configured
  • Confirm DR readiness dashboard shows real-time status of all DR components
  • Test that runbook automation correctly reports progress during failover
  • Validate post-recovery health check suite passes before traffic is routed

Distributed Systems Concepts:

  • RPO vs RTO: Recovery Point (data loss tolerance) vs Recovery Time (downtime tolerance)
  • Consistency during failover: Transactions in-flight during switch may be lost
  • Split-brain prevention: Ensure old primary doesn't accept writes after failover

Common Mistakes

  • Never actually testing DR (only having it documented)
  • Testing DR once and assuming it still works after architecture changes
  • Not measuring actual RTO/RPO during tests (just verifying "it works")
  • Ignoring the failback procedure (returning to primary after DR event)

Follow-up Questions

  • How often should DR tests be conducted?
  • How would you test DR for a multi-region active-active architecture?
  • What's your approach to DR testing without impacting production users?

Q12How would you test backup and restore? #

Objective

Demonstrate ability to verify backup completeness, integrity, restore speed, and recoverability under various failure scenarios.

Interview Answer

Backup testing is not just verifying backups exist — it's verifying they can be restored successfully within time constraints and that the restored data is complete and consistent.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Production  │────▶│  Backup      │────▶│  Backup Storage  │
│  Database    │     │  Agent       │     │  (S3/Glacier     │
│  (PostgreSQL)│     │  (pg_dump/   │     │   encrypted)     │
└──────────────┘     │   WAL archive)│    └─────────────────┘
                     └──────────────┘              │
                                                   │
┌──────────────┐     ┌──────────────┐     ┌───────▼─────────┐
│  Restored    │◀────│  Restore     │◀────│  Backup          │
│  Database    │     │  Process     │     │  Catalog         │
│  (Isolated)  │     │  (Automated) │     │  (Metadata)      │
└──────────────┘     └──────────────┘     └─────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Backup scheduling logic, retention policy evaluation JUnit, pytest
Integration Full backup and restore cycle to isolated environment pgBackRest, Testcontainers
Validation Row counts, checksums, referential integrity post-restore Custom SQL scripts
Performance Restore time for various database sizes Time measurement, benchmarks
Chaos Corrupted backup file, partial backup, storage unavailable Fault injection
Security Backup encryption, access control verification AWS KMS tests

Specific Test Cases:

  1. Full restore — Restore latest backup; verify row counts match production ±0
  2. Point-in-time recovery — Restore to specific timestamp; verify transaction at T visible, T+1 not
  3. Incremental restore — Restore from full + 7 incrementals; verify consistent state
  4. Corruption detection — Flip bits in backup file; verify restore fails with clear error
  5. Encryption — Verify backup is unreadable without correct KMS key
  6. Cross-region restore — Restore backup in different region; verify success
  7. Restore time — 1TB database restores within 2 hours (SLA verification)
  8. Application compatibility — Restored DB works with current application version

Failure Injection Scenarios:

Scenario: Latest backup is corrupted, must use previous
Given: Daily backups are taken at midnight
And: Today's backup file has checksum mismatch (corrupted)
When: Restore is attempted from today's backup
Then: Restore process detects corruption via checksum verification
And: Alert fires for "backup_integrity_failure"
And: System automatically attempts restore from yesterday's backup
And: Successful restore achieves RPO of 24h + WAL replay
And: Incident report identifies corruption cause

Observability Testing:

  • Verify backup completion metrics (success/failure, duration, size)
  • Confirm backup integrity check runs daily and reports results
  • Test that restore time metrics are tracked per database size
  • Validate backup catalog accurately reflects available restore points

Distributed Systems Concepts:

  • Consistency: Point-in-time recovery requires WAL (Write-Ahead Log) completeness
  • Durability: Backups must survive the same failure that took down the primary
  • Isolation: Restore testing must not impact production systems

Common Mistakes

  • Only testing that backups are created, never testing restore
  • Not measuring restore time as databases grow over time
  • Storing backups in the same failure domain as production
  • Not testing that restored databases are compatible with current application code

Follow-up Questions

  • How would you test backup verification for a 50TB database cost-effectively?
  • How would you handle backup testing for databases with PII (masking)?
  • How would you test logical backup vs. physical backup restore differences?

Q13How would you test a caching layer? #

Objective

Demonstrate understanding of cache coherence testing, invalidation strategies, thundering herd prevention, and performance verification.

Interview Answer

Caching introduces an eventual consistency layer that can serve stale data, fail in complex ways, and create performance cliffs when cold. Testing must cover hit/miss behavior, invalidation correctness, and failure modes.

Architecture:

┌──────────┐     ┌──────────────┐     ┌─────────────────┐
│  Client  │────▶│  App Server  │────▶│  Cache (Redis/   │
│          │◀────│              │◀────│   Memcached)     │
└──────────┘     └──────┬───────┘     └────────┬─────────┘
                        │                      │ Miss
                        │              ┌───────▼─────────┐
                        │              │  Database       │
                        └──────────────│  (Source of     │
                                       │   Truth)        │
                                       └─────────────────┘

Cache Patterns:
┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
│  Cache-Aside    │  │  Write-Through  │  │  Write-Behind   │
│  App manages    │  │  Cache + DB in  │  │  Cache first,   │
│  cache reads    │  │  sync writes    │  │  async DB write │
└─────────────────┘  └─────────────────┘  └─────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Cache key generation, TTL calculation, serialization JUnit, pytest
Integration Cache-aside pattern, invalidation on write Testcontainers (Redis)
Contract Cache serialization format compatibility across versions Schema validation
E2E Update data → verify cache serves updated value within TTL API tests with timing
Chaos Cache node failure, network partition between app and cache Toxiproxy
Load Thundering herd: cache expires, 10K requests hit DB simultaneously k6, Gatling

Specific Test Cases:

  1. Cache hit — Request same resource twice; verify second request served from cache (faster)
  2. Invalidation — Update record; verify subsequent reads return new value
  3. TTL expiry — Set 60s TTL; verify cached value disappears after 60s
  4. Thundering herd — Expire popular key; verify only 1 request goes to DB (lock/dogpile prevention)
  5. Cache stampede — Clear entire cache; verify system survives cold-cache load
  6. Serialization — Store complex object; verify deserialized value matches exactly
  7. Memory pressure — Fill cache to capacity; verify LRU eviction behavior
  8. Stale read — Write new value; immediately read; verify consistency per pattern

Failure Injection Scenarios:

Scenario: Redis cluster node failure
Given: Application uses Redis cluster with 3 nodes
And: Cache hit rate is 95%
When: One Redis node becomes unreachable
Then: Application falls back to database for affected keys
And: Response latency increases but stays within SLA (p99 < 2s)
And: No errors returned to clients (graceful degradation)
And: Cache hit rate metric drops (alerting fires)
And: When node recovers, cache gradually warms without stampede

Observability Testing:

  • Verify cache hit/miss ratio metrics per endpoint
  • Confirm cache latency vs. database latency comparison dashboards
  • Test that eviction rate alerts fire when memory utilization >90%
  • Validate that cache warm-up time is tracked after cold starts

Distributed Systems Concepts:

  • Eventual consistency: Cache may serve stale data within TTL window
  • CAP trade-off: Cache prioritizes availability (serve stale) over consistency
  • Idempotency: Cache writes must be idempotent (same write repeated = safe)

Common Mistakes

  • Testing only cache hits, never testing miss path and DB fallback
  • Not testing cache invalidation under concurrent writes
  • Ignoring thundering herd scenario when popular keys expire
  • Not testing application behavior when cache is completely unavailable

Follow-up Questions

  • How would you test cache warming strategies for a new deployment?
  • How would you test multi-level caching (L1 local + L2 distributed)?
  • How would you verify that sensitive data isn't cached inappropriately?

Q14How would you test a queue-based workflow? #

Objective

Demonstrate ability to test asynchronous processing systems with ordering guarantees, retry logic, dead-letter handling, and exactly-once semantics.

Interview Answer

Queue-based workflows decouple producers from consumers, introducing challenges around ordering, retry behavior, poison messages, and backpressure. Testing must verify the system handles all these correctly.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Producer    │────▶│  Message     │────▶│  Consumer        │
│  (API/Event) │     │  Queue       │     │  (Worker)        │
└──────────────┘     │  (SQS/Kafka/ │     └────────┬─────────┘
                     │   RabbitMQ)  │              │
                     └──────┬───────┘              │ Processing
                            │                      │ failure
                     ┌──────▼───────┐     ┌───────▼──────────┐
                     │  Dead Letter │     │  Result Store    │
                     │  Queue (DLQ) │     │  (DB/Event)      │
                     └──────────────┘     └──────────────────┘

Retry Strategy:
┌────────┐   ┌────────┐   ┌────────┐   ┌────────┐   ┌──────┐
│ Attempt│──▶│ Wait   │──▶│ Attempt│──▶│ Wait   │──▶│ DLQ  │
│   1    │   │  1s    │   │   2    │   │  4s    │   │      │
└────────┘   └────────┘   └────────┘   └────────┘   └──────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Message serialization, retry logic, idempotency key generation JUnit, pytest
Integration Produce → consume → result verification Testcontainers (SQS/Kafka)
Contract Message schema between producer and consumer AsyncAPI, Pact
E2E Full workflow: trigger → queue → process → outcome visible Custom framework
Chaos Consumer crash mid-processing, queue unavailable Toxiproxy, Chaos Mesh
Load 100K messages/sec throughput, consumer scaling behavior k6, custom producers

Specific Test Cases:

  1. At-least-once delivery — Kill consumer mid-processing; verify message redelivered
  2. Idempotent processing — Same message consumed twice; verify single side-effect
  3. Ordering — Send messages 1,2,3; verify processed in order (for ordered queues)
  4. Poison message — Message always fails processing; verify moves to DLQ after N retries
  5. Backpressure — Produce 10x faster than consume; verify queue depth grows, no loss
  6. Visibility timeout — Consumer takes too long; verify message becomes visible to others
  7. Batch processing — Process batch of 10; if 1 fails, verify other 9 succeed
  8. Schema evolution — Send v2 message to v1 consumer; verify graceful handling

Failure Injection Scenarios:

Scenario: Consumer crashes mid-processing
Given: Message "process-order-123" is in the queue
And: Consumer picks up the message and begins processing
When: Consumer process is killed at 50% completion
Then: Message visibility timeout expires (30s)
And: Message becomes available for another consumer
And: New consumer processes the message from scratch
And: Idempotency logic prevents duplicate side-effects
And: Order is processed exactly once despite the crash

Observability Testing:

  • Verify queue depth metrics trigger auto-scaling at threshold
  • Confirm processing latency histograms per message type
  • Test that DLQ depth alerts fire immediately (any message in DLQ is exceptional)
  • Validate end-to-end latency from produce to result-visible

Distributed Systems Concepts:

  • At-least-once delivery: Messages may be delivered multiple times; consumers must be idempotent
  • Ordering guarantees: FIFO queues vs. standard queues; test both behaviors
  • Backpressure: System must handle producer outpacing consumer without data loss
  • Exactly-once semantics: Achieved via idempotent consumers, not queue guarantees

Common Mistakes

  • Assuming exactly-once delivery from the queue (most offer at-least-once)
  • Not testing consumer idempotency under message redelivery
  • Ignoring DLQ monitoring (poison messages silently accumulate)
  • Not testing message schema evolution between producer and consumer versions

Follow-up Questions

  • How would you test message ordering in a partitioned topic (Kafka)?
  • How would you test consumer group rebalancing behavior?
  • How would you test queue-based workflows that span multiple services?

Q15How would you test concurrent edits? #

Objective

Demonstrate ability to test systems where multiple users modify the same resource simultaneously, requiring conflict detection and resolution.

Interview Answer

Concurrent edit testing verifies that when multiple users modify the same data simultaneously, the system either prevents conflicts (pessimistic locking) or detects and resolves them (optimistic concurrency control).

Architecture:

┌──────────┐                              ┌──────────┐
│  User A  │──── Edit Document ──────────▶│          │
│  (v1→v2) │                              │  Server  │
└──────────┘                              │          │
                                          │  (OCC/   │
┌──────────┐                              │   CRDT/  │
│  User B  │──── Edit Document ──────────▶│   OT)    │
│  (v1→v3) │                              │          │
└──────────┘                              └────┬─────┘
                                               │
                                        ┌──────▼──────┐
                                        │  Conflict   │
                                        │  Resolution │
                                        │  Strategy   │
                                        ├─────────────┤
                                        │ • Last Write│
                                        │   Wins      │
                                        │ • Merge     │
                                        │ • Reject    │
                                        │ • CRDT      │
                                        └─────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Version comparison, merge algorithms, CRDT logic JUnit, pytest, property-based testing
Integration Optimistic locking with real database Testcontainers
Contract ETag/If-Match header behavior per API spec REST Assured
E2E Two browser sessions editing same document Playwright (parallel contexts)
Chaos Network delay causing version desync Toxiproxy
Load 100 concurrent editors on same document k6, custom concurrent clients

Specific Test Cases:

  1. Optimistic locking — User A and B read v1; A saves first (succeeds); B saves (409 conflict)
  2. ETag validation — PUT without matching ETag; verify 412 Precondition Failed
  3. Last-write-wins — Two concurrent writes; verify last timestamp wins, no corruption
  4. Field-level merge — A edits title, B edits body; verify both changes preserved
  5. Conflict notification — B gets conflict; verify UI shows diff and merge options
  6. CRDT convergence — Concurrent edits on collaborative doc; verify all clients converge
  7. Lost update prevention — Read-modify-write without version check; verify system rejects
  8. Deadlock detection — Two users lock resources in opposite order; verify timeout + recovery

Failure Injection Scenarios:

Scenario: Network delay causes version conflict
Given: User A and User B both read document at version 5
And: Network to User B has 5-second artificial delay
When: User A saves changes (document becomes version 6)
And: User B saves changes (still referencing version 5)
Then: User B receives 409 Conflict response
And: Response includes current version (6) and A's changes
And: User B can review diff and re-submit with merge
And: No data from User A's edit is lost

Observability Testing:

  • Verify conflict rate metrics per resource type
  • Confirm version skew metrics (how often clients have stale versions)
  • Test that lock wait time histograms detect deadlock-prone patterns
  • Validate that conflict resolution audit trail records who won and what was merged

Distributed Systems Concepts:

  • Optimistic Concurrency Control (OCC): Allow all writes, reject on version mismatch
  • CRDTs: Conflict-free Replicated Data Types enable merge without coordination
  • Vector clocks: Detect concurrent vs. causal modifications
  • Linearizability: Strongest consistency; every read reflects the latest write

Common Mistakes

  • Testing concurrent edits with artificial delays instead of actual parallelism
  • Not testing the conflict resolution UX (just the backend detection)
  • Ignoring the read-modify-write race condition in test design
  • Not testing what happens when merge produces nonsensical results

Follow-up Questions

  • How would you test operational transformation for a real-time collaborative editor?
  • How would you benchmark conflict rates to determine if OCC or pessimistic locking is better?
  • How would you test concurrent edits across microservices with distributed transactions?

Q16How would you test conflict resolution? #

Objective

Demonstrate deep understanding of how distributed systems resolve conflicting state changes and how to verify correctness of resolution strategies.

Interview Answer

Conflict resolution goes beyond detection — it's about the strategy used when two valid writes collide. Testing must verify that the chosen strategy (LWW, merge, manual, CRDT) produces correct, predictable results.

Architecture:

┌──────────────┐          ┌──────────────┐
│  Replica A   │          │  Replica B   │
│  (DC-East)   │          │  (DC-West)   │
│  Write: X=5  │          │  Write: X=7  │
│  @T1         │          │  @T2         │
└──────┬───────┘          └──────┬───────┘
       │                         │
       └────────────┬────────────┘
                    │
           ┌───────▼────────┐
           │  Conflict       │
           │  Resolution     │
           │  Engine         │
           ├────────────────┤
           │  Strategies:    │
           │  • LWW (T2>T1)  │
           │    → X=7 wins   │
           │  • Max wins     │
           │    → X=7 wins   │
           │  • Merge (set)  │
           │    → X={5,7}    │
           │  • Custom rule  │
           │    → App logic  │
           └────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Resolution algorithm correctness, edge cases Property-based testing (Hypothesis)
Integration Multi-replica conflict detection and resolution Multi-node test clusters
Contract Resolution outcome format and metadata Schema validation
E2E User experience during and after conflict Playwright
Chaos Network partition → concurrent writes → heal → resolve Chaos Mesh, Jepsen
Formal Model checking resolution algorithm properties TLA+, Alloy

Specific Test Cases:

  1. Last-Write-Wins (LWW) — Two writes with known timestamps; verify later timestamp wins
  2. Sibling creation — Concurrent writes with no causal relation; verify siblings stored
  3. Application-level merge — Shopping cart conflict; verify union of items (no loss)
  4. Semantic resolution — Counter incremented on both sides; verify sum (not max)
  5. Conflict metadata — After resolution, verify audit trail records both values and decision
  6. Convergence — All replicas reach same state regardless of message arrival order
  7. Idempotent resolution — Apply same conflict resolution twice; verify same outcome
  8. Cascading conflicts — Resolve A, which triggers conflict in B; verify chain resolves

Failure Injection Scenarios:

Scenario: Network partition creates divergent state
Given: Document exists at version 10 in both DC-East and DC-West
When: Network partition isolates the two data centers
And: DC-East user edits title to "Hello" (version 11a)
And: DC-West user edits title to "World" (version 11b)
And: Network partition heals
Then: Conflict resolution engine detects divergent versions
And: Resolution strategy (configured as LWW) selects latest timestamp
And: Both replicas converge to same value within 5 seconds
And: Losing write is preserved in conflict history for audit
And: Application notifies losing user of the resolution

Observability Testing:

  • Verify conflict rate metrics per data type and region pair
  • Confirm resolution strategy selection metrics (which strategy used)
  • Test that unresolved conflict alerts fire when manual intervention needed
  • Validate convergence time metrics across replicas

Distributed Systems Concepts:

  • Vector clocks: Detect true concurrency vs. causal ordering
  • CRDTs: Data structures that merge without conflicts by design
  • Eventual consistency: All replicas converge eventually; test convergence time
  • Commutativity: Resolution must produce same result regardless of operation order

Common Mistakes

  • Only testing LWW without considering data loss implications
  • Not testing what happens when clocks are skewed (LWW becomes non-deterministic)
  • Ignoring the user experience when their write "loses" a conflict
  • Not testing convergence — just testing that resolution runs without verifying all replicas agree

Follow-up Questions

  • How would you test custom conflict resolution logic for a domain-specific merge?
  • How would you verify that CRDTs converge under all possible operation sequences?
  • What's the trade-off between automatic resolution and manual conflict handling?

Q17How would you test clock skew? #

Objective

Demonstrate understanding of time-dependent system behavior and how clock drift between nodes can cause subtle bugs in distributed systems.

Interview Answer

Clock skew is the difference in time between machines in a distributed system. It affects everything from distributed locks to event ordering to cache TTLs. Testing requires deliberately introducing time differences.

Architecture:

┌────────────────────────────────────────────────────────┐
│  Distributed System with Clock-Dependent Components     │
│                                                         │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐             │
│  │  Node A  │  │  Node B  │  │  Node C  │             │
│  │  T=12:00 │  │  T=12:05 │  │  T=11:58 │             │
│  │  :00.000 │  │  :00.000 │  │  :00.000 │             │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘             │
│       │              │              │                   │
│  Clock-Dependent Operations:                            │
│  • Distributed locks (lease expiry)                     │
│  • Event ordering (timestamp-based)                     │
│  • Cache TTL (expiration timing)                        │
│  • Certificate validation (not-before/not-after)        │
│  • Rate limiting (time windows)                         │
│  • Scheduled jobs (cron triggers)                       │
└────────────────────────────────────────────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Time-dependent logic with injected clocks Clock mocking (libfaketime)
Integration Distributed lock behavior under skew Testcontainers + clock manipulation
Contract Timestamp format and timezone handling Schema validation
E2E Event ordering when nodes have different clocks Multi-node test cluster
Chaos NTP failure, clock jump forward/backward Chaos Mesh (TimeChaos)
Formal Verify algorithm correctness under bounded skew TLA+

Specific Test Cases:

  1. Lock expiry — Node A acquires lock; clock skew causes Node B to see it as expired; verify no double-acquisition
  2. Event ordering — Events from skewed nodes; verify logical ordering (not just timestamps)
  3. Cache TTL — Set 60s TTL; one node's clock is 30s ahead; verify no premature eviction
  4. Certificate validation — Server clock 5 min ahead of CA's not-before; verify handling
  5. Rate limiting — Node's clock jumps forward; verify rate limiter doesn't allow burst
  6. Lease renewal — Clock goes backward; verify lease doesn't accidentally double its duration
  7. Hybrid logical clocks — Verify HLC provides causal ordering despite physical clock skew
  8. NTP recovery — Clock jumps 30 seconds on NTP sync; verify system handles discontinuity

Failure Injection Scenarios:

Scenario: Clock skew causes distributed lock double-acquisition
Given: Node A holds a distributed lock with 30-second TTL
And: Node A's clock is 10 seconds behind Node B's clock
When: Node A believes the lock has 15 seconds remaining
But: Node B's clock shows the lock expired 5 seconds ago
Then: System uses fencing tokens (not wall-clock) for lock validity
And: If Node B attempts to acquire lock, fencing token prevents conflict
And: Operations protected by the lock maintain correctness
And: Clock skew metric alerts fire when skew > 5 seconds

Observability Testing:

  • Verify clock skew metrics between all node pairs
  • Confirm NTP sync status monitoring and alerting
  • Test that clock jump events are logged with magnitude and direction
  • Validate that hybrid logical clock counters advance correctly

Distributed Systems Concepts:

  • Logical clocks (Lamport): Order events without physical time synchronization
  • Hybrid Logical Clocks: Combine physical time with logical counters
  • Fencing tokens: Prevent stale lock holders from making changes
  • Bounded skew assumption: Many algorithms assume max skew (e.g., 500ms)

Common Mistakes

  • Relying on synchronized wall clocks for ordering in distributed systems
  • Not testing what happens when NTP daemon fails or clock jumps
  • Testing only small skew (milliseconds) when real skew can be seconds
  • Using system clock directly instead of injectable clock abstraction

Follow-up Questions

  • How would you test a system that uses Google's TrueTime API?
  • What's the maximum clock skew your system can tolerate and how did you determine it?
  • How would you test leap second handling?

Q18How would you test time-based jobs? #

Objective

Demonstrate ability to test scheduled task execution, timing accuracy, overlap prevention, and failure recovery for cron-like systems.

Interview Answer

Time-based jobs (cron, scheduled tasks) are notoriously difficult to test because they depend on calendar time, can overlap if slow, and fail silently. Testing must cover timing accuracy, idempotency, and failure handling.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Scheduler   │────▶│  Job Queue   │────▶│  Worker Pool     │
│  (Cron/      │     │  (Priority   │     │  (Execution      │
│   Quartz/    │     │   Queue)     │     │   Environment)   │
│   CloudWatch)│     └──────────────┘     └────────┬─────────┘
└──────────────┘                                   │
                                          ┌────────▼─────────┐
                                          │  Job State Store  │
                                          │  (Started/Done/   │
                                          │   Failed/Locked)  │
                                          └────────┬─────────┘
                                                   │
                                          ┌────────▼─────────┐
                                          │  Distributed Lock │
                                          │  (Prevent overlap)│
                                          └──────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Job logic, schedule expression parsing, idempotency JUnit with clock injection
Integration Full job execution with real dependencies Testcontainers
Contract Job input/output schemas Schema validation
E2E Schedule → execute → verify outcome Custom test harness with time control
Chaos Worker crash mid-job, scheduler node failure Chaos Mesh
Timing DST transitions, leap years, timezone boundary behavior libfaketime

Specific Test Cases:

  1. Schedule accuracy — Job set for 03:00 UTC; verify execution starts within ±1 second
  2. No overlap — Job runs for 90 seconds on 60-second schedule; verify no parallel execution
  3. DST handling — Job at 02:30 local time; verify behavior during spring-forward (02:30 doesn't exist)
  4. Idempotent execution — Same job runs twice; verify no duplicate side-effects
  5. Failure retry — Job fails on attempt 1; verify retry with backoff; verify eventual success
  6. Stale lock cleanup — Worker crashes holding lock; verify lock released after timeout
  7. Catch-up behavior — System was down for 3 hours; verify missed jobs execute or skip per policy
  8. Concurrent schedulers — Two scheduler instances; verify job executes exactly once

Failure Injection Scenarios:

Scenario: Worker crashes during job execution
Given: Daily report generation job starts at 03:00
And: Job has been running for 5 minutes (50% complete)
When: Worker process is killed (OOM, hardware failure)
Then: Job lock TTL expires after configured timeout (10 min)
And: Scheduler detects missed heartbeat
And: Job is re-queued for execution on healthy worker
And: Idempotent design ensures no partial/duplicate data
And: Job completes successfully on retry
And: Alert fires for "job_execution_failure" with job context

Observability Testing:

  • Verify job execution duration metrics per job type
  • Confirm schedule drift metrics (difference between expected and actual start time)
  • Test that job failure alerts include execution context and stack trace
  • Validate that missed execution alerts fire when expected job doesn't run

Distributed Systems Concepts:

  • Distributed locking: Prevent same job running on multiple nodes
  • Idempotency: Jobs must be safely re-runnable (crash recovery)
  • Exactly-once execution: Achieved via distributed lock + idempotent logic
  • Clock dependency: Job scheduling depends on consistent time across nodes

Common Mistakes

  • Testing jobs only at current time, not at boundary conditions (midnight, DST, New Year)
  • Not testing the overlap prevention mechanism under slow job execution
  • Ignoring the catch-up problem (what happens to missed jobs after outage)
  • Not testing scheduler high-availability (what if scheduler node dies)

Follow-up Questions

  • How would you test a job that must run exactly once across a 50-node cluster?
  • How would you test jobs that have dependencies (Job B runs after Job A)?
  • How would you test time-based jobs during a cloud provider's maintenance window?

Q19How would you test data synchronization? #

Objective

Demonstrate ability to test bidirectional data sync between systems with conflict handling, eventual consistency verification, and integrity checks.

Interview Answer

Data synchronization testing verifies that multiple systems maintain consistent state despite operating independently, handling conflicts, network failures, and schema differences.

Architecture:

┌──────────────┐                         ┌──────────────┐
│  System A    │                         │  System B    │
│  (CRM)      │                         │  (ERP)       │
│  ┌────────┐ │     ┌──────────────┐    │ ┌────────┐  │
│  │Customer│ │────▶│  Sync Engine │◀───│ │Customer│  │
│  │Records │ │◀────│  (CDC +      │───▶│ │Records │  │
│  └────────┘ │     │   Transform) │    │ └────────┘  │
└──────────────┘     └──────┬───────┘    └──────────────┘
                            │
                     ┌──────▼───────┐
                     │  Conflict    │
                     │  Resolution  │
                     │  + Audit Log │
                     └──────────────┘

Sync Patterns:
┌───────────────┐  ┌───────────────┐  ┌───────────────┐
│  Unidirectional│ │  Bidirectional│  │  Event-Driven │
│  A → B only   │  │  A ↔ B merge │  │  Pub/Sub sync │
└───────────────┘  └───────────────┘  └───────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Field mapping, transformation logic, conflict rules JUnit, pytest
Integration Full sync cycle between real instances Testcontainers, sandbox APIs
Contract Data format compatibility between systems Schema registry, Pact
E2E Create in A → verify in B; update in B → verify in A API tests with polling
Chaos Network partition during sync, partial sync failure Toxiproxy
Data Quality Row counts, checksums, referential integrity Great Expectations, dbt tests

Specific Test Cases:

  1. Initial full sync — Sync 1M records from A to B; verify count and checksum match
  2. Incremental sync — Create 100 records in A; verify they appear in B within SLA
  3. Bidirectional conflict — Update same record in A and B simultaneously; verify resolution
  4. Schema mismatch — A has field X that B doesn't; verify graceful handling (map or ignore)
  5. Delete propagation — Delete in A; verify soft/hard delete in B per configuration
  6. Ordering — Rapid updates to same record; verify final state is consistent
  7. Idempotent replay — Replay sync events; verify no duplicate records created
  8. Large payload — Record with 10MB blob field; verify sync handles size limits

Failure Injection Scenarios:

Scenario: Sync engine crashes mid-batch
Given: Sync engine is processing a batch of 1000 records from System A to B
And: 600 records have been successfully synced
When: Sync engine process crashes
Then: Checkpoint records position at record 600
And: On restart, sync resumes from record 601 (not from beginning)
And: No records are duplicated in System B
And: Sync completion metrics show the interruption
And: Total sync completes within SLA despite the crash

Observability Testing:

  • Verify sync lag metrics (time between source change and target update)
  • Confirm record count reconciliation runs hourly and alerts on drift
  • Test that sync failure rate metrics fire alerts at configured threshold
  • Validate that conflict resolution audit shows source, target, and outcome

Distributed Systems Concepts:

  • Eventual consistency: Synced systems will be temporarily inconsistent; test the window
  • Idempotency: Sync operations must be safely repeatable (crash recovery)
  • Causal consistency: Related records must sync in dependency order
  • Conflict-free operations: Design data model to minimize sync conflicts

Common Mistakes

  • Testing sync only with small datasets (missing performance issues at scale)
  • Not testing bidirectional conflicts (only testing unidirectional flow)
  • Ignoring the ordering of related records (parent must sync before child)
  • Not verifying that sync doesn't lose data during schema evolution

Follow-up Questions

  • How would you test sync between systems with different consistency models?
  • How would you verify data integrity when sync involves lossy transformations?
  • How would you test offline-first mobile sync with server reconciliation?

Q20How would you test a third-party integration? #

Objective

Demonstrate ability to test systems that depend on external services you don't control, including contract testing, fallback behavior, and sandbox limitations.

Interview Answer

Third-party integration testing is challenging because you don't control the external service, sandboxes may not match production, and the service can change without notice. The strategy must cover both the happy path and degraded states.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Your        │────▶│  Integration │────▶│  Third-Party     │
│  Application │◀────│  Layer       │◀────│  Service (API)   │
└──────────────┘     │  (Adapter    │     │  • Stripe        │
                     │   Pattern)   │     │  • Twilio        │
                     └──────┬───────┘     │  • Salesforce    │
                            │             └─────────────────┘
                     ┌──────▼───────┐
                     │  Fallback/   │
                     │  Circuit     │
                     │  Breaker     │
                     └──────┬───────┘
                            │
                     ┌──────▼───────┐
                     │  Contract    │
                     │  Tests       │
                     │  (Recorded   │
                     │   Responses) │
                     └──────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Request building, response parsing, error mapping JUnit with WireMock
Integration Full API interaction with sandbox/test mode Provider sandboxes
Contract API response schema hasn't changed Pact, Prism, recorded fixtures
E2E Full user flow through third-party interaction Provider test modes
Chaos Third-party timeout, 500 errors, rate limiting Toxiproxy, WireMock
Monitoring Production traffic anomaly detection Canary requests, synthetic monitoring

Specific Test Cases:

  1. Happy path — Full integration cycle in sandbox (e.g., create charge in Stripe test mode)
  2. Timeout handling — Third-party takes 30s to respond; verify your timeout + fallback
  3. Rate limiting — Exceed third-party rate limit; verify backoff and retry logic
  4. Schema change — Provider adds new field; verify your parser handles gracefully
  5. Authentication expiry — OAuth token expires mid-request; verify refresh and retry
  6. Webhook verification — Verify webhook signature validation rejects tampered payloads
  7. Idempotency — Retry failed request; verify idempotency key prevents duplicates
  8. Deprecated API — Test with sunset header; verify deprecation alert triggers

Failure Injection Scenarios:

Scenario: Third-party service returns unexpected response format
Given: Integration with payment provider expects JSON response
And: Provider has deployed a breaking change to their API
When: Your service sends a valid payment request
And: Response contains unexpected field structure
Then: Response parser fails gracefully (no crash)
And: Error is logged with full request/response for debugging
And: Circuit breaker opens after 5 consecutive parsing failures
And: Fallback behavior activates (e.g., queue for manual processing)
And: Alert fires for "integration_schema_mismatch"

Observability Testing:

  • Verify third-party response time metrics (to detect their degradation)
  • Confirm error rate by error type (timeout, 4xx, 5xx, parsing)
  • Test that circuit breaker state changes emit events
  • Validate canary health checks verify integration is alive

Distributed Systems Concepts:

  • Circuit breaker pattern: Prevent cascading failure from third-party outage
  • Idempotency: Third-party operations must be retryable without side-effects
  • Eventual consistency: Webhook delivery may be delayed or out of order
  • Contract evolution: External APIs change; test forward compatibility

Common Mistakes

  • Testing only against mock/sandbox, never verifying production behavior
  • Not testing the timeout/circuit-breaker path (only testing when third-party is healthy)
  • Assuming sandbox perfectly mirrors production behavior
  • Not monitoring third-party response times and error rates in production

Follow-up Questions

  • How would you handle a third-party that doesn't offer a sandbox?
  • How would you test webhook delivery reliability?
  • How would you detect and respond to unannounced third-party API changes?

Q21How would you test failover? #

Objective

Demonstrate ability to verify that systems automatically switch to backup components when primary components fail, maintaining availability within SLA.

Interview Answer

Failover testing verifies that when a primary component fails, traffic is routed to a healthy standby with minimal disruption. This applies to databases, application servers, load balancers, and entire regions.

Architecture:

┌──────────────┐     ┌──────────────┐
│  Load        │────▶│  Primary     │──── Health Check ────┐
│  Balancer    │     │  Instance    │                      │
│  (Route53/   │     └──────────────┘                      │
│   ALB)       │                                           │
│              │     ┌──────────────┐              ┌───────▼───────┐
│              │────▶│  Standby     │              │  Health       │
│              │     │  Instance    │◀─────────────│  Monitor      │
└──────────────┘     └──────────────┘  Promote     │  (Failover    │
                                       on failure   │   Controller) │
                                                   └───────────────┘

Failover Types:
┌───────────────┐  ┌───────────────┐  ┌───────────────┐
│  Active-      │  │  Active-      │  │  Active-      │
│  Passive      │  │  Active       │  │  Active-      │
│  (Cold standby)│ │  (Load shared)│  │  Active (Multi│
│               │  │               │  │   Region)     │
└───────────────┘  └───────────────┘  └───────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Health check logic, failover decision criteria JUnit, pytest
Integration Database promotion, connection re-routing AWS RDS failover, Testcontainers
Runbook Manual failover procedure timing and correctness Game day exercises
Chaos Kill primary instance; measure failover time Chaos Monkey, AWS FIS
E2E User traffic during failover; measure error rate Synthetic monitoring + load test
Validation Data consistency after failover Custom verification queries

Specific Test Cases:

  1. Detection time — Primary fails; measure time until health check detects failure (<30s)
  2. Switchover time — From detection to standby serving traffic; measure total (<60s)
  3. Connection draining — In-flight requests during failover; verify graceful handling
  4. Data consistency — After DB failover, verify no committed transactions lost
  5. DNS propagation — DNS-based failover; verify clients get new IP within TTL
  6. Cascading failure — Primary and standby both fail; verify escalation procedure works
  7. False positive prevention — Transient network blip; verify no unnecessary failover
  8. Failback — After primary recovers; verify clean failback without data conflicts

Failure Injection Scenarios:

Scenario: Database primary node failure
Given: PostgreSQL primary with synchronous replica (standby)
And: Application is connected to primary for read/write
When: Primary node is terminated (process kill, not graceful)
Then: Health check detects failure within 10 seconds
And: Standby is promoted to primary within 30 seconds
And: Application connection pool reconnects to new primary
And: In-flight transactions receive connection error (expected)
And: New transactions succeed on promoted standby
And: Zero committed data is lost (synchronous replication)
And: Total user-visible downtime < 60 seconds

Observability Testing:

  • Verify failover duration metrics (detection time + promotion time + routing time)
  • Confirm alert fires immediately on failover initiation
  • Test that connection pool metrics show reconnection pattern during failover
  • Validate that request error rate during failover is within acceptable bounds

Distributed Systems Concepts:

  • Availability vs Consistency: During failover, system may sacrifice one temporarily
  • Split-brain prevention: Old primary must not accept writes after failover
  • Replication lag: Async replication means standby may be behind; measure data loss
  • Fencing: Prevent old primary from causing damage (STONITH)

Common Mistakes

  • Only testing planned failover (graceful), never unplanned (crash)
  • Not measuring actual failover time in realistic conditions
  • Not testing what happens to in-flight requests during failover
  • Not verifying data consistency after failover completes

Follow-up Questions

  • How would you test failover for a stateful service (e.g., WebSocket connections)?
  • How would you test cascading failover (primary → secondary → tertiary)?
  • What's your approach to testing failover without impacting production users?

Q22How would you test a circuit breaker? #

Objective

Demonstrate understanding of the circuit breaker pattern — testing state transitions (closed → open → half-open → closed), threshold tuning, and impact on system behavior.

Interview Answer

Circuit breakers prevent cascading failures by stopping requests to a failing dependency. Testing must verify correct state transitions, threshold sensitivity, and recovery behavior.

Architecture:

┌──────────┐     ┌──────────────────────────────┐     ┌──────────────┐
│  Client  │────▶│  Circuit Breaker              │────▶│  Downstream  │
│  Request │     │                               │     │  Service     │
└──────────┘     │  States:                      │     └──────────────┘
                 │  ┌────────┐    ┌────────┐     │
                 │  │ CLOSED │───▶│  OPEN  │     │
                 │  │(normal)│    │(reject)│     │
                 │  └────┬───┘    └───┬────┘     │
                 │       ▲            │          │
                 │       │       ┌────▼─────┐    │
                 │       └───────│HALF-OPEN │    │
                 │   (success)   │(probe)   │    │
                 │               └──────────┘    │
                 └──────────────────────────────┘

Thresholds:
• CLOSED → OPEN:  5 failures in 10 seconds
• OPEN duration:  30 seconds
• HALF-OPEN:      Allow 3 probe requests
• HALF-OPEN → CLOSED: 3/3 probes succeed
• HALF-OPEN → OPEN:   1/3 probes fail

Test Strategy by Layer:

Layer What to Test Tools
Unit State transition logic, threshold counters, timer behavior JUnit with mock clock
Integration Circuit breaker with real HTTP calls to failing service Testcontainers + WireMock
Contract Fallback response format matches expected contract Pact
E2E User experience when circuit is open (degraded but functional) Playwright
Chaos Dependency failure patterns (gradual, sudden, flapping) Toxiproxy
Load Circuit breaker under high throughput (thread safety) Gatling, k6

Specific Test Cases:

  1. Closed → Open — Inject 5 consecutive failures; verify circuit opens, requests short-circuited
  2. Open behavior — While open, verify requests fail fast (no timeout wait)
  3. Open → Half-Open — Wait timeout period; verify probe request sent to downstream
  4. Half-Open → Closed — Probe succeeds; verify circuit closes, normal traffic resumes
  5. Half-Open → Open — Probe fails; verify circuit re-opens, timer resets
  6. Fallback response — While open, verify client receives degraded but useful response
  7. Metrics emission — Verify state transitions emit events for alerting
  8. Thread safety — 1000 concurrent requests during state transition; verify no race condition

Failure Injection Scenarios:

Scenario: Downstream service gradual degradation
Given: Circuit breaker configured with 50% failure threshold over 10s window
And: Downstream service normally responds in 50ms
When: Downstream service begins responding with 500 errors at 60% rate
Then: Failure counter crosses threshold within 5 seconds
And: Circuit opens (state: OPEN)
And: All requests receive fallback response (cached data / degraded)
And: After 30 seconds, circuit transitions to HALF-OPEN
And: 3 probe requests are sent to downstream
And: If probes succeed, circuit closes and normal traffic resumes
And: If probes fail, circuit re-opens for another 30 seconds

Observability Testing:

  • Verify circuit state change events include: breaker name, old state, new state, trigger
  • Confirm failure rate metrics per downstream dependency
  • Test that open-circuit alerts fire with dependency context
  • Validate fallback invocation rate metrics during open state

Distributed Systems Concepts:

  • Cascading failure prevention: Open circuit stops failure propagation
  • Fast failure: Better to fail fast than wait for timeout
  • Bulkhead pattern: Circuit breakers complement bulkheads for isolation
  • Self-healing: Half-open state enables automatic recovery detection

Common Mistakes

  • Not testing the half-open → open transition (only testing happy recovery)
  • Setting thresholds too sensitive (flapping) or too lenient (slow detection)
  • Not testing fallback response quality (users still need useful information)
  • Not testing circuit breaker under concurrent load (race conditions in state transitions)

Follow-up Questions

  • How would you tune circuit breaker thresholds for different dependency types?
  • How would you test a circuit breaker that's shared across multiple instances?
  • How would you test the interaction between circuit breakers and retry logic?

Q23How would you test graceful degradation? #

Objective

Demonstrate ability to verify that systems continue providing value (at reduced functionality) rather than failing completely when components are unavailable.

Interview Answer

Graceful degradation means the system provides reduced but functional service when dependencies fail. Testing must verify each degradation level provides the right trade-off between availability and functionality.

Architecture:

┌──────────────────────────────────────────────────────────────┐
│                     Degradation Levels                         │
│                                                               │
│  Level 0: Full Functionality                                  │
│  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐    │
│  │ Search │ │ Reco   │ │ Reviews│ │ Cart   │ │ Payment│    │
│  │  ✓     │ │  ✓     │ │  ✓     │ │  ✓     │ │  ✓     │    │
│  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘    │
│                                                               │
│  Level 1: Non-critical services degraded                      │
│  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐    │
│  │ Search │ │ Reco   │ │ Reviews│ │ Cart   │ │ Payment│    │
│  │  ✓     │ │  ✗     │ │  ✗     │ │  ✓     │ │  ✓     │    │
│  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘    │
│                                                               │
│  Level 2: Minimal viable service                              │
│  ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐    │
│  │ Search │ │ Reco   │ │ Reviews│ │ Cart   │ │ Payment│    │
│  │  ✗     │ │  ✗     │ │  ✗     │ │  ✓     │ │  ✓     │    │
│  └────────┘ └────────┘ └────────┘ └────────┘ └────────┘    │
│                                                               │
│  Level 3: Static fallback (maintenance page)                  │
│  ┌─────────────────────────────────────────────────────┐     │
│  │         Static page served from CDN                  │     │
│  └─────────────────────────────────────────────────────┘     │
└──────────────────────────────────────────────────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Feature availability decision logic, priority classification JUnit, pytest
Integration Each service failure → correct degradation level Testcontainers + WireMock
Contract Degraded response format still meets minimum client expectations Pact
E2E User journey through degraded states Playwright
Chaos Progressively disable services; verify smooth degradation Gremlin, custom kill scripts
UX User can still complete critical paths at each degradation level Manual + automated

Specific Test Cases:

  1. Level 1 degradation — Recommendation service down; page loads without recs section
  2. Level 2 degradation — Search down; user can still browse categories and checkout
  3. Core path protection — Payment service is last to degrade; always available if possible
  4. Stale data serving — Cache serves stale product data when DB is unreachable
  5. Feature flag integration — Kill switch disables feature; UI hides it cleanly
  6. Error message quality — Degraded state shows helpful message, not raw error
  7. Recovery transition — Service recovers; verify smooth transition from degraded to full
  8. Load shedding — Under extreme load, non-essential features disabled proactively

Failure Injection Scenarios:

Scenario: Progressive service failure during peak traffic
Given: E-commerce platform at 80% capacity during sale event
When: Recommendation service becomes unavailable
Then: Product pages load without recommendations section (Level 1)
And: Page load time improves (less dependency)
And: User can still search, browse, and purchase

When: Search service also becomes unavailable
Then: Search bar shows "temporarily unavailable" message (Level 2)
And: Category navigation and direct URLs still work
And: Cart and checkout remain fully functional

When: Product catalog service becomes unavailable
Then: Cached product pages served (stale but available)
And: Cart shows items already added
And: New items cannot be added (graceful error message)
And: Checkout for existing cart items still works

Observability Testing:

  • Verify degradation level metric reflects current system state
  • Confirm per-feature availability metrics for SLA reporting
  • Test that degradation events include affected features and user impact estimate
  • Validate that recovery events fire when full functionality is restored

Distributed Systems Concepts:

  • Availability over consistency: Serve stale data rather than nothing
  • Priority classification: Critical path (checkout) protected over nice-to-have (recs)
  • Bulkhead isolation: Failing component doesn't consume resources needed by healthy ones
  • Static stability: System can operate in degraded mode indefinitely if needed

Common Mistakes

  • Not defining degradation levels before testing (ad-hoc degradation is unpredictable)
  • Testing only complete failure, not partial/intermittent degradation
  • Not testing the transition between degradation levels (smooth vs. jarring)
  • Ignoring the user experience during degradation (error messages, missing UI sections)

Follow-up Questions

  • How would you prioritize which features to degrade first?
  • How would you test that graceful degradation works under sustained load (not just momentary)?
  • How would you test mobile app behavior when backend is in degraded mode?

Q24How would you test observability and alerting? #

Objective

Demonstrate ability to verify that monitoring systems correctly detect anomalies, alerts fire with correct severity, and dashboards provide actionable information.

Interview Answer

Testing observability means verifying that when something goes wrong, the right people are notified with the right context at the right time. It's testing the system that tests your system.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Application │────▶│  Telemetry   │────▶│  Metrics Store   │
│  Services    │     │  Collector   │     │  (Prometheus/    │
│  (Metrics,   │     │  (OTel       │     │   CloudWatch/    │
│   Logs,      │     │   Collector) │     │   Datadog)       │
│   Traces)    │     └──────────────┘     └────────┬─────────┘
└──────────────┘                                   │
                                          ┌────────▼─────────┐
                                          │  Alert Manager   │
                                          │  (Rules Engine)  │
                                          └────────┬─────────┘
                                                   │
                                    ┌──────────────┼──────────────┐
                                    │              │              │
                              ┌─────▼─────┐ ┌────▼─────┐ ┌─────▼─────┐
                              │  PagerDuty│ │  Slack   │ │  Email    │
                              │  (P1/P2)  │ │  (P3/P4) │ │  (Weekly  │
                              │           │ │          │ │   Report) │
                              └───────────┘ └──────────┘ └───────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Metric calculation logic, alert threshold evaluation JUnit, pytest
Integration Metric emission → collection → storage → query Testcontainers (Prometheus)
Contract Alert payload format for each notification channel Schema validation
E2E Inject failure → alert fires → correct team notified Synthetic failure injection
Chaos Monitoring system failure; verify redundant alerting Chaos engineering
Runbook Alert → responder → action; verify runbook completeness Game day exercises

Specific Test Cases:

  1. Metric accuracy — Generate known load; verify metrics match expected values (±5%)
  2. Alert threshold — Error rate crosses 5%; verify alert fires within 60 seconds
  3. Alert routing — P1 alert → PagerDuty; P3 alert → Slack; verify correct routing
  4. Alert content — Verify alert includes: what, where, when, severity, runbook link
  5. Alert deduplication — Same condition persists; verify single alert (not flood)
  6. Alert recovery — Condition resolves; verify "resolved" notification sent
  7. Dashboard accuracy — Compare dashboard values with raw data queries
  8. Trace completeness — Request spans all services; verify trace includes every hop

Failure Injection Scenarios:

Scenario: Verify alerting pipeline detects elevated error rates
Given: Application normally has <0.1% error rate
And: Alert configured for "error_rate > 1% for 5 minutes"
When: Inject failures causing 5% error rate
Then: Alert fires within 5-6 minutes (threshold + evaluation interval)
And: Alert routes to correct PagerDuty escalation policy
And: Alert payload includes:
  - Service name and environment
  - Current error rate (5%) and threshold (1%)
  - Link to relevant dashboard
  - Link to runbook
And: When errors stop, "resolved" alert fires within 5 minutes

Observability Testing:

  • Meta-monitoring: Verify the monitoring system itself is monitored
  • Test metric cardinality doesn't explode (high cardinality = performance issues)
  • Confirm log sampling rates are configured correctly per severity
  • Validate that SLO burn rate alerts fire before SLA breach

Distributed Systems Concepts:

  • Observability triad: Metrics (what), Logs (why), Traces (where) — test all three
  • SLI/SLO/SLA: Service Level Indicators feed Objectives, which define Agreements
  • Distributed tracing: Request correlation across service boundaries
  • Sampling: Trade-off between completeness and cost; verify sampling is representative

Common Mistakes

  • Testing only that alerts can fire, not that they fire at the right threshold
  • Not testing alert routing and escalation paths
  • Ignoring alert fatigue (too many alerts = ignored alerts)
  • Not testing the monitoring system's own availability

Follow-up Questions

  • How would you test that your monitoring survives the same failure it's monitoring?
  • How would you verify SLO burn rate calculations are accurate?
  • How would you test alerting for intermittent issues (flapping detection)?

Q25How would you test security logging? #

Objective

Demonstrate ability to verify that security-relevant events are captured, tamper-proof, and actionable for incident response and compliance.

Interview Answer

Security logging testing verifies that authentication events, authorization decisions, data access, and anomalous behavior are recorded accurately and completely for SIEM consumption and forensic analysis.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Application │────▶│  Security    │────▶│  Log Aggregator  │
│  Services    │     │  Event       │     │  (CloudWatch/    │
│  (Auth,      │     │  Formatter   │     │   Splunk/ELK)    │
│   Access,    │     │  (CEF/JSON)  │     └────────┬─────────┘
│   Admin)     │     └──────────────┘              │
└──────────────┘                          ┌────────▼─────────┐
                                          │  SIEM            │
                                          │  (Correlation    │
                                          │   Rules +        │
                                          │   Anomaly Det.)  │
                                          └────────┬─────────┘
                                                   │
                                          ┌────────▼─────────┐
                                          │  Alert +         │
                                          │  Incident        │
                                          │  Response        │
                                          └──────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Event formatting, field completeness, PII masking JUnit, pytest
Integration Log emission → aggregation → SIEM ingestion Testcontainers (ELK)
Contract Log format conformance (CEF, JSON structure) Schema validation
E2E Perform security action → verify log entry → verify alert Custom framework
Penetration Attempt attack → verify detection and logging OWASP ZAP, Burp Suite
Compliance Verify all required events per SOC 2 / PCI-DSS Audit checklist

Specific Test Cases:

  1. Auth events — Successful login, failed login, MFA challenge; verify all logged
  2. Privilege escalation — User gains admin; verify event with before/after roles
  3. Data access — Read sensitive record; verify access log with who, what, when
  4. Brute force detection — 10 failed logins in 1 minute; verify SIEM alert fires
  5. Tamper resistance — Attempt to delete security log entries; verify rejection
  6. PII masking — Verify SSN, credit card numbers are masked in security logs
  7. Completeness — Generate all security event types; verify none missing in SIEM
  8. Correlation — Related events (login → access → logout) share session/correlation ID

Failure Injection Scenarios:

Scenario: Attempted unauthorized data access triggers security alert
Given: User with "viewer" role is authenticated
And: Security logging is configured for all authorization failures
When: User attempts to access admin API endpoint
Then: Authorization check fails (403 returned to user)
And: Security log records:
  - Timestamp (UTC, millisecond precision)
  - Actor (user ID, session ID, IP address)
  - Action attempted (GET /admin/users)
  - Resource (admin endpoint)
  - Decision (DENY)
  - Reason (insufficient_role: viewer, required: admin)
And: If 5 denied requests in 1 minute from same user → anomaly alert fires
And: Security team receives alert with full context

Observability Testing:

  • Verify security event ingestion lag (time from event to SIEM-searchable)
  • Confirm log volume metrics per event type (detect if events stop flowing)
  • Test that SIEM correlation rules fire on known attack patterns
  • Validate security log retention meets compliance requirements (1 year minimum)

Distributed Systems Concepts:

  • Immutability: Security logs must be append-only and tamper-evident
  • Completeness: No security event should be lost (at-least-once delivery to SIEM)
  • Ordering: Events must be queryable in causal order for incident reconstruction
  • Non-repudiation: Events must be attributable to a specific actor

Common Mistakes

  • Only testing that logs are created, not that they're correctly ingested by SIEM
  • Logging sensitive data (PII, tokens) in security events
  • Not testing security logging under high-throughput conditions (events dropped?)
  • Not verifying that security log tampering is detected and alerted

Follow-up Questions

  • How would you test security logging without generating false alerts in production?
  • How would you verify completeness of security logging across all microservices?
  • How would you test that security logs survive a full infrastructure compromise?

Q26How would you test a high-volume import? #

Objective

Demonstrate ability to test batch processing systems that handle large data imports with validation, error handling, resumability, and performance requirements.

Interview Answer

High-volume imports must handle millions of records efficiently while validating data, handling errors gracefully, providing progress feedback, and being resumable after failures.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Upload      │────▶│  Validation  │────▶│  Batch Processor │
│  (File/API   │     │  Pipeline    │     │  (Chunked        │
│   Stream)    │     │  (Schema +   │     │   Parallel)      │
└──────────────┘     │   Business)  │     └────────┬─────────┘
                     └──────────────┘              │
                                          ┌────────┼─────────┐
                                          │        │         │
                                   ┌──────▼──┐ ┌──▼──────┐ ┌▼───────────┐
                                   │  Target │ │ Error   │ │ Progress   │
                                   │  Store  │ │ Report  │ │ Tracker    │
                                   │  (DB)   │ │ (S3)   │ │ (Redis)    │
                                   └─────────┘ └─────────┘ └────────────┘

Processing Strategy:
┌─────────────────────────────────────────────────────┐
│  File (10M rows)                                     │
│  ├── Chunk 1 (10K rows) → Worker A → ✓ Complete    │
│  ├── Chunk 2 (10K rows) → Worker B → ✓ Complete    │
│  ├── Chunk 3 (10K rows) → Worker C → ✗ Failed     │
│  ├── Chunk 4 (10K rows) → Worker A → ✓ Complete    │
│  └── ... (1000 chunks total)                        │
│                                                      │
│  Checkpoint: Chunk 3 needs retry, chunks 1-2,4 done │
└─────────────────────────────────────────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Row validation, transformation, error classification JUnit, pytest
Integration Full import pipeline with real database Testcontainers
Contract Import file format specification Schema validation
E2E Upload 1M records → verify all imported correctly Custom framework
Chaos Worker crash mid-import, DB connection pool exhaustion Chaos Mesh
Load 10M records with 50 parallel workers Custom benchmarks

Specific Test Cases:

  1. Happy path — Import 1M valid records; verify all persisted with correct values
  2. Partial failure — 5% of rows have validation errors; verify 95% imported, errors reported
  3. Resume after crash — Kill process at 50%; restart; verify resumes from checkpoint
  4. Duplicate handling — Import same file twice; verify idempotent (upsert or skip)
  5. Memory efficiency — Import 10GB file; verify memory usage stays bounded (<1GB)
  6. Progress reporting — Verify progress API shows accurate percentage during import
  7. Rollback — Import fails at 80% and user cancels; verify clean rollback
  8. Encoding handling — File with mixed UTF-8/Latin-1 characters; verify correct handling

Failure Injection Scenarios:

Scenario: Database connection pool exhaustion during import
Given: Import of 5M records using 20 parallel workers
And: Database connection pool is set to 50 connections
When: Additional application load consumes 40 pool connections
And: Import workers can only acquire 10 connections
Then: Import throughput decreases (detected via progress metrics)
And: No workers crash or produce errors (graceful throttling)
And: Import completes successfully (longer duration, but correct)
And: Alert fires for "import_throughput_degradation"
And: Workers use connection backoff, not aggressive retrying

Observability Testing:

  • Verify import throughput metrics (records/second) during processing
  • Confirm progress percentage accuracy within ±1%
  • Test that error rate per chunk is tracked and alerts at threshold
  • Validate resource utilization metrics (CPU, memory, DB connections) during import

Distributed Systems Concepts:

  • Checkpointing: Resume from last successful chunk after failure
  • Idempotency: Re-importing same data must not create duplicates
  • Backpressure: Workers must slow down when downstream is overwhelmed
  • Exactly-once processing: Each record imported exactly once despite retries

Common Mistakes

  • Testing only with small files (1000 rows) that fit in memory
  • Not testing the resume-after-failure path
  • Ignoring memory and connection pool behavior at scale
  • Not testing concurrent imports by different users

Follow-up Questions

  • How would you test import performance regression as database grows?
  • How would you test imports with complex referential integrity dependencies?
  • How would you test that imports don't degrade online query performance?

Q27How would you test a rollback? #

Objective

Demonstrate ability to verify that system changes (deployments, migrations, configuration) can be safely reversed when problems are detected.

Interview Answer

Rollback testing verifies that when a deployment or change goes wrong, the system can return to its previous known-good state without data loss, corruption, or extended downtime.

Architecture:

┌────────────────────────────────────────────────────────────┐
│                    Deployment Pipeline                       │
│                                                             │
│  ┌─────────┐   ┌─────────┐   ┌─────────┐   ┌──────────┐  │
│  │ Build   │──▶│ Deploy  │──▶│ Verify  │──▶│ Promote/ │  │
│  │ v2.1    │   │ Canary  │   │ Health  │   │ Rollback │  │
│  └─────────┘   └─────────┘   └─────────┘   └──────────┘  │
│                                                    │        │
│                                             ┌──────▼──────┐ │
│                                             │  Rollback   │ │
│                                             │  Controller │ │
│                                             ├─────────────┤ │
│                                             │ • Code: v2.0│ │
│                                             │ • DB: undo  │ │
│                                             │   migration │ │
│                                             │ • Config:   │ │
│                                             │   previous  │ │
│                                             └─────────────┘ │
└────────────────────────────────────────────────────────────┘

Rollback Scenarios:
┌───────────────┐  ┌───────────────┐  ┌───────────────┐
│  Code Only    │  │  Code + DB    │  │  Code + DB +  │
│  (Easy: swap  │  │  (Complex:    │  │  Config       │
│   container)  │  │   backward    │  │  (Hardest:    │
│               │  │   migration)  │  │   coordinated)│
└───────────────┘  └───────────────┘  └───────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Rollback decision logic, version comparison JUnit, pytest
Integration Database migration up + down cycle Flyway/Liquibase test mode
Contract API backward compatibility (v2 → v1 clients still work) Pact
E2E Deploy v2 → detect problem → rollback → verify v1 works Deployment pipeline tests
Chaos Rollback during partial deployment (mixed fleet) Kubernetes, custom
Data Data created during v2 is accessible after rollback to v1 Custom data verification

Specific Test Cases:

  1. Code rollback — Deploy v2, rollback to v1; verify all functionality restored
  2. DB backward migration — Run down migration; verify schema matches v1 expectations
  3. Data compatibility — Records created during v2; verify readable by v1 code
  4. Config rollback — Feature flag changed; rollback; verify old behavior restored
  5. Partial rollback — 3 of 10 pods on v2; rollback; verify all return to v1
  6. Rollback speed — Measure time from decision to full rollback completion (<5 min)
  7. Rollback during traffic — Active users during rollback; verify no request failures
  8. Double rollback — Rollback of a rollback (re-deploy v2); verify clean state

Failure Injection Scenarios:

Scenario: Rollback required due to data corruption bug
Given: Version 2.1 deployed to production
And: Bug in v2.1 corrupts 1% of records written after deploy
And: Issue detected 30 minutes after deployment
When: Rollback to v2.0 is initiated
Then: All pods return to v2.0 within 5 minutes
And: No new corrupted records are created after rollback
And: Corrupted records from 30-minute window are identified
And: Data repair job fixes corrupted records using audit trail
And: Forward-fix in v2.2 addresses the bug before next deploy
And: Post-incident report documents detection gap (30 min)

Observability Testing:

  • Verify deployment version metrics clearly show current running version
  • Confirm rollback duration metrics (time from trigger to completion)
  • Test that rollback events fire alerts with context (why, who, from-version, to-version)
  • Validate that error rate comparison (before vs after rollback) is available

Distributed Systems Concepts:

  • Backward compatibility: New code must work with old data and vice versa
  • Blue-green deployments: Keep previous version running for instant rollback
  • Expand-contract pattern: Database changes that work with both old and new code
  • Idempotent migrations: Running migration multiple times is safe

Common Mistakes

  • Never testing rollback (only testing forward deployment)
  • Not testing data created during v2 is compatible with v1 code
  • Ignoring database schema rollback (only rolling back application code)
  • Not testing rollback speed under production-like conditions

Follow-up Questions

  • How would you test rollback for a database change that's not reversible (data transformation)?
  • How would you test rollback in a microservices architecture with version dependencies?
  • What's your strategy when rollback itself fails?

Q28How would you test schema evolution? #

Objective

Demonstrate ability to test database and API schema changes that maintain backward compatibility, data integrity, and zero-downtime deployments.

Interview Answer

Schema evolution testing verifies that structural changes to databases, APIs, or message formats don't break existing consumers, lose data, or require downtime.

Architecture:

┌────────────────────────────────────────────────────────────────┐
│                    Schema Evolution Patterns                     │
│                                                                 │
│  Database (Expand-Contract):                                    │
│  ┌──────────┐     ┌──────────────┐     ┌──────────────┐       │
│  │ Phase 1: │────▶│ Phase 2:     │────▶│ Phase 3:     │       │
│  │ ADD new  │     │ Migrate data │     │ DROP old     │       │
│  │ column   │     │ (backfill)   │     │ column       │       │
│  └──────────┘     └──────────────┘     └──────────────┘       │
│                                                                 │
│  API Versioning:                                                │
│  ┌──────────┐     ┌──────────────┐     ┌──────────────┐       │
│  │ v1: name │     │ v2: first,   │     │ v1 deprecated│       │
│  │          │     │     last     │     │ v2 primary   │       │
│  └──────────┘     └──────────────┘     └──────────────┘       │
│                                                                 │
│  Event Schema (Forward Compatibility):                          │
│  ┌──────────┐     ┌──────────────┐                             │
│  │ v1 event │     │ v2 event     │  v1 consumers ignore       │
│  │ {a, b}   │     │ {a, b, c}    │  unknown fields            │
│  └──────────┘     └──────────────┘                             │
└────────────────────────────────────────────────────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Data transformation logic, default value handling JUnit, pytest
Integration Migration execution on production-like data volumes Flyway, Liquibase, pgTAP
Contract Old clients work with new schema (backward compat) Pact, Avro schema registry
E2E Full deployment with migration under traffic Staging environment
Load Migration performance on billion-row tables Custom benchmarks
Compatibility N-1 version reads N version data (forward compat) Version matrix testing

Specific Test Cases:

  1. Additive change — Add nullable column; verify old code ignores it, new code uses it
  2. Column rename — Rename via expand-contract; verify both old and new names work during transition
  3. Type change — Change string → enum; verify data migration preserves all values
  4. Backfill correctness — Backfill 10M rows; verify all transformed correctly
  5. Concurrent access — Run migration while application processes requests; verify no errors
  6. Rollback migration — Run down migration; verify schema returns to previous state
  7. Schema registry — Publish breaking change; verify registry rejects incompatible schema
  8. Consumer compatibility — New event schema; verify all consumers handle gracefully

Failure Injection Scenarios:

Scenario: Long-running migration on large table
Given: Table has 500M rows and needs a new indexed column
And: Application is serving production traffic
When: ALTER TABLE ADD COLUMN executes (non-blocking in PG)
And: Background job backfills values for new column (2 hours)
Then: No read/write locks acquired on the table during migration
And: Application continues serving requests with no latency increase
And: New column has NULL values until backfilled (handled by code)
And: After backfill, both old code (ignores column) and new code (uses column) work
And: NOT NULL constraint added only after 100% backfill verified

Observability Testing:

  • Verify migration duration metrics per migration step
  • Confirm table lock wait metrics during schema changes
  • Test that schema version tracking clearly shows current state
  • Validate that incompatible schema changes are blocked by CI/CD checks

Distributed Systems Concepts:

  • Backward compatibility: New schema must not break old consumers
  • Forward compatibility: Old schema consumers must handle new schema gracefully
  • Expand-contract: Safe pattern for non-breaking schema changes
  • Eventual migration: Large backfills are eventually consistent; new code handles both states

Common Mistakes

  • Testing migrations on empty databases (missing production data volume effects)
  • Not testing the transition period when both old and new code run simultaneously
  • Assuming all column additions are non-breaking (NOT NULL without default breaks)
  • Not testing migration rollback (down migration)

Follow-up Questions

  • How would you test a schema migration on a 1TB table with zero downtime?
  • How would you handle schema evolution for event-driven systems with Avro/Protobuf?
  • How would you test that old API versions are correctly sunset?

Q29How would you test GDPR-style deletion? #

Objective

Demonstrate ability to verify that personal data deletion is complete, irreversible, and compliant across all systems that hold the data.

Interview Answer

GDPR "Right to Erasure" requires that all personal data for a subject is deleted or anonymized across ALL systems within 30 days. Testing must verify completeness, irreversibility, and that no data lingers in backups, caches, or logs.

Architecture:

┌──────────────┐     ┌──────────────┐     ┌─────────────────┐
│  Deletion    │────▶│  Orchestrator│────▶│  System A (DB)   │
│  Request     │     │  (Saga       │     │  → DELETE user   │
│  (Subject    │     │   Pattern)   │     └─────────────────┘
│   Access     │     │              │     ┌─────────────────┐
│   Request)   │     │              │────▶│  System B (S3)   │
└──────────────┘     │              │     │  → DELETE files  │
                     │              │     └─────────────────┘
                     │              │     ┌─────────────────┐
                     │              │────▶│  System C (Elastic)│
                     │              │     │  → DELETE docs   │
                     │              │     └─────────────────┘
                     │              │     ┌─────────────────┐
                     │              │────▶│  System D (Logs) │
                     └──────────────┘     │  → ANONYMIZE     │
                            │             └─────────────────┘
                     ┌──────▼───────┐
                     │  Deletion    │
                     │  Verification│
                     │  Certificate │
                     └──────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Anonymization logic, field-level deletion rules JUnit, pytest
Integration Deletion across each data store Testcontainers, LocalStack
Contract Deletion API request/response format OpenAPI validation
E2E Full deletion request → verification across all systems Custom framework
Compliance Verify data cannot be recovered after deletion Audit scripts
Timing Deletion completes within 30-day GDPR window SLA monitoring

Specific Test Cases:

  1. Complete deletion — Delete user; search all systems; verify zero PII found
  2. Backup handling — Data exists in backup; verify excluded on next restore
  3. Cache purge — Data was cached; verify removed from all cache layers
  4. Log anonymization — User's actions in logs; verify PII anonymized (not deleted)
  5. Third-party propagation — Data shared with Stripe, analytics; verify deletion propagated
  6. Derived data — ML model trained on user data; verify model retrained or data removed
  7. Partial deletion — Retain legally required data (invoices); delete everything else
  8. Verification certificate — After deletion, generate proof of completion for audit

Failure Injection Scenarios:

Scenario: Deletion fails for one of five systems
Given: User requests deletion of all personal data
And: Data exists in: PostgreSQL, Elasticsearch, S3, Redis, Analytics
When: Deletion orchestrator begins saga across all systems
And: Elasticsearch delete fails (cluster unhealthy)
Then: Successful deletions (PG, S3, Redis, Analytics) are NOT rolled back
And: Elasticsearch deletion is queued for retry
And: Deletion status shows "partial - retrying" with failed system listed
And: Alert fires for "deletion_incomplete" with 24h SLA for resolution
And: After ES recovery, deletion completes and certificate is generated
And: Total time does not exceed 30-day GDPR deadline

Observability Testing:

  • Verify deletion request status tracking (pending, in-progress, partial, complete)
  • Confirm per-system deletion latency metrics
  • Test that overdue deletion alerts fire before GDPR deadline
  • Validate deletion certificate generation includes all systems verified

Distributed Systems Concepts:

  • Saga pattern: Coordinate deletion across multiple services without distributed transactions
  • Eventual deletion: Data may persist temporarily in replicas; verify final state
  • Tombstones: Soft-delete markers that prevent data from reappearing
  • Right to be forgotten vs data retention: Conflict resolution between deletion and legal hold

Common Mistakes

  • Only testing deletion in primary database, ignoring replicas, caches, logs, and backups
  • Not testing that deleted data doesn't reappear after backup restoration
  • Ignoring third-party systems that hold copies of the data
  • Not generating auditable proof that deletion was complete

Follow-up Questions

  • How would you test deletion when data is embedded in aggregate/analytics tables?
  • How would you verify deletion across 50+ microservices?
  • How would you test the conflict between GDPR deletion and legal hold requirements?

Q30How would you test a production canary? #

Objective

Demonstrate ability to verify that canary deployment mechanisms correctly detect problems, route traffic appropriately, and auto-rollback when quality degrades.

Interview Answer

Canary testing verifies that the progressive deployment mechanism itself works correctly — that it detects bad deployments, limits blast radius, and rolls back automatically before users are significantly impacted.

Architecture:

┌─────────────────────────────────────────────────────────────┐
│                    Canary Deployment Pipeline                 │
│                                                              │
│  ┌──────────┐    ┌───────────────────────────────────┐      │
│  │  Load    │    │  Production Fleet                  │      │
│  │  Balancer│    │                                    │      │
│  │          │──▶ │  ┌─────────────────────────────┐  │      │
│  │  Traffic │    │  │  Stable (v2.0) — 95% traffic│  │      │
│  │  Split   │    │  │  [Pod][Pod][Pod][Pod][Pod]  │  │      │
│  │          │    │  └─────────────────────────────┘  │      │
│  │          │──▶ │  ┌─────────────────────────────┐  │      │
│  │          │    │  │  Canary (v2.1) — 5% traffic │  │      │
│  │          │    │  │  [Pod]                       │  │      │
│  └──────────┘    │  └─────────────────────────────┘  │      │
│                  └───────────────────────────────────┘      │
│                                                              │
│  ┌──────────────────────────────────────────────────┐       │
│  │  Canary Analysis                                  │       │
│  │  Compare: error_rate(canary) vs error_rate(stable)│       │
│  │  Compare: latency(canary) vs latency(stable)      │       │
│  │  Compare: saturation(canary) vs saturation(stable)│       │
│  │  Decision: PROMOTE | ROLLBACK | CONTINUE          │       │
│  └──────────────────────────────────────────────────┘       │
└─────────────────────────────────────────────────────────────┘

Test Strategy by Layer:

Layer What to Test Tools
Unit Canary analysis statistical comparison logic JUnit, pytest
Integration Traffic splitting accuracy, metric collection per variant Kubernetes + Istio
Contract Canary analysis report format Schema validation
E2E Deploy bad canary → detect → auto-rollback → verify Flagger, Argo Rollouts
Statistical False positive/negative rates of canary analysis Historical data replay
Load Canary behavior under high traffic (metric accuracy) k6, Locust

Specific Test Cases:

  1. Traffic splitting accuracy — Set 5% canary; verify actual traffic is 4.5-5.5%
  2. Bad canary detection — Deploy version with 10x error rate; verify auto-rollback
  3. Slow canary detection — Deploy version with 2x latency; verify detection within SLA
  4. Good canary promotion — Deploy healthy version; verify auto-promotion to 100%
  5. Metric isolation — Canary metrics don't pollute stable metrics (separate labels)
  6. Sticky sessions — User hits canary; subsequent requests stay on canary (consistency)
  7. Rollback speed — From detection to full rollback; verify <2 minutes
  8. Manual override — Operator forces rollback; verify immediate effect

Failure Injection Scenarios:

Scenario: Canary deploys version with memory leak
Given: Canary is deployed with 5% traffic
And: New version has a slow memory leak (grows 10MB/hour)
And: Analysis window is 30 minutes
When: After 15 minutes, canary pod's memory usage grows abnormally
Then: Saturation metric (memory utilization) diverges from stable
And: Canary analysis detects divergence in resource utilization
And: If configured for auto-rollback on resource anomaly: rollback fires
And: If not configured: alert fires for manual investigation
And: Pod doesn't OOM during analysis window (memory limit protects)
And: After rollback, no user impact from the memory-leaking version

Observability Testing:

  • Verify per-variant metrics are correctly labeled (canary vs stable)
  • Confirm canary analysis decision metrics (promote/rollback/continue counts)
  • Test that canary duration metrics track time from deploy to decision
  • Validate blast radius metrics (what % of users were affected before rollback)

Distributed Systems Concepts:

  • Statistical significance: Canary analysis needs enough traffic for valid comparison
  • Blast radius control: Limit exposure to protect most users from bad deploys
  • Observability: Canary relies on accurate, real-time metrics per variant
  • Automated decision-making: Machine-driven rollback faster than human response

Common Mistakes

  • Not testing the canary analysis logic itself (trusting it blindly)
  • Setting canary traffic too low for statistical significance
  • Not testing slow-burn issues that only manifest after analysis window
  • Not verifying that rollback actually removes ALL canary pods

Follow-up Questions

  • How would you determine the right traffic percentage and analysis duration for a canary?
  • How would you test canary deployments for async services (no request traffic)?
  • How would you test canary analysis when baseline metrics are noisy?

Summary: Key Principles for System Design QA #

Test Strategy Framework

┌────────────────────────────────────────────────────────┐
│  For every system design question, structure as:        │
│                                                         │
│  1. ARCHITECTURE                                        │
│     Draw components, data flows, boundaries             │
│                                                         │
│  2. FAILURE MODES                                       │
│     What can go wrong? Network, disk, clock, logic      │
│                                                         │
│  3. TEST LAYERS                                         │
│     Unit → Integration → Contract → E2E → Chaos        │
│                                                         │
│  4. OBSERVABILITY                                       │
│     How do you KNOW it's working? Metrics, logs, traces │
│                                                         │
│  5. DISTRIBUTED CONCEPTS                                │
│     CAP, consistency, idempotency, ordering             │
│                                                         │
│  6. TOOLS                                               │
│     Name specific tools for each layer                  │
└────────────────────────────────────────────────────────┘

Essential Tools Reference

Category Tools
Chaos Engineering Chaos Monkey, Gremlin, LitmusChaos, Chaos Mesh, AWS FIS
Load Testing k6, Gatling, Locust, JMeter, Artillery
Contract Testing Pact, Spring Cloud Contract, Prism
Service Virtualization WireMock, Mountebank, Hoverfly, Toxiproxy
Observability Prometheus, Grafana, Datadog, OpenTelemetry, Jaeger
Data Quality Great Expectations, dbt tests, Monte Carlo
Infrastructure Testing Testcontainers, LocalStack, MinIO
Formal Verification TLA+, Alloy, Jepsen

Distributed Systems Concepts Checklist

  • CAP Theorem — Does the system favor CP or AP? Test accordingly
  • Eventual Consistency — What's the acceptable staleness window?
  • Idempotency — Are all mutations safely retryable?
  • Ordering — Is event order guaranteed? What happens out-of-order?
  • Partition Tolerance — What happens during network splits?
  • Exactly-Once — How is deduplication achieved?
  • Saga/Compensation — How are distributed transactions handled?
  • Circuit Breakers — How do dependencies fail gracefully?
  • Backpressure — What happens when consumers are slower than producers?
  • Clock Dependency — What breaks if clocks drift?

Finished this chapter?

Mark it as done to track your progress on the guide overview. Progress is kept only while this browser tab is open.

← Back to chapters