API & Integration Testing

Idempotency, contract testing, resilience patterns, authentication flows, async APIs, and microservices debugging.

Overview #

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.

Key Themes:

  • Contract validation and schema enforcement
  • Resilience patterns (retries, timeouts, circuit breakers)
  • Security testing (authentication, authorization, PII)
  • Asynchronous and event-driven architectures
  • Observability and debugging distributed systems

Frameworks & Tools Referenced:

  • REST Assured (Java)
  • Postman/Newman
  • curl
  • WireMock
  • JSON Schema Validator
  • Karate DSL
  • Apache JMeter

Q1What makes an API idempotent? #

Objective

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:

  1. Network failures cause retries — without idempotency, a payment could be charged twice
  2. Load balancers may replay requests during failover
  3. Message queues may deliver the same message multiple times (at-least-once delivery)
// REST Assured — Testing PUT idempotency
@Test
public void testPutIdempotency() {
    String payload = "{\"name\": \"Updated User\", \"email\": \"user@test.com\"}";

    // First PUT request
    Response first = given()
        .header("Content-Type", "application/json")
        .body(payload)
    .when()
        .put("/api/v1/users/123")
    .then()
        .statusCode(200)
        .extract().response();

    // Second identical PUT request
    Response second = 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

Request/Response Example:

PUT /api/v1/users/123
Content-Type: application/json

{"name": "Updated User", "email": "user@test.com"}

--- Response (both calls) ---
HTTP/1.1 200 OK
{
  "id": 123,
  "name": "Updated User",
  "email": "user@test.com",
  "updatedAt": "2026-07-15T10:00:00Z"
}

Common Mistakes to Avoid

  • Assuming all DELETE operations are idempotent (some return 404 on second call vs 204)
  • Confusing idempotent with safe (PUT is idempotent but not safe — it modifies state)
  • Not testing the database state after repeated calls (response may look same but DB has duplicates)

Follow-up Questions

  • How does idempotency differ from being "safe" in HTTP semantics?
  • What happens if a network timeout occurs between the server processing and sending the response?
  • How would you test idempotency in an event-driven system?

Q2How would you test idempotency keys? #

Objective

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:

  1. Happy path — Same key, same request returns cached response
  2. Same key, different body — Should return 422 Unprocessable Entity
  3. Key expiration — After TTL, key should no longer be recognized
  4. Concurrent requests — Same key sent simultaneously should process only once
  5. Different keys, same body — Should create two separate resources
// REST Assured — Comprehensive idempotency key testing
@Test
public void testIdempotencyKey_duplicateRequest_returnsCachedResponse() {
    String idempotencyKey = UUID.randomUUID().toString();
    String payload = "{\"amount\": 5000, \"currency\": \"USD\", \"recipient\": \"acc_123\"}";

    // First request — creates the payment
    Response first = given()
        .header("Content-Type", "application/json")
        .header("Idempotency-Key", idempotencyKey)
        .header("Authorization", "Bearer sk_test_token")
        .body(payload)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(201)
        .extract().response();

    // Second request — same key, same body
    Response second = given()
        .header("Content-Type", "application/json")
        .header("Idempotency-Key", idempotencyKey)
        .header("Authorization", "Bearer sk_test_token")
        .body(payload)
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(200) // Note: 200 not 201 — indicates cached
        .extract().response();

    assertEquals(first.jsonPath().getString("id"), second.jsonPath().getString("id"));
    assertEquals(first.jsonPath().getInt("amount"), second.jsonPath().getInt("amount"));
}

@Test
public void testIdempotencyKey_sameKeyDifferentBody_returnsConflict() {
    String idempotencyKey = UUID.randomUUID().toString();

    given()
        .header("Idempotency-Key", idempotencyKey)
        .header("Content-Type", "application/json")
        .body("{\"amount\": 5000, \"currency\": \"USD\"}")
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(201);

    // Same key but different amount
    given()
        .header("Idempotency-Key", idempotencyKey)
        .header("Content-Type", "application/json")
        .body("{\"amount\": 9999, \"currency\": \"USD\"}")
    .when()
        .post("/api/v1/payments")
    .then()
        .statusCode(422)
        .body("error.code", equalTo("idempotency_key_mismatch"));
}

@Test
public void testIdempotencyKey_concurrentRequests_processesOnce() throws Exception {
    String idempotencyKey = UUID.randomUUID().toString();
    String payload = "{\"amount\": 5000, \"currency\": \"USD\"}";
    AtomicInteger createdCount = new AtomicInteger(0);

    ExecutorService executor = Executors.newFixedThreadPool(5);
    List<Future<Response>> futures = new ArrayList<>();

    for (int i = 0; i < 5; i++) {
        futures.add(executor.submit(() -> given()
            .header("Idempotency-Key", idempotencyKey)
            .header("Content-Type", "application/json")
            .body(payload)
        .when()
            .post("/api/v1/payments")
        .then()
            .extract().response()));
    }

    Set<String> paymentIds = new HashSet<>();
    for (Future<Response> f : futures) {
        paymentIds.add(f.get().jsonPath().getString("id"));
    }

    assertEquals(1, paymentIds.size(), "Only one payment should be created");
}
# curl — Testing idempotency key
IDEM_KEY=$(uuidgen)

# First call
curl -X POST https://api.example.com/v1/payments \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IDEM_KEY" \
  -H "Authorization: Bearer sk_test_token" \
  -d '{"amount": 5000, "currency": "USD"}' \
  -w "\nHTTP Status: %{http_code}\n"

# Repeat — should get same response
curl -X POST https://api.example.com/v1/payments \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IDEM_KEY" \
  -H "Authorization: Bearer sk_test_token" \
  -d '{"amount": 5000, "currency": "USD"}' \
  -w "\nHTTP Status: %{http_code}\n"

Common Mistakes to Avoid

  • 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:

  1. Client or API gateway generates a UUID and attaches it as a header (e.g., X-Correlation-ID)
  2. Each downstream service reads and forwards this header
  3. Every log entry includes the correlation ID
  4. 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
// REST Assured — Testing correlation ID propagation
@Test
public void testCorrelationId_propagatedInResponse() {
    String correlationId = UUID.randomUUID().toString();

    given()
        .header("X-Correlation-ID", correlationId)
        .header("Authorization", "Bearer token123")
    .when()
        .get("/api/v1/orders/456")
    .then()
        .statusCode(200)
        .header("X-Correlation-ID", equalTo(correlationId));
}

@Test
public void testCorrelationId_generatedWhenMissing() {
    Response response = given()
        .header("Authorization", "Bearer token123")
    .when()
        .get("/api/v1/orders/456")
    .then()
        .statusCode(200)
        .extract().response();

    String generatedId = response.getHeader("X-Correlation-ID");
    assertNotNull(generatedId, "Server should generate correlation ID if not provided");
    assertTrue(generatedId.matches("[0-9a-f\\-]{36}"), "Should be valid UUID format");
}

@Test
public void testCorrelationId_presentInErrorResponses() {
    String correlationId = UUID.randomUUID().toString();

    given()
        .header("X-Correlation-ID", correlationId)
    .when()
        .get("/api/v1/orders/nonexistent")
    .then()
        .statusCode(404)
        .header("X-Correlation-ID", equalTo(correlationId))
        .body("error.correlationId", equalTo(correlationId));
}
# curl — Sending and verifying correlation ID
curl -X GET https://api.example.com/v1/orders/456 \
  -H "X-Correlation-ID: 550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Bearer token123" \
  -v 2>&1 | grep -i "x-correlation-id"

Request/Response Example:

GET /api/v1/orders/456
X-Correlation-ID: 550e8400-e29b-41d4-a716-446655440000

--- Response ---
HTTP/1.1 200 OK
X-Correlation-ID: 550e8400-e29b-41d4-a716-446655440000

{
  "orderId": 456,
  "status": "shipped",
  "correlationId": "550e8400-e29b-41d4-a716-446655440000"
}

Observability Diagram:

Client → [X-Correlation-ID: abc-123] → API Gateway
    → [abc-123] → Order Service (logs: "Processing order | corrId=abc-123")
        → [abc-123] → Payment Service (logs: "Charging card | corrId=abc-123")
        → [abc-123] → Inventory Service (logs: "Reserving stock | corrId=abc-123")
    ← Response [X-Correlation-ID: abc-123]

Common Mistakes to Avoid

  • Not verifying that correlation IDs appear in error response bodies (not just headers)
  • Assuming the client must always provide the ID (server should generate if missing)
  • Not checking that downstream services actually propagate the ID (integration gap)
  • Confusing correlation ID with session ID or request ID (different scopes)

Follow-up Questions

  • How do correlation IDs relate to OpenTelemetry trace IDs?
  • What happens if a service drops the correlation ID mid-chain?
  • How would you test correlation ID propagation through async message queues?

Q4How do you test a timeout followed by retry? #

Objective

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:

  1. Use WireMock or a mock server to introduce artificial delays
  2. Verify the client retries with correct backoff intervals
  3. Confirm that the final response is correct after recovery
  4. Validate that retries don't cause duplicate operations
  5. Check circuit breaker activation after max retries
// WireMock + REST Assured — Testing timeout and retry
@Test
public void testTimeout_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 succeed
    long startTime = System.currentTimeMillis();

    Response response = given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/inventory/item/99")
    .then()
        .statusCode(200)
        .extract().response();

    long elapsed = 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")));
}

@Test
public void testTimeout_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"));
}
# curl — Testing with explicit timeout
curl -X GET https://api.example.com/v1/inventory/item/99 \
  -H "Authorization: Bearer token" \
  --connect-timeout 3 \
  --max-time 5 \
  -w "\nTime: %{time_total}s\nHTTP Code: %{http_code}\n"

Expected Retry Pattern:

Attempt 1: t=0s     → Timeout at 3s
Attempt 2: t=4s     → Timeout at 7s  (1s backoff)
Attempt 3: t=9s     → Timeout at 12s (2s backoff)
Attempt 4: t=13s    → Success or 503 (4s backoff, max retries)

Common Mistakes to Avoid

  • Not verifying the backoff intervals (just checking retries happened)
  • Forgetting to test the "all retries exhausted" scenario
  • Not checking for duplicate side effects (e.g., double charges after retry)
  • Not testing with jitter (real backoff includes randomization)

Follow-up Questions

  • How does exponential backoff with jitter prevent thundering herd?
  • What is the difference between connection timeout and read timeout?
  • How do you test retry behavior in message queue consumers?

Q5How do you test duplicate webhooks? #

Objective

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:

  1. Send the same webhook payload twice with the same event ID
  2. Verify the side effect occurs only once
  3. Verify the second delivery returns 200 (acknowledged) without re-processing
  4. Test with slight variations in delivery timing (immediate vs delayed duplicate)
  5. Validate deduplication storage (Redis/DB) is correctly populated
// REST Assured — Testing duplicate webhook handling
@Test
public void testDuplicateWebhook_processedOnlyOnce() {
    String webhookPayload = """
        {
            "event_id": "evt_abc123",
            "type": "payment.completed",
            "data": {
                "payment_id": "pay_789",
                "amount": 5000,
                "currency": "USD"
            },
            "timestamp": "2026-07-15T10:00:00Z"
        }
    """;
    String signature = computeHmacSignature(webhookPayload, WEBHOOK_SECRET);

    // First delivery
    given()
        .header("Content-Type", "application/json")
        .header("X-Webhook-Signature", signature)
        .body(webhookPayload)
    .when()
        .post("/webhooks/payments")
    .then()
        .statusCode(200)
        .body("processed", equalTo(true));

    // Second delivery — same event_id
    given()
        .header("Content-Type", "application/json")
        .header("X-Webhook-Signature", signature)
        .body(webhookPayload)
    .when()
        .post("/webhooks/payments")
    .then()
        .statusCode(200)
        .body("processed", equalTo(false))
        .body("message", equalTo("Event already processed"));

    // Verify side effect happened only once
    Response orders = given()
        .header("Authorization", "Bearer admin_token")
    .when()
        .get("/api/v1/payments/pay_789/fulfillments")
    .then()
        .extract().response();

    assertEquals(1, orders.jsonPath().getList("fulfillments").size());
}

@Test
public void testDuplicateWebhook_concurrentDelivery() throws Exception {
    String webhookPayload = """
        {
            "event_id": "evt_concurrent_001",
            "type": "order.created",
            "data": {"order_id": "ord_555"}
        }
    """;
    String signature = computeHmacSignature(webhookPayload, WEBHOOK_SECRET);

    ExecutorService executor = Executors.newFixedThreadPool(3);
    List<Future<Integer>> futures = new ArrayList<>();

    for (int i = 0; i < 3; i++) {
        futures.add(executor.submit(() -> given()
            .header("Content-Type", "application/json")
            .header("X-Webhook-Signature", signature)
            .body(webhookPayload)
        .when()
            .post("/webhooks/orders")
        .then()
            .extract().statusCode()));
    }

    List<Integer> statuses = futures.stream()
        .map(f -> { try { return f.get(); } catch (Exception e) { return 500; } })
        .collect(Collectors.toList());

    assertTrue(statuses.stream().allMatch(s -> s == 200),
        "All deliveries should be acknowledged");
}
# curl — Simulating duplicate webhook delivery
PAYLOAD='{"event_id":"evt_abc123","type":"payment.completed","data":{"payment_id":"pay_789","amount":5000}}'
SIGNATURE=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "whsec_secret123" | awk '{print $2}')

