API and Integration Testing forms the backbone of modern quality assurance. As systems evolve into distributed microservices architectures, the ability to validate contracts, resilience patterns, and cross-service interactions becomes a critical senior QA competency. This chapter covers 30 essential interview questions spanning idempotency, authentication, asynchronous patterns, error handling, security, and observability.
Demonstrate understanding of idempotency as a distributed systems concept and explain how it impacts API design and testing strategy.
Interview Answer
An API operation is idempotent when making the same request multiple times produces the same result as making it once. The server state does not change after the first successful execution, regardless of how many times the client repeats the call.
HTTP Method Idempotency by Specification:
GET, PUT, DELETE, HEAD, OPTIONS — idempotent by design
POST — NOT idempotent by default (requires explicit implementation)
PATCH — NOT guaranteed idempotent
For POST operations (e.g., creating a payment), idempotency is achieved through an idempotency key — a unique client-generated identifier sent in a header. The server stores this key with the response and returns the cached result on subsequent calls.
Why it matters for QA:
Network failures cause retries — without idempotency, a payment could be charged twice
Load balancers may replay requests during failover
Message queues may deliver the same message multiple times (at-least-once delivery)
// REST Assured — Testing PUT idempotency@TestpublicvoidtestPutIdempotency() {
Stringpayload="{\"name\": \"Updated User\", \"email\": \"user@test.com\"}";
// First PUT requestResponsefirst= given()
.header("Content-Type", "application/json")
.body(payload)
.when()
.put("/api/v1/users/123")
.then()
.statusCode(200)
.extract().response();
// Second identical PUT requestResponsesecond= given()
.header("Content-Type", "application/json")
.body(payload)
.when()
.put("/api/v1/users/123")
.then()
.statusCode(200)
.extract().response();
// Both responses should be identical
assertEquals(first.jsonPath().getString("name"), second.jsonPath().getString("name"));
assertEquals(first.jsonPath().getString("updatedAt"), second.jsonPath().getString("updatedAt"));
}
# curl — Demonstrating idempotent PUT
curl -X PUT https://api.example.com/v1/users/123 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer token123" \
-d '{"name": "Updated User", "email": "user@test.com"}'# Repeating the same call should return the same result
Show practical test design for validating idempotency key implementations in payment or order creation APIs.
Interview Answer
An idempotency key is a unique value (typically UUID) sent by the client in a request header. The server uses this key to detect duplicate requests and return the original response without re-executing the operation.
Test Strategy for Idempotency Keys:
Happy path — Same key, same request returns cached response
Same key, different body — Should return 422 Unprocessable Entity
Key expiration — After TTL, key should no longer be recognized
Concurrent requests — Same key sent simultaneously should process only once
Different keys, same body — Should create two separate resources
Not testing key expiration (keys typically expire after 24-48 hours)
Forgetting to validate that the server actually stores and checks keys (verify DB/cache)
Not testing what happens when the key header is missing entirely
Ignoring race conditions in concurrent duplicate detection
Follow-up Questions
Where should idempotency keys be stored (database vs Redis)?
What is the appropriate TTL for idempotency keys?
How do you handle idempotency in GraphQL mutations?
Q3What is a correlation ID and how do you use it?#
Objective
Explain how correlation IDs enable distributed tracing and how QA leverages them for debugging cross-service issues.
Interview Answer
A correlation ID (also called trace ID or request ID) is a unique identifier attached to a request that propagates across all services involved in processing that request. It creates a thread linking logs, metrics, and traces across the entire request lifecycle.
How it works:
Client or API gateway generates a UUID and attaches it as a header (e.g., X-Correlation-ID)
Each downstream service reads and forwards this header
Every log entry includes the correlation ID
When an issue occurs, you search logs by correlation ID to see the full journey
QA uses correlation IDs to:
Trace a failed request through multiple services
Verify that all services in a chain received and processed the request
Identify which service introduced latency or errors
Validate that logs are properly correlated in observability platforms
Demonstrate ability to validate retry logic and timeout handling in distributed systems, including exponential backoff verification.
Interview Answer
Testing timeout-then-retry scenarios validates that the system gracefully handles slow or unresponsive dependencies. The key is to simulate controlled delays, verify retry behavior, and ensure no duplicate side effects.
Test Strategy:
Use WireMock or a mock server to introduce artificial delays
Verify the client retries with correct backoff intervals
Confirm that the final response is correct after recovery
Validate that retries don't cause duplicate operations
Check circuit breaker activation after max retries
// WireMock + REST Assured — Testing timeout and retry@TestpublicvoidtestTimeout_retriesWithExponentialBackoff() {
// First call — times out (delay > client timeout)
stubFor(get(urlEqualTo("/api/v1/inventory/item/99"))
.inScenario("Retry Test")
.whenScenarioStateIs(Scenario.STARTED)
.willReturn(aResponse()
.withFixedDelay(5000) // 5s delay, client timeout is 3s
.withStatus(200)
.withBody("{\"stock\": 50}"))
.willSetStateTo("FIRST_TIMEOUT"));
// Second call — also times out
stubFor(get(urlEqualTo("/api/v1/inventory/item/99"))
.inScenario("Retry Test")
.whenScenarioStateIs("FIRST_TIMEOUT")
.willReturn(aResponse()
.withFixedDelay(5000)
.withStatus(200))
.willSetStateTo("SECOND_TIMEOUT"));
// Third call — succeeds
stubFor(get(urlEqualTo("/api/v1/inventory/item/99"))
.inScenario("Retry Test")
.whenScenarioStateIs("SECOND_TIMEOUT")
.willReturn(aResponse()
.withFixedDelay(100) // Fast response
.withStatus(200)
.withBody("{\"stock\": 50}")));
// Execute — the client should retry and eventually succeedlongstartTime= System.currentTimeMillis();
Responseresponse= given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/inventory/item/99")
.then()
.statusCode(200)
.extract().response();
longelapsed= System.currentTimeMillis() - startTime;
assertEquals(50, response.jsonPath().getInt("stock"));
// Verify exponential backoff: ~1s + ~2s + response time
assertTrue(elapsed > 3000, "Should show backoff delay");
// Verify exactly 3 attempts were made
verify(3, getRequestedFor(urlEqualTo("/api/v1/inventory/item/99")));
}
@TestpublicvoidtestTimeout_maxRetriesExhausted_returns503() {
// All calls timeout
stubFor(get(urlEqualTo("/api/v1/inventory/item/99"))
.willReturn(aResponse().withFixedDelay(10000).withStatus(200)));
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/inventory/item/99")
.then()
.statusCode(503)
.body("error.code", equalTo("service_unavailable"))
.body("error.message", containsString("retry"));
}
Show how to validate that webhook consumers handle duplicate deliveries gracefully without processing the event twice.
Interview Answer
Webhook providers often send the same event multiple times due to network issues, retries, or infrastructure restarts. Testing duplicate webhook handling ensures the consumer is idempotent and deduplicates based on event ID.
Test Strategy:
Send the same webhook payload twice with the same event ID
Verify the side effect occurs only once
Verify the second delivery returns 200 (acknowledged) without re-processing
Test with slight variations in delivery timing (immediate vs delayed duplicate)
Validate deduplication storage (Redis/DB) is correctly populated
Demonstrate contract testing approaches including JSON Schema validation, consumer-driven contracts, and structural assertions.
Interview Answer
JSON contract validation ensures that API responses conform to a predefined structure, preventing breaking changes from reaching consumers. There are three levels of validation:
Show comprehensive test coverage for paginated API endpoints including edge cases, consistency, and performance.
Interview Answer
Pagination testing goes beyond checking page numbers. It validates data integrity, boundary conditions, and performance characteristics. The three common patterns are offset-based, cursor-based, and keyset pagination.
Demonstrate systematic testing of query parameter-based sorting and filtering, including edge cases and SQL injection prevention.
Interview Answer
Sorting and filtering are critical for APIs returning collections. Testing must cover correctness, combinatorial logic, edge cases, and security (filter injection). A strong approach combines boundary value analysis with equivalence partitioning.
Test Dimensions:
Sort fields: each sortable column ascending and descending
Filter operators: equals, contains, greater than, less than, in, between
Show how to verify rate limiting implementation including headers, quota reset, and behavior under burst traffic.
Interview Answer
Rate limiting protects APIs from abuse and ensures fair resource allocation. Testing validates that limits are enforced correctly, headers communicate quota status, and the response degrades gracefully.
Key Test Areas:
Requests within limit succeed
Requests exceeding limit return 429 Too Many Requests
Rate limit headers are present and accurate
Quota resets after the window expires
Different rate limits for different tiers/endpoints
Show testing of the complete token lifecycle including expiration, refresh flows, and edge cases around token rotation.
Interview Answer
Token lifecycle testing validates the authentication flow from issuance through expiration to refresh. Key scenarios include using expired tokens, refreshing before/after expiry, refresh token rotation, and concurrent refresh attempts.
Token Lifecycle:
Login → Access Token (short-lived, 15min) + Refresh Token (long-lived, 7d)
→ Access Token expires
→ Use Refresh Token to get new Access Token
→ Refresh Token rotated (old one invalidated)
// REST Assured — Token expiry and refresh testing@TestpublicvoidtestAccessToken_expiredToken_returns401() {
// Generate a token that expired 1 minute agoStringexpiredToken= generateJwt(userId, Instant.now().minusSeconds(60));
given()
.header("Authorization", "Bearer " + expiredToken)
.when()
.get("/api/v1/users/me")
.then()
.statusCode(401)
.body("error.code", equalTo("token_expired"))
.body("error.message", containsString("expired"));
}
@TestpublicvoidtestRefreshToken_validRefresh_returnsNewTokens() {
// Login to get initial tokensResponseloginResp= given()
.header("Content-Type", "application/json")
.body("{\"email\": \"user@test.com\", \"password\": \"password123\"}")
.when()
.post("/api/v1/auth/login")
.then()
.statusCode(200)
.extract().response();
StringrefreshToken= loginResp.jsonPath().getString("refreshToken");
// Use refresh token to get new access tokenResponserefreshResp= given()
.header("Content-Type", "application/json")
.body("{\"refreshToken\": \"" + refreshToken + "\"}")
.when()
.post("/api/v1/auth/refresh")
.then()
.statusCode(200)
.body("accessToken", notNullValue())
.body("refreshToken", notNullValue())
.body("expiresIn", greaterThan(0))
.extract().response();
// New access token should workStringnewAccessToken= refreshResp.jsonPath().getString("accessToken");
given()
.header("Authorization", "Bearer " + newAccessToken)
.when()
.get("/api/v1/users/me")
.then()
.statusCode(200);
}
@TestpublicvoidtestRefreshToken_rotationInvalidatesOldToken() {
// Get initial tokensStringrefreshToken= loginAndGetRefreshToken();
// Refresh once — get new refresh tokenResponserefreshResp= given()
.header("Content-Type", "application/json")
.body("{\"refreshToken\": \"" + refreshToken + "\"}")
.when()
.post("/api/v1/auth/refresh")
.then()
.statusCode(200)
.extract().response();
StringnewRefreshToken= refreshResp.jsonPath().getString("refreshToken");
assertNotEquals(refreshToken, newRefreshToken);
// Old refresh token should no longer work
given()
.header("Content-Type", "application/json")
.body("{\"refreshToken\": \"" + refreshToken + "\"}")
.when()
.post("/api/v1/auth/refresh")
.then()
.statusCode(401)
.body("error.code", equalTo("token_revoked"));
}
@TestpublicvoidtestRefreshToken_reuseDetection_revokesFamily() {
// This tests refresh token reuse detection (security feature)StringrefreshToken= loginAndGetRefreshToken();
// First refresh — legitimateResponseresp1= given()
.body("{\"refreshToken\": \"" + refreshToken + "\"}")
.header("Content-Type", "application/json")
.when()
.post("/api/v1/auth/refresh")
.then()
.statusCode(200)
.extract().response();
StringnewRefreshToken= resp1.jsonPath().getString("refreshToken");
// Attempt to reuse OLD refresh token (simulates stolen token)
given()
.body("{\"refreshToken\": \"" + refreshToken + "\"}")
.header("Content-Type", "application/json")
.when()
.post("/api/v1/auth/refresh")
.then()
.statusCode(401);
// Even the new refresh token should be invalidated (family revocation)
given()
.body("{\"refreshToken\": \"" + newRefreshToken + "\"}")
.header("Content-Type", "application/json")
.when()
.post("/api/v1/auth/refresh")
.then()
.statusCode(401);
}
@TestpublicvoidtestRefreshToken_concurrentRefresh_onlyOneSucceeds()throws Exception {
StringrefreshToken= loginAndGetRefreshToken();
ExecutorServiceexecutor= Executors.newFixedThreadPool(3);
List<Future<Integer>> futures=newArrayList<>();
for (inti=0; i < 3; i++) {
futures.add(executor.submit(() -> given()
.body("{\"refreshToken\": \"" + refreshToken + "\"}")
.header("Content-Type", "application/json")
.when()
.post("/api/v1/auth/refresh")
.then()
.extract().statusCode()));
}
List<Integer> statuses= futures.stream()
.map(f -> { try { return f.get(); } catch (Exception e) { return500; } })
.collect(Collectors.toList());
longsuccessCount= statuses.stream().filter(s -> s == 200).count();
assertTrue(successCount <= 1, "At most one concurrent refresh should succeed");
}
Demonstrate testing of asynchronous API patterns where the server accepts a request for processing but doesn't complete it immediately.
Interview Answer
A 202 Accepted response indicates the server has received the request and will process it asynchronously. The client must poll a status endpoint or wait for a callback/webhook. Testing must validate the full lifecycle: submission, polling, completion, and failure scenarios.
Async API Pattern:
Client → POST /jobs → 202 Accepted (Location: /jobs/123/status)
Client → GET /jobs/123/status → 200 {status: "processing"}
Client → GET /jobs/123/status → 200 {status: "processing"}
Client → GET /jobs/123/status → 200 {status: "completed", result: {...}}
Explain testing strategies for systems where data propagation between services is not immediate, requiring time-based assertions.
Interview Answer
Eventual consistency means that after a write, different parts of the system may temporarily return different values until propagation completes. Testing must account for this delay while still catching genuine bugs.
Challenge: Distinguishing between "not yet consistent" (expected) and "will never be consistent" (bug).
Strategy:
Write data to the primary service
Poll the read replica/dependent service with a bounded timeout
Assert consistency is achieved within the SLA
Test that stale reads don't cause incorrect behavior
// REST Assured — Eventual consistency testing@TestpublicvoidtestEventualConsistency_orderCreationPropagates() {
// Create order in order serviceStringorderId= given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body("{\"product\": \"widget\", \"quantity\": 5}")
.when()
.post("/api/v1/orders")
.then()
.statusCode(201)
.extract().jsonPath().getString("id");
// Query the search/analytics service — may take time to propagate
await()
.atMost(Duration.ofSeconds(10))
.pollInterval(Duration.ofMillis(500))
.untilAsserted(() -> {
given()
.header("Authorization", "Bearer token")
.queryParam("orderId", orderId)
.when()
.get("/api/v1/search/orders")
.then()
.statusCode(200)
.body("results.size()", equalTo(1))
.body("results[0].id", equalTo(orderId));
});
}
@TestpublicvoidtestEventualConsistency_updatePropagatesWithinSLA() {
// Update user profile on write service
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body("{\"displayName\": \"New Name\"}")
.when()
.put("/api/v1/users/me/profile")
.then()
.statusCode(200);
// Read from cache/CDN — measure propagation timelongstart= System.currentTimeMillis();
booleanconsistent=false;
while (System.currentTimeMillis() - start < 5000) { // 5s SLAResponsereadResp= given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/public/users/me")
.then()
.extract().response();
if ("New Name".equals(readResp.jsonPath().getString("displayName"))) {
consistent = true;
longpropagationTime= System.currentTimeMillis() - start;
System.out.println("Consistency achieved in " + propagationTime + "ms");
break;
}
Thread.sleep(200);
}
assertTrue(consistent, "Data should be consistent within 5s SLA");
}
@TestpublicvoidtestEventualConsistency_deleteEventuallyPropagates() {
// Create then immediately deleteStringid= createResource();
deleteResource(id);
// The resource may still appear briefly in search
await()
.atMost(Duration.ofSeconds(10))
.pollInterval(Duration.ofSeconds(1))
.untilAsserted(() -> {
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/search/items/" + id)
.then()
.statusCode(404);
});
}
Show how to validate that a new API version works correctly and that the version routing mechanism functions properly.
Interview Answer
API versioning testing ensures that clients using older versions continue to work while new versions introduce intended changes. Testing covers version routing, backward compatibility, deprecation warnings, and migration paths.
Demonstrate strategies for ensuring API changes don't break existing consumers, including additive changes, field removal detection, and contract testing.
Interview Answer
Backward compatibility testing ensures that new API releases don't break existing clients. A change is backward compatible if existing clients can continue operating without modification.
Backward Compatible Changes (Safe):
Adding new optional fields to responses
Adding new endpoints
Adding new optional query parameters
Widening accepted input values
Breaking Changes (Unsafe):
Removing fields from responses
Renaming fields
Changing field types
Making optional parameters required
Changing status codes
// REST Assured — Backward compatibility tests@TestpublicvoidtestBackwardCompatibility_newFieldsDoNotBreakOldConsumers() {
// Simulate old consumer that only reads specific fieldsResponseresponse= given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/users/123")
.then()
.statusCode(200)
.extract().response();
// Old consumer fields still present and correct type
assertNotNull(response.jsonPath().getString("id"));
assertNotNull(response.jsonPath().getString("email"));
assertNotNull(response.jsonPath().getString("name"));
// New fields may exist but shouldn't break deserialization
}
@TestpublicvoidtestBackwardCompatibility_oldRequestFormatStillAccepted() {
// V1 format: separate first/last name
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body("{\"firstName\": \"John\", \"lastName\": \"Doe\", \"email\": \"john@test.com\"}")
.when()
.post("/api/v1/users")
.then()
.statusCode(201); // Old format still works
}
@TestpublicvoidtestBackwardCompatibility_responseFieldsNotRemoved() {
// Record baseline fields from v1 documentation/contractSet<String> requiredV1Fields= Set.of("id", "email", "name", "role", "createdAt");
Responseresponse= given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/users/123")
.then()
.statusCode(200)
.extract().response();
Set<String> actualFields= response.jsonPath().getMap("$").keySet();
assertTrue(actualFields.containsAll(requiredV1Fields),
"All v1 fields must still be present. Missing: " +
requiredV1Fields.stream()
.filter(f -> !actualFields.contains(f))
.collect(Collectors.joining(", ")));
}
@TestpublicvoidtestBackwardCompatibility_fieldTypesUnchanged() {
Responseresponse= given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/users/123")
.then()
.statusCode(200)
.extract().response();
// Verify types haven't changed
assertTrue(response.jsonPath().get("id") instanceof Integer);
assertTrue(response.jsonPath().get("email") instanceof String);
assertTrue(response.jsonPath().get("active") instanceof Boolean);
assertTrue(response.jsonPath().get("tags") instanceof List);
}
// Pact Consumer-Driven Contract Test@Pact(consumer = "OrderService", provider = "UserService")publicRequestResponsePactuserDetailsPact(PactDslWithProvider builder) {
return builder
.given("user 123 exists")
.uponReceiving("a request for user details")
.path("/api/v1/users/123")
.method("GET")
.willRespondWith()
.status(200)
.body(newPactDslJsonBody()
.integerType("id", 123)
.stringType("email", "user@test.com")
.stringType("name", "Test User")
.stringType("role", "user"))
.toPact();
}
@Test@PactVerification("UserService")publicvoidtestPactContract_userDetails() {
// This test verifies the provider still satisfies the consumer's expectationsResponseresponse= given()
.port(mockProvider.getPort())
.when()
.get("/api/v1/users/123")
.then()
.statusCode(200)
.extract().response();
assertNotNull(response.jsonPath().getString("email"));
}
Only testing your own consumers (third-party consumers may use fields you consider internal)
Not testing with the actual old client library version
Assuming additive changes are always safe (new required field in request body is breaking)
Not maintaining contract tests in CI/CD pipeline
Follow-up Questions
How does consumer-driven contract testing (Pact) prevent breaking changes?
How do you handle breaking changes that are necessary?
What is the Tolerant Reader pattern and how does it help?
Q16How do you test database transaction rollback?#
Objective
Demonstrate testing that failed operations correctly roll back all database changes, maintaining data integrity.
Interview Answer
Transaction rollback testing validates that when a multi-step operation fails midway, all prior steps are undone. This is critical for operations like fund transfers, order creation with inventory reservation, and multi-table inserts.
Test Approach:
Trigger an operation that should fail partway through
Verify ALL database changes from the transaction are reverted
Verify no orphaned records remain
Test at both the API level and the database level
// REST Assured — Transaction rollback testing@TestpublicvoidtestTransactionRollback_failedPayment_reversesOrderCreation() {
// Get initial stateintinitialOrderCount= getOrderCount();
doubleinitialBalance= getAccountBalance("user_123");
// Attempt to create order with payment that will fail (insufficient funds)
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer user123_token")
.body("""
{
"items": [{"productId": "prod_1", "quantity": 1}],
"paymentMethod": "card_insufficient_funds",
"amount": 999999.99
}
""")
.when()
.post("/api/v1/orders")
.then()
.statusCode(402)
.body("error.code", equalTo("payment_failed"));
// Verify order was NOT created (rolled back)
assertEquals(initialOrderCount, getOrderCount(),
"Order count should not change after failed payment");
// Verify balance unchanged
assertEquals(initialBalance, getAccountBalance("user_123"),
"Account balance should be unchanged");
// Verify no inventory reservation remains
given()
.header("Authorization", "Bearer admin_token")
.when()
.get("/api/v1/inventory/prod_1/reservations")
.then()
.body("reservations.findAll { it.userId == 'user_123' }.size()", equalTo(0));
}
@TestpublicvoidtestTransactionRollback_partialBatchInsert() {
// Batch insert where one record violates a constraintStringpayload="""
{
"users": [
{"email": "valid1@test.com", "name": "User 1"},
{"email": "valid2@test.com", "name": "User 2"},
{"email": "duplicate@test.com", "name": "Duplicate"},
{"email": "valid3@test.com", "name": "User 3"}
]
}
""";
// Pre-create the duplicate to trigger constraint violation
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer admin_token")
.body("{\"email\": \"duplicate@test.com\", \"name\": \"Existing\"}")
.when()
.post("/api/v1/users");
intcountBefore= getUserCount();
// Batch insert should fail and rollback all
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer admin_token")
.body(payload)
.when()
.post("/api/v1/users/batch")
.then()
.statusCode(409)
.body("error.code", equalTo("duplicate_entry"))
.body("error.failedIndex", equalTo(2));
// None of the valid records should exist
assertEquals(countBefore, getUserCount(),
"All inserts should be rolled back");
given()
.queryParam("email", "valid1@test.com")
.when()
.get("/api/v1/users")
.then()
.body("data.size()", equalTo(0));
}
@TestpublicvoidtestTransactionRollback_concurrentModification() {
// Simulate optimistic locking failureResponseoriginal= given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.extract().response();
Stringetag= original.getHeader("ETag");
intoriginalStock= original.jsonPath().getInt("stock");
// Another user modifies the resource first
given()
.header("Authorization", "Bearer other_user_token")
.header("Content-Type", "application/json")
.body("{\"stock\": " + (originalStock - 1) + "}")
.when()
.put("/api/v1/products/123");
// Our update with stale ETag should fail
given()
.header("Authorization", "Bearer token")
.header("Content-Type", "application/json")
.header("If-Match", etag)
.body("{\"stock\": " + (originalStock - 5) + "}")
.when()
.put("/api/v1/products/123")
.then()
.statusCode(409)
.body("error.code", equalTo("conflict"))
.body("error.message", containsString("modified"));
}
# curl — Verify rollback via DB state check# Attempt operation that will fail
curl -X POST https://api.example.com/v1/transfers \
-H "Content-Type: application/json" \
-H "Authorization: Bearer token" \
-d '{"from": "acc_1", "to": "acc_invalid", "amount": 100}' \
-w "\nHTTP: %{http_code}\n"# Verify source balance unchanged
curl -s https://api.example.com/v1/accounts/acc_1/balance \
-H "Authorization: Bearer token" | jq '.balance'
Common Mistakes to Avoid
Only checking the API response without verifying actual database state
Not testing distributed transaction scenarios (saga pattern rollback)
Forgetting to check for orphaned records in junction/association tables
Not testing rollback under concurrent load
Follow-up Questions
How do you test saga pattern compensating transactions?
What is the difference between ACID rollback and compensating transactions?
How do you test partial rollback in a microservices architecture?
Q17How do you test partial failure across services?#
Objective
Show how to validate system behavior when some services in a distributed call chain fail while others succeed.
Interview Answer
Partial failure testing validates that when one service in a chain fails, the system degrades gracefully rather than producing inconsistent state. This involves testing circuit breakers, fallback mechanisms, and saga compensation.
Scenarios:
Service A succeeds, Service B fails → A should compensate (rollback)
Service A succeeds, Service B times out → Retry or compensate
Multiple services called in parallel — some fail, some succeed
Cascade failure — one failure causes upstream failures
// REST Assured + WireMock — Testing partial failure@TestpublicvoidtestPartialFailure_paymentSucceeds_shippingFails() {
// Mock shipping service to fail
stubFor(post(urlEqualTo("/shipping/create"))
.willReturn(aResponse().withStatus(503)));
// Order creation should handle partial failure gracefullyResponseresponse= given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body("""
{
"items": [{"productId": "prod_1", "quantity": 1}],
"paymentMethod": "card_valid",
"shippingAddress": {"street": "123 Main St"}
}
""")
.when()
.post("/api/v1/orders")
.then()
.statusCode(201) // Order created despite shipping failure
.body("status", equalTo("pending_shipping"))
.body("warnings[0].service", equalTo("shipping"))
.body("warnings[0].message", containsString("temporarily unavailable"))
.extract().response();
StringorderId= response.jsonPath().getString("id");
// Verify payment was charged (succeeded)
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/orders/" + orderId + "/payment")
.then()
.body("status", equalTo("charged"));
// Verify shipping will be retried
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/orders/" + orderId + "/shipping")
.then()
.body("status", equalTo("pending_retry"))
.body("nextRetryAt", notNullValue());
}
@TestpublicvoidtestPartialFailure_criticalServiceFails_rollsBackAll() {
// Mock payment service to fail (critical — can't proceed without it)
stubFor(post(urlEqualTo("/payments/charge"))
.willReturn(aResponse().withStatus(500)));
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body("""
{
"items": [{"productId": "prod_1", "quantity": 1}],
"paymentMethod": "card_error"
}
""")
.when()
.post("/api/v1/orders")
.then()
.statusCode(500)
.body("error.code", equalTo("payment_service_unavailable"))
.body("error.retryable", equalTo(true));
// Verify inventory reservation was released (compensated)
given()
.header("Authorization", "Bearer admin_token")
.when()
.get("/api/v1/inventory/prod_1")
.then()
.body("availableStock", equalTo(100)); // Original stock restored
}
@TestpublicvoidtestPartialFailure_circuitBreakerOpens() {
// Fail shipping service repeatedly to trip circuit breaker
stubFor(post(urlEqualTo("/shipping/create"))
.willReturn(aResponse().withStatus(503)));
// Make enough calls to open the circuitfor (inti=0; i < 5; i++) {
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body("{\"items\": [{\"productId\": \"prod_1\", \"quantity\": 1}]}")
.when()
.post("/api/v1/orders");
}
// Verify circuit breaker status
given()
.header("Authorization", "Bearer admin_token")
.when()
.get("/api/v1/internal/circuit-breakers")
.then()
.body("breakers.shipping.state", equalTo("OPEN"))
.body("breakers.shipping.failureCount", greaterThanOrEqualTo(5));
}
Partial Failure Diagram:
Order Service
├── Payment Service ✓ (Success)
├── Inventory Service ✓ (Success)
└── Shipping Service ✗ (503 Failure)
→ Circuit Breaker: CLOSED → OPEN
→ Fallback: Queue for retry
→ Order Status: "pending_shipping"
Common Mistakes to Avoid
Not distinguishing between critical and non-critical service failures
Not testing the compensation/saga rollback when a critical service fails
Forgetting to test the "half-open" state of circuit breakers
Not verifying that partial failure is visible in the response (warnings array)
Follow-up Questions
How do you implement the saga pattern for distributed transactions?
What is the difference between orchestration and choreography in saga patterns?
How do you test circuit breaker state transitions?
Demonstrate testing of message queue consumer idempotency and redelivery handling with at-least-once delivery guarantees.
Interview Answer
Message queues with at-least-once delivery guarantee may deliver the same message multiple times. Testing ensures consumers handle redelivery without duplicate side effects, and that retry mechanisms work correctly for failed processing.
Key Scenarios:
Same message delivered twice — processed only once
Processing failure — message returns to queue for retry
Poison messages — moved to dead-letter queue after max retries
Show testing strategies for DLQ configuration, message routing, and alerting when messages fail processing.
Interview Answer
A Dead-Letter Queue (DLQ) captures messages that cannot be processed after exhausting retry attempts. Testing validates that messages are correctly routed to the DLQ, retain their metadata, trigger alerts, and can be replayed.
Test Scenarios:
Message exceeds max retry count → routed to DLQ
Message TTL expires → routed to DLQ
Message schema invalid → routed to DLQ immediately (no retry)
DLQ message retains original headers and error context
DLQ message can be replayed to original queue
Alerts fire when DLQ depth exceeds threshold
// Testing Dead-Letter Queue behavior@TestpublicvoidtestDLQ_messageRoutedAfterMaxRetries() {
intmaxRetries=3;
StringpoisonMessage="""
{
"messageId": "msg_dlq_test",
"type": "order.created",
"data": {"orderId": "will_fail_processing"}
}
""";
// Publish poison message
publishToQueue("orders.created", poisonMessage, "msg_dlq_test");
// Wait for all retries to exhaust
await().atMost(60, TimeUnit.SECONDS).pollInterval(2, TimeUnit.SECONDS)
.until(() -> getDeadLetterQueueDepth("orders.created.dlq") == 1);
// Verify original queue is empty (message moved to DLQ)
assertEquals(0, getQueueDepth("orders.created"));
// Read DLQ message and verify metadataMessagedlqMsg= peekDeadLetterQueue("orders.created.dlq");
assertEquals("msg_dlq_test", extractMessageId(dlqMsg));
assertEquals(maxRetries, Integer.parseInt(dlqMsg.getAttribute("ApproximateReceiveCount")));
assertNotNull(dlqMsg.getAttribute("x-first-death-reason"));
assertNotNull(dlqMsg.getAttribute("x-first-death-queue"));
}
@TestpublicvoidtestDLQ_messageRetainsOriginalPayload() {
StringoriginalPayload="""
{
"messageId": "msg_payload_check",
"type": "payment.created",
"data": {"paymentId": "pay_999", "amount": 5000}
}
""";
publishToQueue("payments.created", originalPayload, "msg_payload_check");
// Wait for DLQ routing
await().atMost(60, TimeUnit.SECONDS)
.until(() -> getDeadLetterQueueDepth("payments.created.dlq") == 1);
// Verify payload integrityMessagedlqMsg= peekDeadLetterQueue("payments.created.dlq");
JsonNodebody= objectMapper.readTree(dlqMsg.getBody());
assertEquals("msg_payload_check", body.get("messageId").asText());
assertEquals(5000, body.get("data").get("amount").asInt());
}
@TestpublicvoidtestDLQ_replayMessage_reprocessesSuccessfully() {
// Place a message in DLQ manuallyStringmessage="""
{
"messageId": "msg_replay_test",
"type": "order.created",
"data": {"orderId": "ord_replay"}
}
""";
publishToQueue("orders.created.dlq", message, "msg_replay_test");
// Fix the root cause (e.g., downstream service now available)
enableOrderProcessing();
// Replay DLQ messages back to original queue
given()
.header("Authorization", "Bearer admin_token")
.header("Content-Type", "application/json")
.body("{\"sourceQueue\": \"orders.created.dlq\", \"targetQueue\": \"orders.created\"}")
.when()
.post("/api/v1/admin/queues/replay")
.then()
.statusCode(200)
.body("replayedCount", equalTo(1));
// Verify message was successfully processed
await().atMost(10, TimeUnit.SECONDS).until(() ->
getOrderStatus("ord_replay").equals("confirmed")
);
}
@TestpublicvoidtestDLQ_alertTriggeredOnThreshold() {
// Publish multiple poison messages to trigger DLQ alertfor (inti=0; i < 10; i++) {
publishToQueue("orders.created",
"{\"messageId\": \"poison_" + i + "\", \"data\": {\"invalid\": true}}",
"poison_" + i);
}
// Wait for DLQ to fill
await().atMost(120, TimeUnit.SECONDS)
.until(() -> getDeadLetterQueueDepth("orders.created.dlq") >= 10);
// Verify alert was triggered
given()
.header("Authorization", "Bearer admin_token")
.when()
.get("/api/v1/admin/alerts?type=dlq_threshold")
.then()
.body("alerts.size()", greaterThan(0))
.body("alerts[0].queue", equalTo("orders.created.dlq"))
.body("alerts[0].currentDepth", greaterThanOrEqualTo(10))
.body("alerts[0].severity", equalTo("critical"));
}
# AWS SQS — DLQ inspection# Check DLQ depth
aws sqs get-queue-attributes \
--queue-url https://sqs.us-east-1.amazonaws.com/123456789/orders-dlq \
--attribute-names ApproximateNumberOfMessages
# Read messages from DLQ (without consuming)
aws sqs receive-message \
--queue-url https://sqs.us-east-1.amazonaws.com/123456789/orders-dlq \
--max-number-of-messages 5 \
--visibility-timeout 0
# Replay DLQ messages (move back to source queue)# Using a script or AWS Lambda
Show how to simulate third-party service outages and validate the system's resilience, fallback behavior, and recovery mechanisms.
Interview Answer
External provider outage testing validates that your system gracefully handles situations when a third-party dependency (payment gateway, email service, SMS provider) becomes unavailable. This uses service virtualization, fault injection, and chaos engineering principles.
Test Strategy:
Simulate complete outage (connection refused)
Simulate degraded service (high latency, intermittent errors)
Verify fallback behavior (cached data, alternative provider, queued retry)
Test recovery when service comes back online
Validate user-facing error messages are appropriate
Validate that error responses follow a consistent schema across all endpoints, providing actionable information for API consumers.
Interview Answer
Error schema testing ensures that all API errors follow a consistent, documented format regardless of which endpoint produces them. This is critical for client-side error handling and developer experience.
Standard Error Schema:
{"error":{"code":"string (machine-readable)","message":"string (human-readable)","details":[{"field":"string","issue":"string"}],"correlationId":"string (UUID)","timestamp":"string (ISO 8601)","documentation":"string (URL)"}}
Demonstrate testing file upload endpoints including valid uploads, size limits, type validation, and error scenarios.
Interview Answer
Multipart upload testing validates file handling including content type validation, size enforcement, virus scanning, metadata extraction, and storage. Key challenges include boundary handling, streaming large files, and concurrent uploads.
Show testing of request/response size limits, streaming behavior, and graceful handling of oversized payloads.
Interview Answer
Large payload testing validates that the API correctly enforces size limits, handles edge cases around boundaries, and provides clear error messages. This covers both request body limits and response size management.
Key Test Scenarios:
Payload exactly at limit → accepted
Payload 1 byte over limit → rejected with 413
Chunked transfer encoding behavior
Response pagination for large result sets
Memory/timeout behavior with large payloads
// REST Assured — Large payload testing@TestpublicvoidtestPayloadLimit_withinLimit_accepted() {
// Create payload just under 1MB limitStringlargeDescription="A".repeat(999_000);
Stringpayload="{\"name\": \"Test\", \"description\": \"" + largeDescription + "\"}";
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body(payload)
.when()
.post("/api/v1/products")
.then()
.statusCode(201);
}
@TestpublicvoidtestPayloadLimit_exceedsLimit_returns413() {
// Create payload over 1MB limitStringoversizedDescription="B".repeat(1_100_000);
Stringpayload="{\"name\": \"Test\", \"description\": \"" + oversizedDescription + "\"}";
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body(payload)
.when()
.post("/api/v1/products")
.then()
.statusCode(413)
.body("error.code", equalTo("payload_too_large"))
.body("error.message", containsString("1MB"))
.body("error.maxSize", equalTo("1048576"));
}
@TestpublicvoidtestPayloadLimit_largeArray_enforced() {
// Create request with too many itemsList<Map<String, String>> items=newArrayList<>();
for (inti=0; i < 10001; i++) { // Limit is 10000
items.add(Map.of("name", "Item " + i));
}
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body(Map.of("items", items))
.when()
.post("/api/v1/products/batch")
.then()
.statusCode(400)
.body("error.code", equalTo("too_many_items"))
.body("error.message", containsString("10000"));
}
@TestpublicvoidtestPayloadLimit_deeplyNestedJson_rejected() {
// Create deeply nested JSON (potential DoS vector)StringBuildernested=newStringBuilder("{");
for (inti=0; i < 200; i++) { // Limit might be 50 levels
nested.append("\"level").append(i).append("\":{");
}
nested.append("\"value\":1");
for (inti=0; i < 200; i++) {
nested.append("}");
}
nested.append("}");
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body(nested.toString())
.when()
.post("/api/v1/data")
.then()
.statusCode(400)
.body("error.code", equalTo("payload_nesting_exceeded"));
}
@TestpublicvoidtestPayloadLimit_responseTime_withinSLA() {
// Large but valid payload should still respond within SLAStringpayload= createValidLargePayload(500_000); // 500KBlongstart= System.currentTimeMillis();
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body(payload)
.when()
.post("/api/v1/products")
.then()
.statusCode(201);
longelapsed= System.currentTimeMillis() - start;
assertTrue(elapsed < 5000, "Large payload should process within 5s SLA");
}
@TestpublicvoidtestPayloadLimit_contentLengthHeader_validated() {
// Mismatch between Content-Length and actual body
given()
.header("Content-Type", "application/json")
.header("Content-Length", "999999999") // Lie about size
.header("Authorization", "Bearer token")
.body("{\"name\": \"small\"}")
.when()
.post("/api/v1/products")
.then()
.statusCode(anyOf(is(400), is(413)));
}
Show how to systematically detect and prevent Personal Identifiable Information leakage through API responses, logs, and error messages.
Interview Answer
PII exposure testing ensures that sensitive personal data (SSN, credit card numbers, passwords, health data) is never returned in API responses, error messages, logs, or headers unless explicitly required and properly authorized.
PII Categories to Test:
Direct identifiers: SSN, passport number, credit card, bank account
Quasi-identifiers: Date of birth, zip code, gender (combination can identify)
Sensitive data: Health records, financial data, biometric data
Credentials: Passwords, API keys, tokens, secrets
// REST Assured — PII exposure testing@TestpublicvoidtestPIIExposure_userEndpoint_masksSSN() {
given()
.header("Authorization", "Bearer regular_user_token")
.when()
.get("/api/v1/users/me")
.then()
.statusCode(200)
.body("$", not(hasKey("ssn")))
.body("$", not(hasKey("socialSecurityNumber")))
.body("$", not(hasKey("password")))
.body("$", not(hasKey("passwordHash")));
}
@TestpublicvoidtestPIIExposure_creditCardMasked() {
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/users/me/payment-methods")
.then()
.statusCode(200)
.body("cards[0].number", matchesPattern("\\*{12}\\d{4}")) // Only last 4 digits
.body("cards[0].cvv", nullValue()) // Never returned
.body("cards[0].expiryMonth", notNullValue()) // OK to show
.body("cards[0].expiryYear", notNullValue());
}
@TestpublicvoidtestPIIExposure_searchEndpoint_noSensitiveData() {
// Search should not expose PII of other usersResponseresponse= given()
.header("Authorization", "Bearer token")
.queryParam("q", "John")
.when()
.get("/api/v1/users/search")
.then()
.statusCode(200)
.extract().response();
List<Map<String, Object>> users= response.jsonPath().getList("data");
for (Map<String, Object> user : users) {
assertFalse(user.containsKey("email"), "Email should not be in search results");
assertFalse(user.containsKey("phone"), "Phone should not be in search results");
assertFalse(user.containsKey("address"), "Address should not be in search results");
assertFalse(user.containsKey("dateOfBirth"), "DOB should not be in search results");
}
}
@TestpublicvoidtestPIIExposure_errorMessages_noSensitiveData() {
// Trigger error with sensitive data in request
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body("{\"ssn\": \"123-45-6789\", \"email\": \"user@test.com\"}")
.when()
.post("/api/v1/users/verify")
.then()
.statusCode(anyOf(is(200), is(400), is(422)))
.body("error.message", not(containsString("123-45-6789")))
.body("error.message", not(containsString("user@test.com")))
.body(not(containsString("123-45-6789"))); // Nowhere in response body
}
@TestpublicvoidtestPIIExposure_responseHeaders_clean() {
Responseresponse= given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/users/me")
.then()
.extract().response();
// Check no PII in response headers
response.getHeaders().asList().forEach(header -> {
Stringvalue= header.getValue();
assertFalse(value.matches(".*\\d{3}-\\d{2}-\\d{4}.*"), "SSN in header: " + header.getName());
assertFalse(value.matches(".*\\d{16}.*"), "Card number in header: " + header.getName());
});
}
@TestpublicvoidtestPIIExposure_adminEndpoint_showsDataOnlyWithElevatedRole() {
// Regular user cannot see full PII
given()
.header("Authorization", "Bearer regular_user_token")
.when()
.get("/api/v1/admin/users/456")
.then()
.statusCode(403);
// Admin can see full PII (with audit logging)
given()
.header("Authorization", "Bearer admin_token")
.when()
.get("/api/v1/admin/users/456")
.then()
.statusCode(200)
.body("email", notNullValue())
.body("phone", notNullValue())
// But still never returns passwords
.body("$", not(hasKey("password")));
}
@TestpublicvoidtestPIIExposure_bulkExport_respectsDataMinimization() {
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/reports/users")
.then()
.statusCode(200)
.body("users[0]", not(hasKey("ssn")))
.body("users[0]", not(hasKey("creditCard")))
.body("users[0]", not(hasKey("password")))
.body("users[0]", not(hasKey("refreshToken")));
}
Demonstrate testing that multi-tenant systems properly isolate data between tenants, preventing cross-tenant data access.
Interview Answer
Tenant isolation testing validates that users from one tenant (organization) cannot access, modify, or even detect the existence of data belonging to another tenant. This is one of the most critical security tests in SaaS applications.
Isolation Levels to Test:
Data isolation — Tenant A cannot read Tenant B's data
API isolation — Tenant A's queries never return Tenant B's results
Resource isolation — Tenant A cannot affect Tenant B's quotas
Metadata isolation — Tenant A cannot enumerate other tenants
// REST Assured — Tenant isolation testing@TestpublicvoidtestTenantIsolation_cannotAccessOtherTenantData() {
// Create resource as Tenant AStringresourceId= given()
.header("Authorization", "Bearer " + tenantAToken)
.header("X-Tenant-ID", "tenant_a")
.header("Content-Type", "application/json")
.body("{\"name\": \"Tenant A Secret Document\", \"content\": \"confidential\"}")
.when()
.post("/api/v1/documents")
.then()
.statusCode(201)
.extract().jsonPath().getString("id");
// Tenant B attempts to access Tenant A's resource
given()
.header("Authorization", "Bearer " + tenantBToken)
.header("X-Tenant-ID", "tenant_b")
.when()
.get("/api/v1/documents/" + resourceId)
.then()
.statusCode(404); // Should not even confirm existence (not 403)
}
@TestpublicvoidtestTenantIsolation_listEndpointFiltersByTenant() {
// Create documents for both tenants
createDocumentAsTenant("tenant_a", "Doc A1");
createDocumentAsTenant("tenant_a", "Doc A2");
createDocumentAsTenant("tenant_b", "Doc B1");
// Tenant A lists documents — should only see their ownResponsetenantAList= given()
.header("Authorization", "Bearer " + tenantAToken)
.header("X-Tenant-ID", "tenant_a")
.when()
.get("/api/v1/documents")
.then()
.statusCode(200)
.extract().response();
List<String> names= tenantAList.jsonPath().getList("data.name");
assertTrue(names.contains("Doc A1"));
assertTrue(names.contains("Doc A2"));
assertFalse(names.contains("Doc B1"), "Tenant B's document should not appear");
}
@TestpublicvoidtestTenantIsolation_cannotModifyOtherTenantResource() {
StringtenantADoc= createDocumentAsTenant("tenant_a", "Original");
// Tenant B attempts to update Tenant A's document
given()
.header("Authorization", "Bearer " + tenantBToken)
.header("X-Tenant-ID", "tenant_b")
.header("Content-Type", "application/json")
.body("{\"name\": \"Hacked\"}")
.when()
.put("/api/v1/documents/" + tenantADoc)
.then()
.statusCode(404); // Not 403 — don't confirm existence// Verify document unchanged
given()
.header("Authorization", "Bearer " + tenantAToken)
.header("X-Tenant-ID", "tenant_a")
.when()
.get("/api/v1/documents/" + tenantADoc)
.then()
.body("name", equalTo("Original"));
}
@TestpublicvoidtestTenantIsolation_cannotDeleteOtherTenantResource() {
StringtenantADoc= createDocumentAsTenant("tenant_a", "Important");
// Tenant B attempts to delete
given()
.header("Authorization", "Bearer " + tenantBToken)
.header("X-Tenant-ID", "tenant_b")
.when()
.delete("/api/v1/documents/" + tenantADoc)
.then()
.statusCode(404);
// Verify document still exists
given()
.header("Authorization", "Bearer " + tenantAToken)
.header("X-Tenant-ID", "tenant_a")
.when()
.get("/api/v1/documents/" + tenantADoc)
.then()
.statusCode(200);
}
@TestpublicvoidtestTenantIsolation_searchDoesNotLeakCrossTenant() {
createDocumentAsTenant("tenant_a", "Quantum Physics Research");
createDocumentAsTenant("tenant_b", "Quantum Computing Paper");
// Tenant A searches for "Quantum"
given()
.header("Authorization", "Bearer " + tenantAToken)
.header("X-Tenant-ID", "tenant_a")
.queryParam("q", "Quantum")
.when()
.get("/api/v1/documents/search")
.then()
.statusCode(200)
.body("results.size()", equalTo(1))
.body("results[0].name", equalTo("Quantum Physics Research"));
}
@TestpublicvoidtestTenantIsolation_tenantIdTampering_rejected() {
// User from Tenant A tries to set X-Tenant-ID to Tenant B
given()
.header("Authorization", "Bearer " + tenantAToken) // Token belongs to Tenant A
.header("X-Tenant-ID", "tenant_b") // Attempting to impersonate Tenant B
.when()
.get("/api/v1/documents")
.then()
.statusCode(403)
.body("error.code", equalTo("tenant_mismatch"));
}
@TestpublicvoidtestTenantIsolation_aggregateEndpoints_scopedToTenant() {
// Dashboard/analytics should be tenant-scoped
given()
.header("Authorization", "Bearer " + tenantAToken)
.header("X-Tenant-ID", "tenant_a")
.when()
.get("/api/v1/analytics/document-count")
.then()
.statusCode(200)
.body("count", greaterThan(0)) // Only counts Tenant A's documents
.body("tenantId", equalTo("tenant_a"));
}
Show how to verify that audit logging captures all required security events with proper detail and tamper resistance.
Interview Answer
Audit log validation ensures that security-relevant actions are properly recorded for compliance, forensics, and anomaly detection. Testing covers completeness, accuracy, tamper resistance, and queryability.
Demonstrate testing strategies for ensuring cached data is properly invalidated when underlying data changes.
Interview Answer
Cache invalidation testing ensures that stale data is not served after updates. The famous quote "There are only two hard things in Computer Science: cache invalidation and naming things" reflects the real-world complexity. Testing must verify both that caching improves performance AND that invalidation maintains correctness.
Test Scenarios:
Fresh cache — response includes cache headers
Cache hit — faster response, correct data
Write invalidates cache — next read returns fresh data
TTL expiration — cache auto-refreshes after timeout
Cache stampede protection — only one origin request when cache expires
// REST Assured — Cache invalidation testing@TestpublicvoidtestCache_responseIncludesCacheHeaders() {
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.statusCode(200)
.header("Cache-Control", containsString("max-age="))
.header("ETag", notNullValue())
.header("Last-Modified", notNullValue());
}
@TestpublicvoidtestCache_conditionalGet_returns304() {
// First request — get ETagResponsefirst= given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.statusCode(200)
.extract().response();
Stringetag= first.getHeader("ETag");
// Conditional request with If-None-Match
given()
.header("Authorization", "Bearer token")
.header("If-None-Match", etag)
.when()
.get("/api/v1/products/123")
.then()
.statusCode(304); // Not Modified — use cached version
}
@TestpublicvoidtestCache_writeInvalidatesCache() {
// Read to populate cacheResponseoriginal= given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.statusCode(200)
.extract().response();
StringoriginalName= original.jsonPath().getString("name");
StringoriginalEtag= original.getHeader("ETag");
// Update the product
given()
.header("Authorization", "Bearer token")
.header("Content-Type", "application/json")
.body("{\"name\": \"Updated Product Name\"}")
.when()
.put("/api/v1/products/123")
.then()
.statusCode(200);
// Read again — should get fresh data (not cached)
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.statusCode(200)
.body("name", equalTo("Updated Product Name"))
.header("ETag", not(equalTo(originalEtag))); // New ETag
}
@TestpublicvoidtestCache_TTLExpiration_refreshesData()throws Exception {
// Read to populate cache (TTL = 5s for test config)
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.statusCode(200)
.header("Cache-Control", containsString("max-age=5"));
// Update directly in database (bypass API cache invalidation)
updateProductDirectlyInDB("123", "DB Updated Name");
// Read immediately — should still get cached value
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.body("name", not(equalTo("DB Updated Name"))); // Still cached// Wait for TTL to expire
Thread.sleep(6000);
// Read after TTL — should get fresh data
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.body("name", equalTo("DB Updated Name"));
}
@TestpublicvoidtestCache_deleteInvalidatesCache() {
// Populate cache
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/456")
.then()
.statusCode(200);
// Delete the product
given()
.header("Authorization", "Bearer token")
.when()
.delete("/api/v1/products/456")
.then()
.statusCode(204);
// Cache should be invalidated — return 404
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/456")
.then()
.statusCode(404);
}
@TestpublicvoidtestCache_performanceImprovement() {
// First request (cache miss) — slowerlongfirstStart= System.currentTimeMillis();
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.statusCode(200)
.header("X-Cache", equalTo("MISS"));
longfirstTime= System.currentTimeMillis() - firstStart;
// Second request (cache hit) — fasterlongsecondStart= System.currentTimeMillis();
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/products/123")
.then()
.statusCode(200)
.header("X-Cache", equalTo("HIT"));
longsecondTime= System.currentTimeMillis() - secondStart;
assertTrue(secondTime < firstTime / 2,
"Cache hit should be significantly faster than cache miss");
}
Show how to validate that webhook signature verification is correctly implemented to prevent spoofed webhook deliveries.
Interview Answer
Webhook signatures authenticate that a webhook payload genuinely originated from the expected provider and was not tampered with in transit. Testing validates both valid signatures (accepted) and invalid/missing signatures (rejected).
How Webhook Signatures Work:
Provider computes HMAC-SHA256 of the payload using a shared secret
Signature is sent in a header (e.g., X-Webhook-Signature)
Demonstrate comprehensive testing of bulk/batch API endpoints including partial success, error reporting, and performance.
Interview Answer
Bulk endpoints accept multiple items in a single request for efficient batch processing. Testing must cover full success, partial failure, validation across items, ordering guarantees, and performance under load.
Key Behaviors to Validate:
All items valid → all processed successfully
Some items invalid → partial success with per-item error reporting
Demonstrate a systematic debugging methodology for defects that only manifest at the API layer — not reproducible through the UI or unit tests.
Interview Answer
An API-only defect is one that cannot be reproduced through the UI or caught by unit tests. It typically involves specific request combinations, race conditions, header manipulations, or infrastructure-level issues. Investigation requires a structured approach combining observability tools, traffic analysis, and systematic isolation.
Investigation Framework (RAPID):
Reproduce — Capture the exact failing request
Analyze — Examine logs, traces, and metrics
Pinpoint — Isolate the variable that triggers the defect
Identify — Determine root cause
Document — Record findings and write a regression test
// Step 1: Reproduce — Capture and replay the exact request@TestpublicvoidreproduceDefect_JIRA_1234() {
// Exact reproduction from production logsResponseresponse= given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer user_token")
.header("Accept-Language", "fr-FR") // Defect only occurs with French locale
.header("X-Forwarded-For", "203.0.113.50")
.body("""
{
"amount": 10.50,
"currency": "EUR",
"description": "Café résumé — naïve"
}
""")
.when()
.post("/api/v1/payments")
.then()
.extract().response();
// Log full response for analysis
System.out.println("Status: " + response.getStatusCode());
System.out.println("Body: " + response.getBody().asString());
System.out.println("Headers: " + response.getHeaders());
// This was returning 500 due to encoding issue with special characters
assertEquals(201, response.getStatusCode());
}
// Step 2: Analyze — Check correlation ID in distributed tracing@TestpublicvoidanalyzeDefect_traceRequest() {
StringcorrelationId="prod-trace-abc123"; // From production logs// Query distributed trace
given()
.header("Authorization", "Bearer admin_token")
.when()
.get("/api/v1/admin/traces/" + correlationId)
.then()
.statusCode(200)
.body("spans.size()", greaterThan(0))
.body("spans.find { it.service == 'payment-service' }.error", notNullValue());
}
// Step 3: Pinpoint — Isolate the triggering variable@TestpublicvoidpinpointDefect_isolateVariable() {
StringbasePayload="{\"amount\": 10.50, \"currency\": \"EUR\", \"description\": \"%s\"}";
// Test with ASCII-only description — works
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body(String.format(basePayload, "Normal description"))
.when()
.post("/api/v1/payments")
.then()
.statusCode(201);
// Test with UTF-8 special characters — fails
given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer token")
.body(String.format(basePayload, "Café résumé"))
.when()
.post("/api/v1/payments")
.then()
.statusCode(201); // Was returning 500 before fix// Test with emoji — also fails
given()
.header("Content-Type", "application/json; charset=UTF-8")
.header("Authorization", "Bearer token")
.body(String.format(basePayload, "Payment 🎉"))
.when()
.post("/api/v1/payments")
.then()
.statusCode(201);
}
// Step 4: Identify — Root cause analysis/*
* Root Cause: The payment service was using Latin-1 encoding instead of UTF-8
* when writing to the database. Special characters caused a
* CharacterEncodingException that wasn't properly caught.
*
* Why UI didn't catch it: The UI form stripped special characters before sending.
* Why unit tests missed it: Unit tests used mock DB that accepted any encoding.
*/// Step 5: Document — Write regression test@TestpublicvoidregressionTest_JIRA_1234_utf8InPaymentDescription() {
String[] testDescriptions= {
"Café résumé", // French accented characters"naïve señor", // Spanish characters"Ürsprüng", // German umlauts"日本語テスト", // Japanese"Payment 🎉💰", // Emoji"Line1\nLine2", // Newlines"Tab\there", // Tabs"Quote \"test\"", // Escaped quotes"<script>alert(1)</script>"// XSS attempt (should be stored safely)
};
for (String desc : testDescriptions) {
Responseresponse= given()
.header("Content-Type", "application/json; charset=UTF-8")
.header("Authorization", "Bearer token")
.body("{\"amount\": 10.50, \"currency\": \"EUR\", \"description\": \""
+ desc.replace("\"", "\\\"") + "\"}")
.when()
.post("/api/v1/payments")
.then()
.statusCode(201)
.extract().response();
StringpaymentId= response.jsonPath().getString("id");
// Verify stored correctly (round-trip)
given()
.header("Authorization", "Bearer token")
.when()
.get("/api/v1/payments/" + paymentId)
.then()
.body("description", equalTo(desc));
}
}