# First delivery
curl -X POST https://myapp.com/webhooks/payments \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Signature: sha256=$SIGNATURE" \
  -d "$PAYLOAD"

# Duplicate delivery
curl -X POST https://myapp.com/webhooks/payments \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Signature: sha256=$SIGNATURE" \
  -d "$PAYLOAD"

Common Mistakes to Avoid

  • Only testing sequential duplicates (not concurrent ones)
  • Not verifying the deduplication window/TTL
  • Assuming the webhook provider always sends identical payloads for duplicates
  • Not testing what happens when the deduplication store (Redis) is unavailable

Follow-up Questions

  • How long should you retain event IDs for deduplication?
  • What data store is best for deduplication (Redis vs database)?
  • How do you handle webhook redelivery after a consumer deployment?

Q6How do you validate a JSON contract? #

Objective

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:

  1. Schema validation — Structure, types, required fields
  2. Semantic validation — Value ranges, enums, patterns
  3. Consumer-driven contracts — Pact/Spring Cloud Contract
// REST Assured + JSON Schema Validator
@Test
public void testResponseMatchesJsonSchema() {
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/users/123")
    .then()
        .statusCode(200)
        .body(matchesJsonSchemaInClasspath("schemas/user-response.json"));
}

// Inline structural assertions
@Test
public void testUserResponseContract() {
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/users/123")
    .then()
        .statusCode(200)
        .body("id", notNullValue())
        .body("id", instanceOf(Integer.class))
        .body("email", matchesPattern("^[\\w.]+@[\\w.]+\\.[a-z]{2,}$"))
        .body("role", isIn(Arrays.asList("admin", "user", "moderator")))
        .body("createdAt", matchesPattern("\\d{4}-\\d{2}-\\d{2}T.*Z"))
        .body("address.zipCode", matchesPattern("\\d{5}(-\\d{4})?"))
        .body("$", not(hasKey("password")))
        .body("$", not(hasKey("ssn")));
}

JSON Schema Example (schemas/user-response.json):

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "required": ["id", "email", "name", "role", "createdAt"],
  "properties": {
    "id": { "type": "integer", "minimum": 1 },
    "email": { "type": "string", "format": "email" },
    "name": { "type": "string", "minLength": 1, "maxLength": 100 },
    "role": { "type": "string", "enum": ["admin", "user", "moderator"] },
    "createdAt": { "type": "string", "format": "date-time" },
    "address": {
      "type": "object",
      "properties": {
        "street": { "type": "string" },
        "city": { "type": "string" },
        "zipCode": { "type": "string", "pattern": "^\\d{5}(-\\d{4})?$" }
      }
    }
  },
  "additionalProperties": false
}
# curl + jq — Quick contract validation
curl -s https://api.example.com/v1/users/123 \
  -H "Authorization: Bearer token" | \
  jq 'keys' 
# Verify expected fields are present

# Using ajv-cli for schema validation
curl -s https://api.example.com/v1/users/123 \
  -H "Authorization: Bearer token" > response.json
ajv validate -s schemas/user-response.json -d response.json

Postman Contract Test:

// Postman test script
const schema = {
    type: "object",
    required: ["id", "email", "name"],
    properties: {
        id: { type: "number" },
        email: { type: "string", format: "email" },
        name: { type: "string" }
    }
};

pm.test("Response matches schema", function() {
    pm.response.to.have.jsonSchema(schema);
});

pm.test("No extra fields exposed", function() {
    const allowed = ["id", "email", "name", "role", "createdAt", "address"];
    const keys = Object.keys(pm.response.json());
    keys.forEach(k => pm.expect(allowed).to.include(k));
});

Common Mistakes to Avoid

  • Only validating happy-path responses (error responses need schema validation too)
  • Not using additionalProperties: false to catch unexpected field exposure
  • Testing schema only in unit tests, not in integration/E2E environments
  • Not versioning schemas alongside the API

Follow-up Questions

  • How do you handle nullable fields in JSON Schema?
  • What is the difference between JSON Schema validation and Pact contract testing?
  • How do you detect breaking changes in a CI pipeline?

Q7How do you test pagination? #

Objective

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.

Key Test Scenarios:

  1. First page returns correct count and metadata
  2. Last page handles partial results
  3. Page beyond data returns empty array (not error)
  4. Total count accuracy
  5. No duplicate or missing records across pages
  6. Consistency during concurrent writes
// REST Assured — Comprehensive pagination testing
@Test
public void testPagination_firstPage() {
    given()
        .header("Authorization", "Bearer token")
        .queryParam("page", 1)
        .queryParam("pageSize", 10)
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(200)
        .body("data.size()", equalTo(10))
        .body("meta.page", equalTo(1))
        .body("meta.pageSize", equalTo(10))
        .body("meta.totalCount", greaterThan(0))
        .body("meta.totalPages", greaterThan(0))
        .body("links.next", notNullValue())
        .body("links.prev", nullValue());
}

@Test
public void testPagination_lastPage() {
    // First get total count
    int totalCount = given()
        .queryParam("page", 1).queryParam("pageSize", 10)
    .when()
        .get("/api/v1/products")
    .then()
        .extract().jsonPath().getInt("meta.totalCount");

    int lastPage = (int) Math.ceil(totalCount / 10.0);

    given()
        .queryParam("page", lastPage)
        .queryParam("pageSize", 10)
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(200)
        .body("data.size()", lessThanOrEqualTo(10))
        .body("links.next", nullValue())
        .body("links.prev", notNullValue());
}

@Test
public void testPagination_beyondLastPage_returnsEmpty() {
    given()
        .queryParam("page", 99999)
        .queryParam("pageSize", 10)
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(200)
        .body("data.size()", equalTo(0))
        .body("meta.page", equalTo(99999));
}

@Test
public void testPagination_noDuplicatesAcrossPages() {
    Set<Integer> allIds = new HashSet<>();
    int page = 1;
    boolean hasMore = true;

    while (hasMore) {
        Response resp = given()
            .queryParam("page", page)
            .queryParam("pageSize", 50)
        .when()
            .get("/api/v1/products")
        .then()
            .statusCode(200)
            .extract().response();

        List<Integer> ids = resp.jsonPath().getList("data.id");
        for (Integer id : ids) {
            assertFalse(allIds.contains(id), "Duplicate ID found: " + id);
            allIds.add(id);
        }

        hasMore = resp.jsonPath().getString("links.next") != null;
        page++;
    }
}

@Test
public void testPagination_invalidPageSize_returns400() {
    given()
        .queryParam("page", 1)
        .queryParam("pageSize", 1000) // Exceeds max allowed
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(400)
        .body("error.message", containsString("pageSize"));
}
# curl — Pagination testing
# First page
curl -s "https://api.example.com/v1/products?page=1&pageSize=10" \
  -H "Authorization: Bearer token" | jq '.meta'

# Cursor-based pagination
curl -s "https://api.example.com/v1/products?cursor=eyJpZCI6MTB9&limit=10" \
  -H "Authorization: Bearer token" | jq '.meta.nextCursor'

Response Structure:

{
  "data": [ {"id": 1, "name": "Product A"}, {"id": 2, "name": "Product B"} ],
  "meta": {
    "page": 1,
    "pageSize": 10,
    "totalCount": 95,
    "totalPages": 10
  },
  "links": {
    "self": "/api/v1/products?page=1&pageSize=10",
    "next": "/api/v1/products?page=2&pageSize=10",
    "prev": null,
    "first": "/api/v1/products?page=1&pageSize=10",
    "last": "/api/v1/products?page=10&pageSize=10"
  }
}

Common Mistakes to Avoid

  • Not testing with exactly totalCount % pageSize == 0 (last page full scenario)
  • Ignoring sort stability across pages (same sort order may shuffle without tiebreaker)
  • Not testing negative page numbers or zero
  • Forgetting performance: paginating 1M records with OFFSET is O(n)

Follow-up Questions

  • What are the pros and cons of cursor-based vs offset-based pagination?
  • How do you handle pagination consistency when records are added/deleted between page fetches?
  • How would you performance-test deep pagination (page 10000)?

Q8How do you test sorting and filtering? #

Objective

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
  • Combinations: multiple filters + sort + pagination
  • Edge cases: empty results, special characters, null fields
// REST Assured — Sorting and filtering tests
@Test
public void testSorting_ascendingByPrice() {
    List<Float> prices = given()
        .queryParam("sort", "price")
        .queryParam("order", "asc")
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(200)
        .extract().jsonPath().getList("data.price", Float.class);

    List<Float> sorted = new ArrayList<>(prices);
    Collections.sort(sorted);
    assertEquals(sorted, prices, "Prices should be in ascending order");
}

@Test
public void testSorting_descendingByCreatedDate() {
    List<String> dates = given()
        .queryParam("sort", "createdAt")
        .queryParam("order", "desc")
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(200)
        .extract().jsonPath().getList("data.createdAt", String.class);

    for (int i = 0; i < dates.size() - 1; i++) {
        assertTrue(dates.get(i).compareTo(dates.get(i + 1)) >= 0,
            "Dates should be in descending order");
    }
}

@Test
public void testFiltering_byStatus() {
    List<String> statuses = given()
        .queryParam("status", "active")
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(200)
        .extract().jsonPath().getList("data.status", String.class);

    assertTrue(statuses.stream().allMatch(s -> s.equals("active")),
        "All returned products should be active");
}

@Test
public void testFiltering_byPriceRange() {
    List<Float> prices = given()
        .queryParam("minPrice", 10.0)
        .queryParam("maxPrice", 50.0)
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(200)
        .extract().jsonPath().getList("data.price", Float.class);

    assertTrue(prices.stream().allMatch(p -> p >= 10.0 && p <= 50.0),
        "All prices should be within range");
}

@Test
public void testFiltering_invalidField_returns400() {
    given()
        .queryParam("sort", "nonexistent_field")
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(400)
        .body("error.message", containsString("Invalid sort field"));
}

@Test
public void testFiltering_sqlInjectionAttempt_returns400() {
    given()
        .queryParam("name", "'; DROP TABLE products; --")
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(anyOf(is(200), is(400)))
        .body("data.size()", equalTo(0)); // No results, no injection
}

@Test
public void testFiltering_combinedWithSortAndPagination() {
    given()
        .queryParam("category", "electronics")
        .queryParam("minPrice", 100)
        .queryParam("sort", "price")
        .queryParam("order", "asc")
        .queryParam("page", 1)
        .queryParam("pageSize", 5)
    .when()
        .get("/api/v1/products")
    .then()
        .statusCode(200)
        .body("data.size()", lessThanOrEqualTo(5))
        .body("data.every { it.category == 'electronics' }", equalTo(true))
        .body("meta.totalCount", greaterThanOrEqualTo(0));
}
# curl — Sorting and filtering
curl -s "https://api.example.com/v1/products?sort=price&order=asc&category=electronics&minPrice=10" \
  -H "Authorization: Bearer token" | jq '.data[] | {name, price, category}'

# Testing special characters in filters
curl -s "https://api.example.com/v1/products?name=O%27Reilly" \
  -H "Authorization: Bearer token"

Common Mistakes to Avoid

  • Not testing sort stability (records with same sort value should have consistent ordering)
  • Only testing single-field sorting (multi-field sort like sort=price,name is common)
  • Ignoring case sensitivity in text filters
  • Not testing filter combinations that return zero results

Follow-up Questions

  • How do you test sort stability for fields with duplicate values?
  • What is the performance impact of sorting on non-indexed fields?
  • How do you document which fields are sortable/filterable?

Q9How do you test rate limiting? #

Objective

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:

  1. Requests within limit succeed
  2. Requests exceeding limit return 429 Too Many Requests
  3. Rate limit headers are present and accurate
  4. Quota resets after the window expires
  5. Different rate limits for different tiers/endpoints
// REST Assured — Rate limiting tests
@Test
public void testRateLimit_withinQuota_succeeds() {
    Response response = given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/users/me")
    .then()
        .statusCode(200)
        .header("X-RateLimit-Limit", notNullValue())
        .header("X-RateLimit-Remaining", notNullValue())
        .header("X-RateLimit-Reset", notNullValue())
        .extract().response();

    int limit = Integer.parseInt(response.getHeader("X-RateLimit-Limit"));
    int remaining = Integer.parseInt(response.getHeader("X-RateLimit-Remaining"));
    assertTrue(remaining < limit);
    assertTrue(remaining >= 0);
}

@Test
public void testRateLimit_exceedsQuota_returns429() {
    int rateLimit = 100; // Known limit for test tier

    // Exhaust the quota
    for (int i = 0; i < rateLimit; i++) {
        given()
            .header("Authorization", "Bearer test_token")
        .when()
            .get("/api/v1/users/me")
        .then()
            .statusCode(200);
    }

    // Next request should be rate limited
    given()
        .header("Authorization", "Bearer test_token")
    .when()
        .get("/api/v1/users/me")
    .then()
        .statusCode(429)
        .header("Retry-After", notNullValue())
        .body("error.code", equalTo("rate_limit_exceeded"))
        .body("error.message", containsString("Too many requests"));
}

@Test
public void testRateLimit_quotaResetsAfterWindow() throws Exception {
    int rateLimit = 10; // Low limit for test

    // Exhaust quota
    for (int i = 0; i < rateLimit + 1; i++) {
        given().header("Authorization", "Bearer token")
            .when().get("/api/v1/test-endpoint");
    }

    // Get reset time from header
    Response limited = given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/test-endpoint")
    .then()
        .statusCode(429)
        .extract().response();

    long resetEpoch = Long.parseLong(limited.getHeader("X-RateLimit-Reset"));
    long waitMs = (resetEpoch * 1000) - System.currentTimeMillis() + 1000;

    Thread.sleep(waitMs); // Wait for window to reset

    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/test-endpoint")
    .then()
        .statusCode(200);
}

@Test
public void testRateLimit_differentEndpointsDifferentLimits() {
    // Read endpoint — higher limit
    given().header("Authorization", "Bearer token")
        .when().get("/api/v1/products")
        .then().header("X-RateLimit-Limit", equalTo("1000"));

    // Write endpoint — lower limit
    given().header("Authorization", "Bearer token")
        .header("Content-Type", "application/json")
        .body("{\"name\": \"test\"}")
        .when().post("/api/v1/products")
        .then().header("X-RateLimit-Limit", equalTo("100"));
}
# curl — Rapid fire to test rate limiting
for i in $(seq 1 105); do
  STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
    -H "Authorization: Bearer token" \
    https://api.example.com/v1/users/me)
  echo "Request $i: HTTP $STATUS"
  if [ "$STATUS" = "429" ]; then
    echo "Rate limited at request $i"
    curl -s -I https://api.example.com/v1/users/me \
      -H "Authorization: Bearer token" | grep -i "retry-after\|x-ratelimit"
    break
  fi
done

Response Headers:

HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1752577200
Retry-After: 45
Content-Type: application/json

{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Try again in 45 seconds."
  }
}

Common Mistakes to Avoid

  • Only testing from a single client (rate limits may be per-IP, per-token, or per-user)
  • Not verifying the Retry-After header value is accurate
  • Assuming rate limits are globally consistent (distributed rate limiters may have race conditions)
  • Not testing that rate limit 429 responses do NOT count against the quota

Follow-up Questions

  • What is the difference between sliding window and fixed window rate limiting?
  • How do you test rate limiting in a distributed (multi-node) API deployment?
  • How should rate limits differ between API tiers (free vs premium)?

Q10How do you test authentication versus authorization? #

Objective

Clearly distinguish between authentication (who you are) and authorization (what you can do) and show testing strategies for both.

Interview Answer

Authentication verifies identity — "Are you who you claim to be?" Authorization verifies permissions — "Are you allowed to do this?"

Testing must validate both dimensions independently: a valid user (authenticated) may still be denied access (unauthorized) to certain resources.

Test Matrix:

Scenario Auth Token Resource Expected
No token Missing Any 401
Invalid token Expired/malformed Any 401
Valid token, no permission Valid user Admin resource 403
Valid token, has permission Admin user Admin resource 200
Valid token, own resource User A User A's data 200
Valid token, other's resource User A User B's data 403
// REST Assured — Authentication tests
@Test
public void testAuthentication_noToken_returns401() {
    given()
        // No Authorization header
    .when()
        .get("/api/v1/users/me")
    .then()
        .statusCode(401)
        .body("error.code", equalTo("unauthorized"))
        .body("error.message", equalTo("Authentication required"));
}

@Test
public void testAuthentication_expiredToken_returns401() {
    given()
        .header("Authorization", "Bearer expired_token_xyz")
    .when()
        .get("/api/v1/users/me")
    .then()
        .statusCode(401)
        .body("error.code", equalTo("token_expired"))
        .header("WWW-Authenticate", containsString("Bearer"));
}

@Test
public void testAuthentication_malformedToken_returns401() {
    given()
        .header("Authorization", "Bearer not.a.valid.jwt")
    .when()
        .get("/api/v1/users/me")
    .then()
        .statusCode(401)
        .body("error.code", equalTo("invalid_token"));
}

// Authorization tests
@Test
public void testAuthorization_regularUserAccessesAdminEndpoint_returns403() {
    given()
        .header("Authorization", "Bearer " + regularUserToken)
    .when()
        .get("/api/v1/admin/users")
    .then()
        .statusCode(403)
        .body("error.code", equalTo("forbidden"))
        .body("error.message", containsString("insufficient permissions"));
}

@Test
public void testAuthorization_userAccessesOwnResource_returns200() {
    given()
        .header("Authorization", "Bearer " + userAToken)
    .when()
        .get("/api/v1/users/" + userAId + "/profile")
    .then()
        .statusCode(200)
        .body("id", equalTo(userAId));
}

@Test
public void testAuthorization_userAccessesOtherUserResource_returns403() {
    given()
        .header("Authorization", "Bearer " + userAToken)
    .when()
        .get("/api/v1/users/" + userBId + "/profile")
    .then()
        .statusCode(403)
        .body("error.code", equalTo("forbidden"));
}

@Test
public void testAuthorization_roleEscalation_prevented() {
    // User tries to update their own role to admin
    given()
        .header("Authorization", "Bearer " + regularUserToken)
        .header("Content-Type", "application/json")
        .body("{\"role\": \"admin\"}")
    .when()
        .patch("/api/v1/users/me")
    .then()
        .statusCode(403);
}
# curl — Testing auth scenarios
# No token
curl -s https://api.example.com/v1/users/me -w "\n%{http_code}"

# Invalid token
curl -s https://api.example.com/v1/users/me \
  -H "Authorization: Bearer invalid" -w "\n%{http_code}"

# Valid user, forbidden resource
curl -s https://api.example.com/v1/admin/users \
  -H "Authorization: Bearer regular_user_token" -w "\n%{http_code}"

Common Mistakes to Avoid

  • Confusing 401 and 403 (401 = "I don't know who you are", 403 = "I know who you are but you can't")
  • Not testing horizontal authorization (User A accessing User B's resources)
  • Only testing happy-path authorization (admin can access admin resources)
  • Not testing IDOR (Insecure Direct Object Reference) vulnerabilities

Follow-up Questions

  • How do you test RBAC (Role-Based Access Control) at scale with many roles?
  • What is IDOR and how do you systematically test for it?
  • How do you handle authorization testing in a microservices architecture where each service enforces its own policies?

Q11How do you test token expiry and refresh? #

Objective

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
@Test
public void testAccessToken_expiredToken_returns401() {
    // Generate a token that expired 1 minute ago
    String expiredToken = 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"));
}

@Test
public void testRefreshToken_validRefresh_returnsNewTokens() {
    // Login to get initial tokens
    Response loginResp = given()
        .header("Content-Type", "application/json")
        .body("{\"email\": \"user@test.com\", \"password\": \"password123\"}")
    .when()
        .post("/api/v1/auth/login")
    .then()
        .statusCode(200)
        .extract().response();

    String refreshToken = loginResp.jsonPath().getString("refreshToken");

    // Use refresh token to get new access token
    Response refreshResp = 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 work
    String newAccessToken = refreshResp.jsonPath().getString("accessToken");
    given()
        .header("Authorization", "Bearer " + newAccessToken)
    .when()
        .get("/api/v1/users/me")
    .then()
        .statusCode(200);
}

@Test
public void testRefreshToken_rotationInvalidatesOldToken() {
    // Get initial tokens
    String refreshToken = loginAndGetRefreshToken();

    // Refresh once — get new refresh token
    Response refreshResp = given()
        .header("Content-Type", "application/json")
        .body("{\"refreshToken\": \"" + refreshToken + "\"}")
    .when()
        .post("/api/v1/auth/refresh")
    .then()
        .statusCode(200)
        .extract().response();

    String newRefreshToken = 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"));
}

@Test
public void testRefreshToken_reuseDetection_revokesFamily() {
    // This tests refresh token reuse detection (security feature)
    String refreshToken = loginAndGetRefreshToken();

    // First refresh — legitimate
    Response resp1 = given()
        .body("{\"refreshToken\": \"" + refreshToken + "\"}")
        .header("Content-Type", "application/json")
    .when()
        .post("/api/v1/auth/refresh")
    .then()
        .statusCode(200)
        .extract().response();

    String newRefreshToken = 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);
}

@Test
public void testRefreshToken_concurrentRefresh_onlyOneSucceeds() throws Exception {
    String refreshToken = loginAndGetRefreshToken();
    ExecutorService executor = Executors.newFixedThreadPool(3);

    List<Future<Integer>> futures = new ArrayList<>();
    for (int i = 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) { return 500; } })
        .collect(Collectors.toList());

    long successCount = statuses.stream().filter(s -> s == 200).count();
    assertTrue(successCount <= 1, "At most one concurrent refresh should succeed");
}
# curl — Token refresh flow
# Login
TOKENS=$(curl -s -X POST https://api.example.com/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "user@test.com", "password": "pass123"}')

REFRESH_TOKEN=$(echo $TOKENS | jq -r '.refreshToken')

# Refresh
curl -X POST https://api.example.com/v1/auth/refresh \
  -H "Content-Type: application/json" \
  -d "{\"refreshToken\": \"$REFRESH_TOKEN\"}"

Common Mistakes to Avoid

  • Not testing the window between access token expiry and refresh (race condition)
  • Forgetting to test refresh token rotation (old token should be invalidated)
  • Not testing token reuse detection (security-critical)
  • Only testing single-user scenarios (not concurrent sessions)

Follow-up Questions

  • What is refresh token rotation and why is it important for security?
  • How do you handle token refresh in a mobile app with poor connectivity?
  • What is the difference between opaque and JWT refresh tokens?

Q12How do you test a 202 asynchronous response? #

Objective

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: {...}}
// REST Assured — Testing 202 async flow
@Test
public void testAsyncResponse_fullLifecycle() {
    // Submit async job
    Response submitResp = given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body("{\"reportType\": \"monthly\", \"month\": \"2026-06\"}")
    .when()
        .post("/api/v1/reports/generate")
    .then()
        .statusCode(202)
        .header("Location", matchesPattern("/api/v1/reports/jobs/[a-f0-9-]+"))
        .body("jobId", notNullValue())
        .body("status", equalTo("accepted"))
        .body("estimatedCompletionTime", notNullValue())
        .extract().response();

    String jobUrl = submitResp.getHeader("Location");
    String jobId = submitResp.jsonPath().getString("jobId");

    // Poll until complete (with timeout)
    String status = "processing";
    Response statusResp = null;
    int maxAttempts = 30;
    int attempt = 0;

    while (!status.equals("completed") && !status.equals("failed") && attempt < maxAttempts) {
        Thread.sleep(2000); // Poll every 2 seconds
        statusResp = given()
            .header("Authorization", "Bearer token")
        .when()
            .get(jobUrl)
        .then()
            .statusCode(200)
            .extract().response();

        status = statusResp.jsonPath().getString("status");
        attempt++;
    }

    assertEquals("completed", status, "Job should complete within timeout");
    assertNotNull(statusResp.jsonPath().getString("result.downloadUrl"));
}

@Test
public void testAsyncResponse_returns202WithCorrectHeaders() {
    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body("{\"reportType\": \"monthly\", \"month\": \"2026-06\"}")
    .when()
        .post("/api/v1/reports/generate")
    .then()
        .statusCode(202)
        .header("Location", notNullValue())
        .header("Retry-After", notNullValue())
        .body("jobId", notNullValue())
        .body("status", equalTo("accepted"))
        .body("_links.status", notNullValue())
        .body("_links.cancel", notNullValue());
}

@Test
public void testAsyncResponse_cancelPendingJob() {
    // Submit job
    String jobId = given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body("{\"reportType\": \"large_export\"}")
    .when()
        .post("/api/v1/reports/generate")
    .then()
        .statusCode(202)
        .extract().jsonPath().getString("jobId");

    // Cancel the job
    given()
        .header("Authorization", "Bearer token")
    .when()
        .delete("/api/v1/reports/jobs/" + jobId)
    .then()
        .statusCode(200)
        .body("status", equalTo("cancelled"));

    // Verify job status is cancelled
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/reports/jobs/" + jobId)
    .then()
        .statusCode(200)
        .body("status", equalTo("cancelled"));
}

@Test
public void testAsyncResponse_failedJob_returnsErrorDetails() {
    // Submit job that will fail
    String jobId = given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body("{\"reportType\": \"monthly\", \"month\": \"invalid-date\"}")
    .when()
        .post("/api/v1/reports/generate")
    .then()
        .statusCode(202)
        .extract().jsonPath().getString("jobId");

    // Poll until failed
    await().atMost(30, TimeUnit.SECONDS).pollInterval(2, TimeUnit.SECONDS).until(() -> {
        String s = given()
            .header("Authorization", "Bearer token")
        .when()
            .get("/api/v1/reports/jobs/" + jobId)
        .then()
            .extract().jsonPath().getString("status");
        return s.equals("failed");
    });

    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/reports/jobs/" + jobId)
    .then()
        .body("status", equalTo("failed"))
        .body("error.code", notNullValue())
        .body("error.message", notNullValue())
        .body("error.retryable", isA(Boolean.class));
}
# curl — Async job lifecycle
# Submit
JOB=$(curl -s -X POST https://api.example.com/v1/reports/generate \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer token" \
  -d '{"reportType": "monthly", "month": "2026-06"}')

JOB_ID=$(echo $JOB | jq -r '.jobId')
echo "Job submitted: $JOB_ID"

# Poll
while true; do
  STATUS=$(curl -s https://api.example.com/v1/reports/jobs/$JOB_ID \
    -H "Authorization: Bearer token" | jq -r '.status')
  echo "Status: $STATUS"
  [ "$STATUS" = "completed" ] || [ "$STATUS" = "failed" ] && break
  sleep 2
done

Common Mistakes to Avoid

  • Not testing the polling interval (Retry-After header) compliance
  • Forgetting to test job timeout (what if processing never completes?)
  • Not testing concurrent submissions of the same job
  • Not testing what happens when you poll a non-existent job ID

Follow-up Questions

  • How do you choose between polling and webhooks for async completion?
  • How would you test idempotency of async job submission?
  • What observability do you need for async job processing?

Q13How do you test eventual consistency? #

Objective

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:

  1. Write data to the primary service
  2. Poll the read replica/dependent service with a bounded timeout
  3. Assert consistency is achieved within the SLA
  4. Test that stale reads don't cause incorrect behavior
// REST Assured — Eventual consistency testing
@Test
public void testEventualConsistency_orderCreationPropagates() {
    // Create order in order service
    String orderId = 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));
        });
}

@Test
public void testEventualConsistency_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 time
    long start = System.currentTimeMillis();
    boolean consistent = false;

    while (System.currentTimeMillis() - start < 5000) { // 5s SLA
        Response readResp = 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;
            long propagationTime = System.currentTimeMillis() - start;
            System.out.println("Consistency achieved in " + propagationTime + "ms");
            break;
        }
        Thread.sleep(200);
    }

    assertTrue(consistent, "Data should be consistent within 5s SLA");
}

@Test
public void testEventualConsistency_deleteEventuallyPropagates() {
    // Create then immediately delete
    String id = 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);
        });
}
# curl — Manual eventual consistency check
# Write
curl -X POST https://api.example.com/v1/orders \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer token" \
  -d '{"product": "widget", "quantity": 5}'

# Poll read replica
for i in $(seq 1 20); do
  RESULT=$(curl -s "https://api.example.com/v1/search/orders?q=widget" \
    -H "Authorization: Bearer token" | jq '.results | length')
  echo "Attempt $i: $RESULT results"
  [ "$RESULT" -gt "0" ] && echo "Consistent!" && break
  sleep 0.5
done

Common Mistakes to Avoid

  • Using Thread.sleep(5000) instead of polling (brittle and slow)
  • Setting SLA thresholds too tight (flaky tests) or too loose (hiding real bugs)
  • Not testing what happens when consistency is never achieved (service down)
  • Confusing eventual consistency bugs with actual data loss

Follow-up Questions

  • How do you set appropriate consistency SLA thresholds for tests?
  • How does read-your-own-writes consistency differ from eventual consistency?
  • How do you test consistency in CQRS (Command Query Responsibility Segregation) architectures?

Q14How do you test an API version change? #

Objective

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.

Versioning Strategies to Test:

  • URL path: /v1/users vs /v2/users
  • Header: Accept: application/vnd.api+json; version=2
  • Query parameter: /users?version=2
// REST Assured — API version testing
@Test
public void testVersionRouting_v1ReturnsV1Schema() {
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/users/123")
    .then()
        .statusCode(200)
        .body("$", hasKey("firstName"))
        .body("$", hasKey("lastName"))
        .body("$", not(hasKey("fullName"))); // v1 has separate name fields
}

@Test
public void testVersionRouting_v2ReturnsV2Schema() {
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v2/users/123")
    .then()
        .statusCode(200)
        .body("$", hasKey("fullName"))       // v2 has combined name
        .body("$", not(hasKey("firstName"))) // v2 removed separate fields
        .body("$", hasKey("metadata"));      // v2 added metadata
}

@Test
public void testVersionRouting_headerBasedVersioning() {
    // Version 1
    given()
        .header("Authorization", "Bearer token")
        .header("Accept", "application/vnd.myapi.v1+json")
    .when()
        .get("/api/users/123")
    .then()
        .statusCode(200)
        .body("$", hasKey("firstName"));

    // Version 2
    given()
        .header("Authorization", "Bearer token")
        .header("Accept", "application/vnd.myapi.v2+json")
    .when()
        .get("/api/users/123")
    .then()
        .statusCode(200)
        .body("$", hasKey("fullName"));
}

@Test
public void testVersionRouting_deprecationHeader() {
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/users/123")
    .then()
        .statusCode(200)
        .header("Deprecation", notNullValue())
        .header("Sunset", notNullValue()) // RFC 8594
        .header("Link", containsString("v2")); // Link to newer version
}

@Test
public void testVersionRouting_unsupportedVersion_returns404or406() {
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v99/users/123")
    .then()
        .statusCode(404);
}

@Test
public void testVersionRouting_noVersionDefaultsToLatest() {
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/users/123") // No version specified
    .then()
        .statusCode(200)
        .body("$", hasKey("fullName")); // Returns latest (v2) schema
}
# curl — Version comparison
echo "=== V1 Response ==="
curl -s https://api.example.com/v1/users/123 \
  -H "Authorization: Bearer token" | jq 'keys'

echo "=== V2 Response ==="
curl -s https://api.example.com/v2/users/123 \
  -H "Authorization: Bearer token" | jq 'keys'

# Check deprecation headers
curl -sI https://api.example.com/v1/users/123 \
  -H "Authorization: Bearer token" | grep -i "deprecation\|sunset\|link"

Common Mistakes to Avoid

  • Not testing that v1 continues to work after v2 deployment
  • Forgetting to test deprecation/sunset headers on old versions
  • Not testing the default version behavior (what happens with no version specified)
  • Not validating that error responses also respect versioning

Follow-up Questions

  • How do you decide between URL, header, and query parameter versioning?
  • What is the Sunset header (RFC 8594) and how do you test compliance?
  • How do you communicate version deprecation to API consumers?

Q15How do you test backward compatibility? #

Objective

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
@Test
public void testBackwardCompatibility_newFieldsDoNotBreakOldConsumers() {
    // Simulate old consumer that only reads specific fields
    Response response = 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
}

@Test
public void testBackwardCompatibility_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
}

@Test
public void testBackwardCompatibility_responseFieldsNotRemoved() {
    // Record baseline fields from v1 documentation/contract
    Set<String> requiredV1Fields = Set.of("id", "email", "name", "role", "createdAt");

    Response response = 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(", ")));
}

@Test
public void testBackwardCompatibility_fieldTypesUnchanged() {
    Response response = 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")
public RequestResponsePact userDetailsPact(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(new PactDslJsonBody()
            .integerType("id", 123)
            .stringType("email", "user@test.com")
            .stringType("name", "Test User")
            .stringType("role", "user"))
        .toPact();
}

@Test
@PactVerification("UserService")
public void testPactContract_userDetails() {
    // This test verifies the provider still satisfies the consumer's expectations
    Response response = given()
        .port(mockProvider.getPort())
    .when()
        .get("/api/v1/users/123")
    .then()
        .statusCode(200)
        .extract().response();

    assertNotNull(response.jsonPath().getString("email"));
}
# curl — Compare current vs previous response
# Save baseline
curl -s https://api.example.com/v1/users/123 \
  -H "Authorization: Bearer token" | jq 'keys | sort' > baseline_keys.json

# After deployment, compare
curl -s https://api.example.com/v1/users/123 \
  -H "Authorization: Bearer token" | jq 'keys | sort' > current_keys.json

diff baseline_keys.json current_keys.json

Common Mistakes to Avoid

  • 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:

  1. Trigger an operation that should fail partway through
  2. Verify ALL database changes from the transaction are reverted
  3. Verify no orphaned records remain
  4. Test at both the API level and the database level
// REST Assured — Transaction rollback testing
@Test
public void testTransactionRollback_failedPayment_reversesOrderCreation() {
    // Get initial state
    int initialOrderCount = getOrderCount();
    double initialBalance = 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));
}

@Test
public void testTransactionRollback_partialBatchInsert() {
    // Batch insert where one record violates a constraint
    String payload = """
        {
            "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");

    int countBefore = 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));
}

@Test
public void testTransactionRollback_concurrentModification() {
    // Simulate optimistic locking failure
    Response original = given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/products/123")
    .then()
        .extract().response();

    String etag = original.getHeader("ETag");
    int originalStock = 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:

  1. Service A succeeds, Service B fails → A should compensate (rollback)
  2. Service A succeeds, Service B times out → Retry or compensate
  3. Multiple services called in parallel — some fail, some succeed
  4. Cascade failure — one failure causes upstream failures
// REST Assured + WireMock — Testing partial failure
@Test
public void testPartialFailure_paymentSucceeds_shippingFails() {
    // Mock shipping service to fail
    stubFor(post(urlEqualTo("/shipping/create"))
        .willReturn(aResponse().withStatus(503)));

    // Order creation should handle partial failure gracefully
    Response response = 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();

    String orderId = 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());
}

@Test
public void testPartialFailure_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
}

@Test
public void testPartialFailure_circuitBreakerOpens() {
    // Fail shipping service repeatedly to trip circuit breaker
    stubFor(post(urlEqualTo("/shipping/create"))
        .willReturn(aResponse().withStatus(503)));

    // Make enough calls to open the circuit
    for (int i = 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?

Q18How do you test message-queue redelivery? #

Objective

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:

  1. Same message delivered twice — processed only once
  2. Processing failure — message returns to queue for retry
  3. Poison messages — moved to dead-letter queue after max retries
  4. Out-of-order delivery — consumer handles correctly
  5. Message with expired TTL — discarded appropriately
// Testing message redelivery with embedded broker (e.g., RabbitMQ/SQS)
@Test
public void testMessageRedelivery_duplicateMessage_processedOnce() {
    String messageId = UUID.randomUUID().toString();
    String messageBody = """
        {
            "messageId": "%s",
            "type": "order.created",
            "data": {"orderId": "ord_123", "amount": 5000}
        }
    """.formatted(messageId);

    // Publish same message twice
    publishToQueue("orders.created", messageBody, messageId);
    publishToQueue("orders.created", messageBody, messageId);

    // Wait for processing
    await().atMost(10, TimeUnit.SECONDS).until(() ->
        getProcessedMessageCount(messageId) >= 1
    );

    // Verify side effect occurred only once
    given()
        .header("Authorization", "Bearer admin_token")
    .when()
        .get("/api/v1/orders/ord_123/notifications")
    .then()
        .body("notifications.size()", equalTo(1)); // Only one notification sent
}

@Test
public void testMessageRedelivery_processingFailure_retriesCorrectly() {
    // Configure consumer to fail first 2 attempts
    setConsumerFailureCount("order_processor", 2);

    String messageBody = """
        {
            "messageId": "msg_retry_test",
            "type": "order.created",
            "data": {"orderId": "ord_456"}
        }
    """;

    publishToQueue("orders.created", messageBody, "msg_retry_test");

    // Wait for successful processing (after retries)
    await().atMost(30, TimeUnit.SECONDS).until(() ->
        getMessageStatus("msg_retry_test").equals("processed")
    );

    // Verify message was attempted 3 times (2 failures + 1 success)
    assertEquals(3, getAttemptCount("msg_retry_test"));

    // Verify side effect occurred only once despite 3 attempts
    given()
        .header("Authorization", "Bearer admin_token")
    .when()
        .get("/api/v1/orders/ord_456")
    .then()
        .statusCode(200)
        .body("status", equalTo("confirmed"));
}

@Test
public void testMessageRedelivery_maxRetriesExhausted_sentToDLQ() {
    // Configure consumer to always fail
    setConsumerFailureCount("order_processor", Integer.MAX_VALUE);

    String messageBody = """
        {
            "messageId": "msg_poison",
            "type": "order.created",
            "data": {"orderId": "ord_poison"}
        }
    """;

    publishToQueue("orders.created", messageBody, "msg_poison");

    // Wait for message to land in DLQ
    await().atMost(60, TimeUnit.SECONDS).until(() ->
        getDeadLetterQueueSize("orders.created.dlq") > 0
    );

    // Verify DLQ message contains original payload + error metadata
    Message dlqMessage = readFromDeadLetterQueue("orders.created.dlq");
    assertEquals("msg_poison", dlqMessage.getMessageId());
    assertTrue(dlqMessage.getHeaders().containsKey("x-death-count"));
    assertTrue(Integer.parseInt(dlqMessage.getHeaders().get("x-death-count")) >= 3);
}

@Test
public void testMessageRedelivery_outOfOrder_handledCorrectly() {
    // Publish messages out of order
    publishToQueue("orders.status", createStatusMessage("ord_789", "shipped", 3));
    publishToQueue("orders.status", createStatusMessage("ord_789", "processing", 1));
    publishToQueue("orders.status", createStatusMessage("ord_789", "confirmed", 2));

    await().atMost(10, TimeUnit.SECONDS).until(() ->
        getOrderStatus("ord_789").equals("shipped")
    );

    // Final state should reflect highest sequence number
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/orders/ord_789")
    .then()
        .body("status", equalTo("shipped"))  // Not "confirmed" (which arrived last)
        .body("statusSequence", equalTo(3));
}
# AWS SQS — Testing redelivery
# Send message
aws sqs send-message \
  --queue-url https://sqs.us-east-1.amazonaws.com/123456789/orders-queue \
  --message-body '{"orderId": "ord_123", "type": "order.created"}' \
  --message-deduplication-id "dedup-123" \
  --message-group-id "orders"

# Check DLQ for failed messages
aws sqs receive-message \
  --queue-url https://sqs.us-east-1.amazonaws.com/123456789/orders-dlq \
  --max-number-of-messages 10

Common Mistakes to Avoid

  • Not testing idempotency at the consumer level (only testing at API level)
  • Forgetting to test the retry delay/backoff between redeliveries
  • Not verifying message ordering guarantees (FIFO vs standard queues)
  • Not testing what happens when the consumer is redeployed mid-processing

Follow-up Questions

  • How do you ensure exactly-once processing semantics?
  • What is the difference between acknowledgment modes (auto-ack vs manual-ack)?
  • How do you monitor message queue consumer lag?

Q19How do you test a dead-letter queue? #

Objective

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:

  1. Message exceeds max retry count → routed to DLQ
  2. Message TTL expires → routed to DLQ
  3. Message schema invalid → routed to DLQ immediately (no retry)
  4. DLQ message retains original headers and error context
  5. DLQ message can be replayed to original queue
  6. Alerts fire when DLQ depth exceeds threshold
// Testing Dead-Letter Queue behavior
@Test
public void testDLQ_messageRoutedAfterMaxRetries() {
    int maxRetries = 3;
    String poisonMessage = """
        {
            "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 metadata
    Message dlqMsg = 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"));
}

@Test
public void testDLQ_messageRetainsOriginalPayload() {
    String originalPayload = """
        {
            "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 integrity
    Message dlqMsg = peekDeadLetterQueue("payments.created.dlq");
    JsonNode body = objectMapper.readTree(dlqMsg.getBody());
    assertEquals("msg_payload_check", body.get("messageId").asText());
    assertEquals(5000, body.get("data").get("amount").asInt());
}

@Test
public void testDLQ_replayMessage_reprocessesSuccessfully() {
    // Place a message in DLQ manually
    String message = """
        {
            "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")
    );
}

@Test
public void testDLQ_alertTriggeredOnThreshold() {
    // Publish multiple poison messages to trigger DLQ alert
    for (int i = 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

DLQ Flow Diagram:

Source Queue → Consumer (attempt 1: fail)
            → Consumer (attempt 2: fail)  
            → Consumer (attempt 3: fail)
            → Dead-Letter Queue
                 → Alert triggered
                 → Manual investigation
                 → Fix applied
                 → Replay to Source Queue

Common Mistakes to Avoid

  • Not testing DLQ message metadata (lose context about why it failed)
  • Not testing the replay mechanism (messages stuck in DLQ forever)
  • Forgetting to test that DLQ alerts are actionable (include queue name, depth, sample message)
  • Not testing DLQ with different failure types (schema error vs timeout vs business logic)

Follow-up Questions

  • How do you design a DLQ replay strategy for production?
  • What monitoring and alerting should surround DLQs?
  • How do you handle poison messages that will always fail on replay?

Q20How do you test an external provider outage? #

Objective

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:

  1. Simulate complete outage (connection refused)
  2. Simulate degraded service (high latency, intermittent errors)
  3. Verify fallback behavior (cached data, alternative provider, queued retry)
  4. Test recovery when service comes back online
  5. Validate user-facing error messages are appropriate
// WireMock + REST Assured — Simulating provider outage
@Test
public void testExternalOutage_paymentProvider_fallbackToQueue() {
    // Simulate Stripe outage — connection refused
    stubFor(post(urlPathMatching("/v1/charges"))
        .willReturn(aResponse()
            .withFault(Fault.CONNECTION_RESET_BY_PEER)));

    Response response = given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body("""
            {
                "orderId": "ord_100",
                "amount": 5000,
                "paymentMethod": "card_valid"
            }
        """)
    .when()
        .post("/api/v1/payments/charge")
    .then()
        .statusCode(202) // Accepted for async processing
        .body("status", equalTo("queued"))
        .body("message", containsString("Payment will be processed shortly"))
        .body("estimatedProcessingTime", notNullValue())
        .extract().response();
}

@Test
public void testExternalOutage_emailProvider_doesNotBlockOrder() {
    // Simulate SendGrid outage
    stubFor(post(urlPathMatching("/v3/mail/send"))
        .willReturn(aResponse().withStatus(503)));

    // Order should still succeed — email is non-critical
    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body("{\"items\": [{\"productId\": \"prod_1\", \"quantity\": 1}]}")
    .when()
        .post("/api/v1/orders")
    .then()
        .statusCode(201)
        .body("status", equalTo("confirmed"))
        .body("notifications.email", equalTo("queued")); // Email queued for retry
}

@Test
public void testExternalOutage_highLatency_circuitBreakerTrips() {
    // Simulate high latency (10s response time)
    stubFor(get(urlPathMatching("/geocode/.*"))
        .willReturn(aResponse()
            .withFixedDelay(10000)
            .withStatus(200)));

    // Multiple requests trip the circuit breaker
    for (int i = 0; i < 5; i++) {
        given()
            .header("Authorization", "Bearer token")
            .queryParam("address", "123 Main St")
        .when()
            .get("/api/v1/locations/geocode")
        .then()
            .statusCode(anyOf(is(200), is(503)));
    }

    // Subsequent requests should fail fast (circuit open)
    long start = System.currentTimeMillis();
    given()
        .header("Authorization", "Bearer token")
        .queryParam("address", "456 Oak Ave")
    .when()
        .get("/api/v1/locations/geocode")
    .then()
        .statusCode(503)
        .body("error.code", equalTo("service_unavailable"))
        .body("error.fallback", equalTo(true));

    long elapsed = System.currentTimeMillis() - start;
    assertTrue(elapsed < 1000, "Circuit breaker should fail fast (<1s)");
}

@Test
public void testExternalOutage_recovery_processesQueuedRequests() {
    // Phase 1: Provider down — requests queued
    stubFor(post(urlPathMatching("/v1/charges"))
        .willReturn(aResponse().withStatus(503)));

    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body("{\"amount\": 1000, \"paymentMethod\": \"card_valid\"}")
    .when()
        .post("/api/v1/payments/charge")
    .then()
        .statusCode(202);

    // Phase 2: Provider recovers
    stubFor(post(urlPathMatching("/v1/charges"))
        .willReturn(aResponse()
            .withStatus(200)
            .withBody("{\"id\": \"ch_123\", \"status\": \"succeeded\"}")));

    // Wait for queued payment to be processed
    await().atMost(30, TimeUnit.SECONDS).until(() -> {
        String status = given()
            .header("Authorization", "Bearer token")
        .when()
            .get("/api/v1/payments/latest")
        .then()
            .extract().jsonPath().getString("status");
        return "succeeded".equals(status);
    });
}
# curl — Manual outage simulation with network tools
# Simulate outage by blocking external IP (requires admin access)
# iptables -A OUTPUT -d stripe-api-ip -j DROP

# Test the API behavior during outage
curl -X POST https://myapp.com/api/v1/payments/charge \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer token" \
  -d '{"amount": 5000, "paymentMethod": "card_valid"}' \
  -w "\nHTTP: %{http_code}\nTime: %{time_total}s\n"

# Check health endpoint during outage
curl -s https://myapp.com/api/v1/health | jq '.dependencies.paymentProvider'

Health Check Response During Outage:

{
  "status": "degraded",
  "dependencies": {
    "database": { "status": "healthy", "latency": "5ms" },
    "paymentProvider": { "status": "unhealthy", "lastError": "connection_timeout", "circuitBreaker": "OPEN" },
    "emailProvider": { "status": "unhealthy", "lastError": "503", "circuitBreaker": "OPEN" }
  }
}

Common Mistakes to Avoid

  • Only testing complete outage (partial degradation is more common)
  • Not testing the recovery path (system should auto-recover when provider returns)
  • Forgetting to test health check endpoints during outage
  • Not validating that user-facing error messages are friendly (not stack traces)

Follow-up Questions

  • How do you implement chaos engineering for third-party dependencies?
  • What is the difference between circuit breaker and bulkhead patterns?
  • How do you test provider SLA compliance?

Q21How do you test API error schemas? #

Objective

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)"
  }
}
// REST Assured — Error schema validation
private static final String ERROR_SCHEMA = "schemas/error-response.json";

@Test
public void testErrorSchema_400BadRequest() {
    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body("{\"email\": \"not-an-email\"}") // Invalid input
    .when()
        .post("/api/v1/users")
    .then()
        .statusCode(400)
        .body(matchesJsonSchemaInClasspath(ERROR_SCHEMA))
        .body("error.code", equalTo("validation_error"))
        .body("error.details.size()", greaterThan(0))
        .body("error.details[0].field", equalTo("email"))
        .body("error.details[0].issue", containsString("valid email"))
        .body("error.correlationId", matchesPattern("[0-9a-f-]{36}"))
        .body("error.timestamp", notNullValue());
}

@Test
public void testErrorSchema_401Unauthorized() {
    given()
        // No auth header
    .when()
        .get("/api/v1/users/me")
    .then()
        .statusCode(401)
        .body(matchesJsonSchemaInClasspath(ERROR_SCHEMA))
        .body("error.code", equalTo("unauthorized"))
        .body("error.message", notNullValue())
        .body("error.correlationId", notNullValue());
}

@Test
public void testErrorSchema_404NotFound() {
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/users/99999999")
    .then()
        .statusCode(404)
        .body(matchesJsonSchemaInClasspath(ERROR_SCHEMA))
        .body("error.code", equalTo("not_found"))
        .body("error.message", containsString("User"));
}

@Test
public void testErrorSchema_409Conflict() {
    // Create duplicate resource
    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body("{\"email\": \"existing@test.com\", \"name\": \"Test\"}")
    .when()
        .post("/api/v1/users")
    .then()
        .statusCode(409)
        .body(matchesJsonSchemaInClasspath(ERROR_SCHEMA))
        .body("error.code", equalTo("conflict"))
        .body("error.message", containsString("already exists"));
}

@Test
public void testErrorSchema_500InternalError_noLeakedDetails() {
    // Trigger internal error (e.g., via a known bad input that causes exception)
    given()
        .header("Authorization", "Bearer token")
        .header("X-Test-Trigger", "internal_error")
    .when()
        .get("/api/v1/trigger-error")
    .then()
        .statusCode(500)
        .body(matchesJsonSchemaInClasspath(ERROR_SCHEMA))
        .body("error.code", equalTo("internal_error"))
        .body("error.message", equalTo("An unexpected error occurred"))
        // Security: no stack traces or internal details
        .body("error.message", not(containsString("Exception")))
        .body("error.message", not(containsString("at com.")))
        .body("error.message", not(containsString("SQL")))
        .body("$", not(hasKey("stack")))
        .body("$", not(hasKey("trace")));
}

@ParameterizedTest
@ValueSource(strings = {
    "/api/v1/users/invalid-id",
    "/api/v1/orders/bad-format",
    "/api/v1/products/xyz"
})
public void testErrorSchema_consistentAcrossEndpoints(String path) {
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get(path)
    .then()
        .statusCode(anyOf(is(400), is(404)))
        .body(matchesJsonSchemaInClasspath(ERROR_SCHEMA))
        .body("error.code", notNullValue())
        .body("error.message", notNullValue())
        .body("error.correlationId", notNullValue());
}

Error Schema JSON Schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "required": ["error"],
  "properties": {
    "error": {
      "type": "object",
      "required": ["code", "message", "correlationId", "timestamp"],
      "properties": {
        "code": { "type": "string", "minLength": 1 },
        "message": { "type": "string", "minLength": 1 },
        "correlationId": { "type": "string", "format": "uuid" },
        "timestamp": { "type": "string", "format": "date-time" },
        "details": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "field": { "type": "string" },
              "issue": { "type": "string" }
            }
          }
        },
        "documentation": { "type": "string", "format": "uri" }
      }
    }
  }
}

Common Mistakes to Avoid

  • Not testing all HTTP error codes (400, 401, 403, 404, 409, 422, 429, 500, 503)
  • Allowing stack traces to leak in production error responses
  • Not testing that error responses include correlation IDs for debugging
  • Having inconsistent error formats across different microservices

Follow-up Questions

  • How do you enforce error schema consistency across a team of developers?
  • What is RFC 7807 (Problem Details for HTTP APIs) and how do you test compliance?
  • How do you handle errors that span multiple fields (cross-field validation)?

Q22How do you test multipart upload APIs? #

Objective

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.

// REST Assured — Multipart upload testing
@Test
public void testMultipartUpload_validImage_succeeds() {
    File testImage = new File("src/test/resources/test-image.png");

    given()
        .header("Authorization", "Bearer token")
        .multiPart("file", testImage, "image/png")
        .multiPart("description", "Profile photo")
        .multiPart("category", "avatar")
    .when()
        .post("/api/v1/uploads")
    .then()
        .statusCode(201)
        .body("id", notNullValue())
        .body("filename", equalTo("test-image.png"))
        .body("contentType", equalTo("image/png"))
        .body("size", greaterThan(0))
        .body("url", matchesPattern("https://cdn\\.example\\.com/.*"))
        .body("thumbnailUrl", notNullValue());
}

@Test
public void testMultipartUpload_invalidFileType_returns415() {
    File execFile = new File("src/test/resources/malicious.exe");

    given()
        .header("Authorization", "Bearer token")
        .multiPart("file", execFile, "application/x-msdownload")
    .when()
        .post("/api/v1/uploads")
    .then()
        .statusCode(415)
        .body("error.code", equalTo("unsupported_media_type"))
        .body("error.message", containsString("Allowed types"))
        .body("error.details[0].allowedTypes", hasItems("image/png", "image/jpeg", "application/pdf"));
}

@Test
public void testMultipartUpload_exceedsMaxSize_returns413() {
    // Create a large file (11MB when limit is 10MB)
    byte[] largeContent = new byte[11 * 1024 * 1024];
    new Random().nextBytes(largeContent);

    given()
        .header("Authorization", "Bearer token")
        .multiPart("file", "large-file.pdf", largeContent, "application/pdf")
    .when()
        .post("/api/v1/uploads")
    .then()
        .statusCode(413)
        .body("error.code", equalTo("payload_too_large"))
        .body("error.message", containsString("10MB"));
}

@Test
public void testMultipartUpload_spoofedContentType_detected() {
    // Send an exe file disguised as PNG (content-type header says PNG)
    File exeFile = new File("src/test/resources/malicious.exe");

    given()
        .header("Authorization", "Bearer token")
        .multiPart("file", "innocent.png", exeFile, "image/png") // Spoofed type
    .when()
        .post("/api/v1/uploads")
    .then()
        .statusCode(415)
        .body("error.code", equalTo("content_type_mismatch"))
        .body("error.message", containsString("does not match file content"));
}

@Test
public void testMultipartUpload_emptyFile_returns400() {
    given()
        .header("Authorization", "Bearer token")
        .multiPart("file", "empty.pdf", new byte[0], "application/pdf")
    .when()
        .post("/api/v1/uploads")
    .then()
        .statusCode(400)
        .body("error.code", equalTo("empty_file"));
}

@Test
public void testMultipartUpload_missingFile_returns400() {
    given()
        .header("Authorization", "Bearer token")
        .multiPart("description", "No file attached")
    .when()
        .post("/api/v1/uploads")
    .then()
        .statusCode(400)
        .body("error.code", equalTo("missing_file"))
        .body("error.details[0].field", equalTo("file"));
}

@Test
public void testMultipartUpload_specialCharactersInFilename() {
    File testFile = new File("src/test/resources/test-image.png");

    given()
        .header("Authorization", "Bearer token")
        .multiPart("file", "file with spaces & (special).png", testFile, "image/png")
    .when()
        .post("/api/v1/uploads")
    .then()
        .statusCode(201)
        .body("filename", equalTo("file_with_spaces___special_.png")); // Sanitized
}
# curl — Multipart upload
curl -X POST https://api.example.com/v1/uploads \
  -H "Authorization: Bearer token" \
  -F "file=@/path/to/image.png;type=image/png" \
  -F "description=Profile photo" \
  -F "category=avatar" \
  -w "\nHTTP: %{http_code}\n"

# Test large file
dd if=/dev/urandom of=/tmp/large.bin bs=1M count=11
curl -X POST https://api.example.com/v1/uploads \
  -H "Authorization: Bearer token" \
  -F "file=@/tmp/large.bin;type=application/octet-stream" \
  -w "\nHTTP: %{http_code}\n"

Common Mistakes to Avoid

  • Only checking Content-Type header (not magic bytes of actual file content)
  • Not testing filename sanitization (path traversal: ../../etc/passwd)
  • Forgetting to test concurrent uploads from the same user
  • Not testing upload quota/rate limiting per user

Follow-up Questions

  • How do you test resumable/chunked uploads?
  • How do you handle virus scanning in the upload pipeline?
  • How do you test pre-signed URL upload patterns (e.g., S3)?

Q23How do you test large payload limits? #

Objective

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:

  1. Payload exactly at limit → accepted
  2. Payload 1 byte over limit → rejected with 413
  3. Chunked transfer encoding behavior
  4. Response pagination for large result sets
  5. Memory/timeout behavior with large payloads
// REST Assured — Large payload testing
@Test
public void testPayloadLimit_withinLimit_accepted() {
    // Create payload just under 1MB limit
    String largeDescription = "A".repeat(999_000);
    String payload = "{\"name\": \"Test\", \"description\": \"" + largeDescription + "\"}";

    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body(payload)
    .when()
        .post("/api/v1/products")
    .then()
        .statusCode(201);
}

@Test
public void testPayloadLimit_exceedsLimit_returns413() {
    // Create payload over 1MB limit
    String oversizedDescription = "B".repeat(1_100_000);
    String payload = "{\"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"));
}

@Test
public void testPayloadLimit_largeArray_enforced() {
    // Create request with too many items
    List<Map<String, String>> items = new ArrayList<>();
    for (int i = 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"));
}

@Test
public void testPayloadLimit_deeplyNestedJson_rejected() {
    // Create deeply nested JSON (potential DoS vector)
    StringBuilder nested = new StringBuilder("{");
    for (int i = 0; i < 200; i++) { // Limit might be 50 levels
        nested.append("\"level").append(i).append("\":{");
    }
    nested.append("\"value\":1");
    for (int i = 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"));
}

@Test
public void testPayloadLimit_responseTime_withinSLA() {
    // Large but valid payload should still respond within SLA
    String payload = createValidLargePayload(500_000); // 500KB

    long start = System.currentTimeMillis();

    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer token")
        .body(payload)
    .when()
        .post("/api/v1/products")
    .then()
        .statusCode(201);

    long elapsed = System.currentTimeMillis() - start;
    assertTrue(elapsed < 5000, "Large payload should process within 5s SLA");
}

@Test
public void testPayloadLimit_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)));
}
# curl — Large payload testing
# Generate payload at boundary
python3 -c "import json; print(json.dumps({'data': 'A' * 1048576}))" > /tmp/large.json
curl -X POST https://api.example.com/v1/data \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer token" \
  -d @/tmp/large.json \
  -w "\nHTTP: %{http_code}\nSize Sent: %{size_upload}\n"

# Test with known over-limit
python3 -c "import json; print(json.dumps({'data': 'B' * 2097152}))" > /tmp/too_large.json
curl -X POST https://api.example.com/v1/data \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer token" \
  -d @/tmp/too_large.json \
  -w "\nHTTP: %{http_code}\n"

Common Mistakes to Avoid

  • Not testing at exact boundary values (limit-1, limit, limit+1)
  • Forgetting to test Content-Length header spoofing
  • Not considering that load balancers/proxies may have their own limits
  • Not testing deeply nested JSON as a DoS vector

Follow-up Questions

  • How do gateway/proxy limits (nginx, ALB) interact with application limits?
  • How do you test streaming/chunked uploads for very large files?
  • What is the relationship between payload size and timeout configuration?

Q24How do you test PII exposure? #

Objective

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
@Test
public void testPIIExposure_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")));
}

@Test
public void testPIIExposure_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());
}

@Test
public void testPIIExposure_searchEndpoint_noSensitiveData() {
    // Search should not expose PII of other users
    Response response = 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");
    }
}

@Test
public void testPIIExposure_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
}

@Test
public void testPIIExposure_responseHeaders_clean() {
    Response response = 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 -> {
        String value = 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());
    });
}

@Test
public void testPIIExposure_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")));
}

@Test
public void testPIIExposure_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")));
}
# curl — PII scanning
# Fetch response and scan for PII patterns
RESPONSE=$(curl -s https://api.example.com/v1/users/me \
  -H "Authorization: Bearer token")

# Check for SSN pattern
echo "$RESPONSE" | grep -oP '\d{3}-\d{2}-\d{4}' && echo "WARNING: SSN detected!"

# Check for credit card patterns
echo "$RESPONSE" | grep -oP '\d{13,19}' && echo "WARNING: Possible card number!"

# Check for email in unexpected fields
echo "$RESPONSE" | jq 'paths | select(.[-1] != "email")' | while read path; do
  echo "$RESPONSE" | jq ".$path" | grep -oP '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
done

Common Mistakes to Avoid

  • Only testing the main user endpoint (PII can leak through search, export, error messages, logs)
  • Not testing that server logs don't contain PII (log aggregator search)
  • Assuming masking is applied at every layer (it might only be at the API gateway)
  • Not testing verbose error modes (debug=true) that might expose PII

Follow-up Questions

  • How do you automate PII detection in CI/CD pipelines?
  • What is data minimization and how does it relate to GDPR?
  • How do you test the right to erasure (GDPR Article 17)?

Q25How do you test tenant isolation? #

Objective

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:

  1. Data isolation — Tenant A cannot read Tenant B's data
  2. API isolation — Tenant A's queries never return Tenant B's results
  3. Resource isolation — Tenant A cannot affect Tenant B's quotas
  4. Metadata isolation — Tenant A cannot enumerate other tenants
// REST Assured — Tenant isolation testing
@Test
public void testTenantIsolation_cannotAccessOtherTenantData() {
    // Create resource as Tenant A
    String resourceId = 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)
}

@Test
public void testTenantIsolation_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 own
    Response tenantAList = 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");
}

@Test
public void testTenantIsolation_cannotModifyOtherTenantResource() {
    String tenantADoc = 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"));
}

@Test
public void testTenantIsolation_cannotDeleteOtherTenantResource() {
    String tenantADoc = 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);
}

@Test
public void testTenantIsolation_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"));
}

@Test
public void testTenantIsolation_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"));
}

@Test
public void testTenantIsolation_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"));
}
# curl — Tenant isolation testing
# Create resource as Tenant A
DOC_ID=$(curl -s -X POST https://api.example.com/v1/documents \
  -H "Authorization: Bearer tenant_a_token" \
  -H "X-Tenant-ID: tenant_a" \
  -H "Content-Type: application/json" \
  -d '{"name": "Secret", "content": "classified"}' | jq -r '.id')

# Attempt access as Tenant B (should get 404)
curl -s https://api.example.com/v1/documents/$DOC_ID \
  -H "Authorization: Bearer tenant_b_token" \
  -H "X-Tenant-ID: tenant_b" \
  -w "\nHTTP: %{http_code}\n"

Common Mistakes to Avoid

  • Returning 403 instead of 404 for cross-tenant access (403 confirms existence)
  • Only testing direct access (not search, list, aggregate, export endpoints)
  • Not testing tenant ID header tampering
  • Forgetting to test shared/common resources that are intentionally cross-tenant

Follow-up Questions

  • How do you test tenant isolation at the database level (schema vs row-level)?
  • What is the security implication of returning 403 vs 404 for cross-tenant access?
  • How do you test tenant isolation in shared caches (Redis)?

Q26How do you validate audit logs? #

Objective

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.

What Must Be Audited:

  • Authentication events (login, logout, failed attempts)
  • Authorization failures (access denied)
  • Data access (who viewed what)
  • Data modification (who changed what)
  • Admin actions (role changes, user management)
  • Security events (password changes, MFA setup)
// REST Assured — Audit log validation
@Test
public void testAuditLog_loginAttempt_recorded() {
    // Perform login
    given()
        .header("Content-Type", "application/json")
        .body("{\"email\": \"user@test.com\", \"password\": \"correct_pass\"}")
    .when()
        .post("/api/v1/auth/login")
    .then()
        .statusCode(200);

    // Verify audit log entry
    given()
        .header("Authorization", "Bearer admin_token")
        .queryParam("action", "auth.login")
        .queryParam("actor", "user@test.com")
        .queryParam("since", Instant.now().minusSeconds(30).toString())
    .when()
        .get("/api/v1/admin/audit-logs")
    .then()
        .statusCode(200)
        .body("logs.size()", greaterThan(0))
        .body("logs[0].action", equalTo("auth.login"))
        .body("logs[0].actor", equalTo("user@test.com"))
        .body("logs[0].result", equalTo("success"))
        .body("logs[0].ipAddress", notNullValue())
        .body("logs[0].userAgent", notNullValue())
        .body("logs[0].timestamp", notNullValue())
        .body("logs[0].correlationId", notNullValue());
}

@Test
public void testAuditLog_failedLogin_recorded() {
    given()
        .header("Content-Type", "application/json")
        .body("{\"email\": \"user@test.com\", \"password\": \"wrong_pass\"}")
    .when()
        .post("/api/v1/auth/login")
    .then()
        .statusCode(401);

    given()
        .header("Authorization", "Bearer admin_token")
        .queryParam("action", "auth.login")
        .queryParam("result", "failure")
    .when()
        .get("/api/v1/admin/audit-logs")
    .then()
        .body("logs[0].result", equalTo("failure"))
        .body("logs[0].failureReason", equalTo("invalid_credentials"))
        .body("logs[0].actor", equalTo("user@test.com"));
}

@Test
public void testAuditLog_dataModification_capturesBefore AndAfter() {
    // Update a user's role
    given()
        .header("Authorization", "Bearer admin_token")
        .header("Content-Type", "application/json")
        .body("{\"role\": \"admin\"}")
    .when()
        .patch("/api/v1/admin/users/456/role")
    .then()
        .statusCode(200);

    // Verify audit log captures the change detail
    given()
        .header("Authorization", "Bearer admin_token")
        .queryParam("action", "user.role_change")
        .queryParam("targetUserId", "456")
    .when()
        .get("/api/v1/admin/audit-logs")
    .then()
        .body("logs[0].action", equalTo("user.role_change"))
        .body("logs[0].actor", equalTo("admin@company.com"))
        .body("logs[0].target", equalTo("456"))
        .body("logs[0].changes.before.role", equalTo("user"))
        .body("logs[0].changes.after.role", equalTo("admin"));
}

@Test
public void testAuditLog_sensitiveDataAccess_logged() {
    // Access PII data
    given()
        .header("Authorization", "Bearer admin_token")
    .when()
        .get("/api/v1/admin/users/456/full-profile")
    .then()
        .statusCode(200);

    // Verify the access was logged
    given()
        .header("Authorization", "Bearer admin_token")
        .queryParam("action", "data.access")
        .queryParam("resource", "user.full-profile")
    .when()
        .get("/api/v1/admin/audit-logs")
    .then()
        .body("logs[0].action", equalTo("data.access"))
        .body("logs[0].resource", equalTo("user.full-profile"))
        .body("logs[0].resourceId", equalTo("456"))
        .body("logs[0].dataClassification", equalTo("PII"));
}

@Test
public void testAuditLog_immutability_cannotBeDeleted() {
    // Attempt to delete audit logs
    given()
        .header("Authorization", "Bearer admin_token")
    .when()
        .delete("/api/v1/admin/audit-logs/log_123")
    .then()
        .statusCode(405); // Method Not Allowed — logs are immutable

    // Attempt to modify audit logs
    given()
        .header("Authorization", "Bearer admin_token")
        .header("Content-Type", "application/json")
        .body("{\"result\": \"success\"}") // Trying to change failure to success
    .when()
        .patch("/api/v1/admin/audit-logs/log_123")
    .then()
        .statusCode(405);
}

@Test
public void testAuditLog_completeness_allEndpointsAudited() {
    String correlationId = UUID.randomUUID().toString();

    // Perform multiple actions with same correlation ID
    given()
        .header("Authorization", "Bearer token")
        .header("X-Correlation-ID", correlationId)
    .when()
        .get("/api/v1/users/me");

    given()
        .header("Authorization", "Bearer token")
        .header("X-Correlation-ID", correlationId)
        .header("Content-Type", "application/json")
        .body("{\"name\": \"Updated\"}")
    .when()
        .patch("/api/v1/users/me");

    // Verify all actions logged with correlation
    given()
        .header("Authorization", "Bearer admin_token")
        .queryParam("correlationId", correlationId)
    .when()
        .get("/api/v1/admin/audit-logs")
    .then()
        .body("logs.size()", equalTo(2))
        .body("logs.findAll { it.correlationId == '" + correlationId + "' }.size()", equalTo(2));
}
# curl — Audit log queries
# Query recent audit logs
curl -s "https://api.example.com/v1/admin/audit-logs?since=2026-07-15T00:00:00Z&action=auth.login" \
  -H "Authorization: Bearer admin_token" | jq '.logs[] | {action, actor, result, timestamp}'

# Check failed login attempts
curl -s "https://api.example.com/v1/admin/audit-logs?action=auth.login&result=failure&limit=10" \
  -H "Authorization: Bearer admin_token" | jq '.logs[] | {actor, ipAddress, timestamp}'

Common Mistakes to Avoid

  • Not testing that audit logs capture failed operations (not just successful ones)
  • Forgetting to validate immutability (audit logs should never be modifiable)
  • Not testing that PII in audit logs is appropriately handled (masked or encrypted)
  • Only testing happy path (audit logs for errors and edge cases matter most)

Follow-up Questions

  • How do you ensure audit log integrity (tamper-evident logging)?
  • What retention policies apply to audit logs (SOX, HIPAA, GDPR)?
  • How do you test audit log performance under high throughput?

Q27How do you test cache invalidation? #

Objective

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:

  1. Fresh cache — response includes cache headers
  2. Cache hit — faster response, correct data
  3. Write invalidates cache — next read returns fresh data
  4. TTL expiration — cache auto-refreshes after timeout
  5. Cache stampede protection — only one origin request when cache expires
// REST Assured — Cache invalidation testing
@Test
public void testCache_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());
}

@Test
public void testCache_conditionalGet_returns304() {
    // First request — get ETag
    Response first = given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/products/123")
    .then()
        .statusCode(200)
        .extract().response();

    String etag = 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
}

@Test
public void testCache_writeInvalidatesCache() {
    // Read to populate cache
    Response original = given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/products/123")
    .then()
        .statusCode(200)
        .extract().response();

    String originalName = original.jsonPath().getString("name");
    String originalEtag = 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
}

@Test
public void testCache_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"));
}

@Test
public void testCache_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);
}

@Test
public void testCache_performanceImprovement() {
    // First request (cache miss) — slower
    long firstStart = System.currentTimeMillis();
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/products/123")
    .then()
        .statusCode(200)
        .header("X-Cache", equalTo("MISS"));
    long firstTime = System.currentTimeMillis() - firstStart;

    // Second request (cache hit) — faster
    long secondStart = System.currentTimeMillis();
    given()
        .header("Authorization", "Bearer token")
    .when()
        .get("/api/v1/products/123")
    .then()
        .statusCode(200)
        .header("X-Cache", equalTo("HIT"));
    long secondTime = System.currentTimeMillis() - secondStart;

    assertTrue(secondTime < firstTime / 2,
        "Cache hit should be significantly faster than cache miss");
}
# curl — Cache testing
# First request (cache miss)
curl -s -w "\nTime: %{time_total}s\n" \
  https://api.example.com/v1/products/123 \
  -H "Authorization: Bearer token" \
  -D - | grep -i "cache\|etag\|x-cache"

# Conditional request
ETAG=$(curl -sI https://api.example.com/v1/products/123 \
  -H "Authorization: Bearer token" | grep -i "etag" | awk '{print $2}' | tr -d '\r')

curl -s -w "\nHTTP: %{http_code}\n" \
  https://api.example.com/v1/products/123 \
  -H "Authorization: Bearer token" \
  -H "If-None-Match: $ETAG"

Common Mistakes to Avoid

  • Not testing cache invalidation across related resources (updating product should invalidate product list cache)
  • Forgetting to test cache behavior with different query parameters
  • Not testing that authenticated vs unauthenticated requests have separate caches
  • Not testing cache behavior during deployments (cache warm-up)

Follow-up Questions

  • How do you test cache invalidation in a distributed multi-node setup?
  • What is cache stampede and how do you test protection against it?
  • How do you test CDN cache purging?

Q28How do you test a webhook signature? #

Objective

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:

  1. Provider computes HMAC-SHA256 of the payload using a shared secret
  2. Signature is sent in a header (e.g., X-Webhook-Signature)
  3. Consumer recomputes the signature and compares
  4. If signatures match, the payload is authentic
// REST Assured — Webhook signature testing
@Test
public void testWebhookSignature_validSignature_accepted() {
    String payload = "{\"event\":\"payment.completed\",\"data\":{\"id\":\"pay_123\"}}";
    String secret = "whsec_test_secret_key";
    String timestamp = String.valueOf(Instant.now().getEpochSecond());
    String signedContent = timestamp + "." + payload;
    String signature = computeHmacSha256(signedContent, secret);

    given()
        .header("Content-Type", "application/json")
        .header("X-Webhook-Signature", "v1=" + signature)
        .header("X-Webhook-Timestamp", timestamp)
        .body(payload)
    .when()
        .post("/webhooks/payments")
    .then()
        .statusCode(200)
        .body("received", equalTo(true));
}

@Test
public void testWebhookSignature_invalidSignature_rejected() {
    String payload = "{\"event\":\"payment.completed\",\"data\":{\"id\":\"pay_123\"}}";

    given()
        .header("Content-Type", "application/json")
        .header("X-Webhook-Signature", "v1=invalid_signature_abc123")
        .header("X-Webhook-Timestamp", String.valueOf(Instant.now().getEpochSecond()))
        .body(payload)
    .when()
        .post("/webhooks/payments")
    .then()
        .statusCode(401)
        .body("error.code", equalTo("invalid_signature"));
}

@Test
public void testWebhookSignature_missingSignature_rejected() {
    String payload = "{\"event\":\"payment.completed\",\"data\":{\"id\":\"pay_123\"}}";

    given()
        .header("Content-Type", "application/json")
        // No signature header
        .body(payload)
    .when()
        .post("/webhooks/payments")
    .then()
        .statusCode(401)
        .body("error.code", equalTo("missing_signature"));
}

@Test
public void testWebhookSignature_tamperedPayload_rejected() {
    String originalPayload = "{\"event\":\"payment.completed\",\"data\":{\"amount\":100}}";
    String secret = "whsec_test_secret_key";
    String timestamp = String.valueOf(Instant.now().getEpochSecond());
    String signature = computeHmacSha256(timestamp + "." + originalPayload, secret);

    // Tamper with the payload after signing
    String tamperedPayload = "{\"event\":\"payment.completed\",\"data\":{\"amount\":99999}}";

    given()
        .header("Content-Type", "application/json")
        .header("X-Webhook-Signature", "v1=" + signature)
        .header("X-Webhook-Timestamp", timestamp)
        .body(tamperedPayload) // Modified payload
    .when()
        .post("/webhooks/payments")
    .then()
        .statusCode(401)
        .body("error.code", equalTo("invalid_signature"));
}

@Test
public void testWebhookSignature_replayAttack_rejectedByTimestamp() {
    String payload = "{\"event\":\"payment.completed\",\"data\":{\"id\":\"pay_123\"}}";
    String secret = "whsec_test_secret_key";
    // Timestamp from 10 minutes ago (beyond tolerance window)
    String staleTimestamp = String.valueOf(Instant.now().minusSeconds(600).getEpochSecond());
    String signature = computeHmacSha256(staleTimestamp + "." + payload, secret);

    given()
        .header("Content-Type", "application/json")
        .header("X-Webhook-Signature", "v1=" + signature)
        .header("X-Webhook-Timestamp", staleTimestamp)
        .body(payload)
    .when()
        .post("/webhooks/payments")
    .then()
        .statusCode(401)
        .body("error.code", equalTo("timestamp_expired"))
        .body("error.message", containsString("tolerance"));
}

@Test
public void testWebhookSignature_timingAttackResistance() {
    String payload = "{\"event\":\"test\"}";
    String timestamp = String.valueOf(Instant.now().getEpochSecond());

    // Measure response time with completely wrong signature
    long wrongStart = System.currentTimeMillis();
    given()
        .header("X-Webhook-Signature", "v1=aaaa")
        .header("X-Webhook-Timestamp", timestamp)
        .body(payload)
    .when()
        .post("/webhooks/payments");
    long wrongTime = System.currentTimeMillis() - wrongStart;

    // Measure response time with almost-correct signature
    long almostStart = System.currentTimeMillis();
    given()
        .header("X-Webhook-Signature", "v1=" + "a".repeat(64))
        .header("X-Webhook-Timestamp", timestamp)
        .body(payload)
    .when()
        .post("/webhooks/payments");
    long almostTime = System.currentTimeMillis() - almostStart;

    // Timing should be similar (constant-time comparison)
    long diff = Math.abs(wrongTime - almostTime);
    assertTrue(diff < 50, "Signature comparison should be constant-time");
}

// Helper method
private String computeHmacSha256(String data, String secret) {
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        mac.init(keySpec);
        byte[] hash = mac.doFinal(data.getBytes());
        return Hex.encodeHexString(hash);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
# curl — Webhook signature testing
PAYLOAD='{"event":"payment.completed","data":{"id":"pay_123"}}'
SECRET="whsec_test_secret_key"
TIMESTAMP=$(date +%s)
SIGNED_CONTENT="${TIMESTAMP}.${PAYLOAD}"
SIGNATURE=$(echo -n "$SIGNED_CONTENT" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}')

# Valid signature
curl -X POST https://myapp.com/webhooks/payments \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Signature: v1=$SIGNATURE" \
  -H "X-Webhook-Timestamp: $TIMESTAMP" \
  -d "$PAYLOAD" \
  -w "\nHTTP: %{http_code}\n"

# Invalid signature
curl -X POST https://myapp.com/webhooks/payments \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Signature: v1=fakesignature123" \
  -H "X-Webhook-Timestamp: $TIMESTAMP" \
  -d "$PAYLOAD" \
  -w "\nHTTP: %{http_code}\n"

Common Mistakes to Avoid

  • Not testing timestamp validation (replay attack prevention)
  • Using non-constant-time string comparison (timing attack vulnerability)
  • Not testing with different content types (raw body vs parsed JSON may differ)
  • Forgetting to test signature rotation (when provider rotates secrets)

Follow-up Questions

  • How do you handle webhook secret rotation without downtime?
  • What is the appropriate timestamp tolerance window?
  • How do you test webhook signature verification for providers that use asymmetric keys (RSA)?

Q29How do you test a bulk endpoint? #

Objective

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:

  1. All items valid → all processed successfully
  2. Some items invalid → partial success with per-item error reporting
  3. Transactional vs non-transactional behavior
  4. Ordering of results matches ordering of input
  5. Rate limiting and size limits for bulk requests
// REST Assured — Bulk endpoint testing
@Test
public void testBulkEndpoint_allValid_returns200() {
    String payload = """
        {
            "items": [
                {"email": "user1@test.com", "name": "User 1"},
                {"email": "user2@test.com", "name": "User 2"},
                {"email": "user3@test.com", "name": "User 3"}
            ]
        }
    """;

    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer admin_token")
        .body(payload)
    .when()
        .post("/api/v1/users/bulk")
    .then()
        .statusCode(200)
        .body("total", equalTo(3))
        .body("succeeded", equalTo(3))
        .body("failed", equalTo(0))
        .body("results.size()", equalTo(3))
        .body("results[0].status", equalTo("created"))
        .body("results[0].id", notNullValue())
        .body("results[1].status", equalTo("created"))
        .body("results[2].status", equalTo("created"));
}

@Test
public void testBulkEndpoint_partialFailure_reportsPerItem() {
    String payload = """
        {
            "items": [
                {"email": "valid1@test.com", "name": "Valid User 1"},
                {"email": "invalid-email", "name": "Bad Email"},
                {"email": "valid2@test.com", "name": "Valid User 2"},
                {"email": "duplicate@test.com", "name": "Duplicate"}
            ]
        }
    """;

    // Pre-create the duplicate
    createUser("duplicate@test.com", "Existing");

    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer admin_token")
        .body(payload)
    .when()
        .post("/api/v1/users/bulk")
    .then()
        .statusCode(207) // Multi-Status
        .body("total", equalTo(4))
        .body("succeeded", equalTo(2))
        .body("failed", equalTo(2))
        .body("results[0].status", equalTo("created"))
        .body("results[0].index", equalTo(0))
        .body("results[1].status", equalTo("failed"))
        .body("results[1].index", equalTo(1))
        .body("results[1].error.code", equalTo("validation_error"))
        .body("results[1].error.field", equalTo("email"))
        .body("results[2].status", equalTo("created"))
        .body("results[3].status", equalTo("failed"))
        .body("results[3].error.code", equalTo("duplicate_entry"));
}

@Test
public void testBulkEndpoint_exceedsMaxItems_returns400() {
    List<Map<String, String>> items = new ArrayList<>();
    for (int i = 0; i < 1001; i++) { // Limit is 1000
        items.add(Map.of("email", "user" + i + "@test.com", "name", "User " + i));
    }

    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer admin_token")
        .body(Map.of("items", items))
    .when()
        .post("/api/v1/users/bulk")
    .then()
        .statusCode(400)
        .body("error.code", equalTo("too_many_items"))
        .body("error.message", containsString("1000"))
        .body("error.maxItems", equalTo(1000));
}

@Test
public void testBulkEndpoint_emptyArray_returns400() {
    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer admin_token")
        .body("{\"items\": []}")
    .when()
        .post("/api/v1/users/bulk")
    .then()
        .statusCode(400)
        .body("error.code", equalTo("empty_batch"))
        .body("error.message", containsString("at least one item"));
}

@Test
public void testBulkEndpoint_orderPreserved() {
    String payload = """
        {
            "items": [
                {"email": "first@test.com", "name": "First"},
                {"email": "second@test.com", "name": "Second"},
                {"email": "third@test.com", "name": "Third"}
            ]
        }
    """;

    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer admin_token")
        .body(payload)
    .when()
        .post("/api/v1/users/bulk")
    .then()
        .statusCode(200)
        .body("results[0].index", equalTo(0))
        .body("results[0].data.email", equalTo("first@test.com"))
        .body("results[1].index", equalTo(1))
        .body("results[1].data.email", equalTo("second@test.com"))
        .body("results[2].index", equalTo(2))
        .body("results[2].data.email", equalTo("third@test.com"));
}

@Test
public void testBulkEndpoint_performanceWithinSLA() {
    // Create 500 valid items
    List<Map<String, String>> items = new ArrayList<>();
    for (int i = 0; i < 500; i++) {
        items.add(Map.of("email", "perf" + i + "@test.com", "name", "Perf User " + i));
    }

    long start = System.currentTimeMillis();

    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer admin_token")
        .body(Map.of("items", items))
    .when()
        .post("/api/v1/users/bulk")
    .then()
        .statusCode(200)
        .body("succeeded", equalTo(500));

    long elapsed = System.currentTimeMillis() - start;
    assertTrue(elapsed < 30000, "500 items should process within 30s SLA");
}

@Test
public void testBulkEndpoint_idempotencyKey_preventsReprocessing() {
    String idempotencyKey = UUID.randomUUID().toString();
    String payload = """
        {"items": [{"email": "idem@test.com", "name": "Idempotent User"}]}
    """;

    // First call
    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer admin_token")
        .header("Idempotency-Key", idempotencyKey)
        .body(payload)
    .when()
        .post("/api/v1/users/bulk")
    .then()
        .statusCode(200)
        .body("succeeded", equalTo(1));

    // Duplicate call with same key
    given()
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer admin_token")
        .header("Idempotency-Key", idempotencyKey)
        .body(payload)
    .when()
        .post("/api/v1/users/bulk")
    .then()
        .statusCode(200)
        .body("succeeded", equalTo(1)); // Same result, not reprocessed
}
# curl — Bulk endpoint testing
curl -X POST https://api.example.com/v1/users/bulk \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer admin_token" \
  -d '{
    "items": [
      {"email": "user1@test.com", "name": "User 1"},
      {"email": "invalid-email", "name": "Bad"},
      {"email": "user2@test.com", "name": "User 2"}
    ]
  }' | jq '{total, succeeded, failed, results: [.results[] | {index, status, error}]}'

Response Example (207 Multi-Status):

{
  "total": 4,
  "succeeded": 2,
  "failed": 2,
  "results": [
    { "index": 0, "status": "created", "id": "usr_001" },
    { "index": 1, "status": "failed", "error": { "code": "validation_error", "field": "email" } },
    { "index": 2, "status": "created", "id": "usr_002" },
    { "index": 3, "status": "failed", "error": { "code": "duplicate_entry" } }
  ]
}

Common Mistakes to Avoid

  • Not testing partial failure behavior (all-or-nothing vs partial success)
  • Forgetting to validate result ordering matches input ordering
  • Not testing with items that have interdependencies within the batch
  • Not testing the 207 Multi-Status response code for mixed results

Follow-up Questions

  • Should bulk operations be all-or-nothing (transactional) or allow partial success?
  • How do you handle bulk operations that take too long (async bulk)?
  • How do you test bulk delete vs bulk create differences?

Q30How do you investigate an API-only defect? #

Objective

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):

  1. Reproduce — Capture the exact failing request
  2. Analyze — Examine logs, traces, and metrics
  3. Pinpoint — Isolate the variable that triggers the defect
  4. Identify — Determine root cause
  5. Document — Record findings and write a regression test
// Step 1: Reproduce — Capture and replay the exact request
@Test
public void reproduceDefect_JIRA_1234() {
    // Exact reproduction from production logs
    Response response = 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
@Test
public void analyzeDefect_traceRequest() {
    String correlationId = "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
@Test
public void pinpointDefect_isolateVariable() {
    String basePayload = "{\"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
@Test
public void regressionTest_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) {
        Response response = 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();

        String paymentId = 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));
    }
}
# Investigation commands

# 1. Reproduce from access logs
# Extract the failing request from nginx/ALB logs
grep "500" /var/log/nginx/access.log | grep "POST /api/v1/payments" | tail -5

# 2. Replay exact request from curl
curl -X POST https://api.example.com/v1/payments \
  -H "Content-Type: application/json; charset=UTF-8" \
  -H "Authorization: Bearer token" \
  -H "Accept-Language: fr-FR" \
  -d '{"amount": 10.50, "currency": "EUR", "description": "Café résumé"}' \
  -v 2>&1

# 3. Check application logs with correlation ID
# CloudWatch / ELK query
# correlationId:"550e8400-e29b-41d4-a716-446655440000" AND level:ERROR

# 4. Compare working vs failing requests
diff <(curl -s -D - https://api.example.com/v1/payments \
  -H "Authorization: Bearer token" \
  -d '{"amount": 10, "description": "Normal"}') \
     <(curl -s -D - https://api.example.com/v1/payments \
  -H "Authorization: Bearer token" \
  -d '{"amount": 10, "description": "Café"}')

# 5. Check for infrastructure-level issues
curl -s https://api.example.com/v1/health | jq .
curl -s https://api.example.com/v1/metrics | grep payment_errors

Investigation Decision Tree:

API returns unexpected error
├── Can reproduce with curl?
│   ├── YES → Compare headers/body with UI request
│   │   ├── Header difference → Test each header in isolation
│   │   ├── Body difference → Test specific field values
│   │   └── Timing difference → Race condition investigation
│   └── NO → Environment-specific
│       ├── Check server logs for the exact timestamp
│       ├── Check infrastructure (load balancer, DNS, TLS)
│       └── Check if it's intermittent (load/timing dependent)
├── Status code analysis
│   ├── 400 → Request validation issue (check schema)
│   ├── 401/403 → Auth/authz issue (check token, roles)
│   ├── 404 → Routing issue (check path, method)
│   ├── 500 → Server bug (check logs, traces)
│   └── 502/503 → Infrastructure (check upstream services)
└── Works in staging but not prod?
    ├── Configuration difference
    ├── Data difference (prod data has edge cases)
    └── Scale difference (load-related)

Common Mistakes to Avoid

  • Not capturing the full request (headers, body, timing) when reproducing
  • Making changes before fully understanding the root cause
  • Not writing a regression test that specifically covers the edge case
  • Investigating alone without checking observability tools (logs, traces, metrics)

Follow-up Questions

  • How do you use distributed tracing to debug cross-service API issues?
  • What tools do you use to capture and replay production traffic safely?
  • How do you handle API-only defects that are intermittent (Heisenbugs)?

Chapter Summary #

Key Takeaways

Domain Critical Concepts
Idempotency Idempotency keys, duplicate detection, at-least-once delivery
Observability Correlation IDs, distributed tracing, audit logs
Resilience Timeouts, retries, circuit breakers, fallbacks
Contracts JSON Schema validation, backward compatibility, versioning
Security Authentication vs authorization, PII exposure, tenant isolation, webhook signatures
Async Patterns 202 responses, eventual consistency, message queues, DLQs
Data Integrity Transaction rollback, partial failure, saga compensation
Performance Pagination, rate limiting, caching, bulk operations

Framework Quick Reference

// REST Assured Setup — Common Base Specification
public class ApiTestBase {
    protected static RequestSpecification baseSpec;

    @BeforeAll
    static void setup() {
        baseSpec = new RequestSpecBuilder()
            .setBaseUri("https://api.example.com")
            .setBasePath("/api/v1")
            .addHeader("Content-Type", "application/json")
            .addFilter(new AllureRestAssured())
            .addFilter(new RequestLoggingFilter())
            .addFilter(new ResponseLoggingFilter())
            .build();
    }

    protected Response authenticatedGet(String path, String token) {
        return given()
            .spec(baseSpec)
            .header("Authorization", "Bearer " + token)
        .when()
            .get(path)
        .then()
            .extract().response();
    }
}

Testing Pyramid for APIs

         ╱╲        E2E/Integration Tests
        ╱  ╲       (Cross-service flows, real dependencies)
       ╱    ╲
      ╱──────╲     Contract Tests
     ╱        ╲    (Pact, JSON Schema, backward compatibility)
    ╱          ╲
   ╱────────────╲  Component Tests
  ╱              ╲ (Single service, mocked dependencies)
 ╱                ╲
╱──────────────────╲ Unit Tests
                     (Business logic, serialization, validation)

Status Code Decision Guide

Scenario Status Code When to Use
Success 200 OK Resource returned/updated
Created 201 Created New resource created
Accepted 202 Accepted Async processing started
No Content 204 No Content Delete successful
Not Modified 304 Cache still valid (ETag match)
Bad Request 400 Validation error, malformed request
Unauthorized 401 Missing/invalid authentication
Forbidden 403 Authenticated but not authorized
Not Found 404 Resource doesn't exist
Conflict 409 Duplicate, optimistic lock failure
Payload Too Large 413 Request body exceeds limit
Unsupported Media 415 Invalid file type
Unprocessable 422 Semantic validation error
Rate Limited 429 Too many requests
Server Error 500 Unhandled exception
Service Unavailable 503 Dependency down, maintenance

Essential Headers for API Testing

Request Headers:
  Authorization: Bearer <token>
  Content-Type: application/json
  Accept: application/json
  X-Correlation-ID: <uuid>
  Idempotency-Key: <uuid>
  If-None-Match: <etag>
  X-Tenant-ID: <tenant>

Response Headers:
  X-Correlation-ID: <uuid>
  X-RateLimit-Limit: 1000
  X-RateLimit-Remaining: 999
  X-RateLimit-Reset: <epoch>
  ETag: "abc123"
  Cache-Control: max-age=300
  Retry-After: 60
  Deprecation: true
  Sunset: Sat, 01 Jan 2027 00:00:00 GMT

Recommended Tool Stack

Layer Tool Purpose
API Testing REST Assured Java-based API test automation
API Testing Postman/Newman Manual exploration + CI collection runs
Mocking WireMock HTTP service virtualization
Contract Pact Consumer-driven contract testing
Schema JSON Schema Validator Response structure validation
Performance k6 / JMeter Load and stress testing
Observability Jaeger/Zipkin Distributed tracing
Monitoring Grafana/Datadog Metrics and alerting

Interview Tips for This Chapter

  1. Always mention observability — Every answer should reference how you'd monitor/trace the behavior in production
  2. Security by default — Mention PII, authentication, and authorization implications even when not directly asked
  3. Think distributed — Assume multi-service architecture; mention race conditions, eventual consistency
  4. Show the negative path — Demonstrate error handling and failure scenarios, not just happy paths
  5. Quantify where possible — Mention SLAs, timeouts, retry counts, and limits with specific numbers
  6. Connect to business impact — Explain WHY a test matters (e.g., "Without idempotency testing, customers could be double-charged")

End of Chapter D: API & Integration Testing

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