Laravel / Application boundaries and reliable workflows / Lesson 14
Outbound HTTP: timeouts and failure contracts
Bound external requests and translate upstream failures into explicit application behavior.
On this page
Lesson goals
- Set separate connection and total request limits.
- Distinguish transport failures from HTTP error responses.
- Test retries and safe response handling with a fake client.
- Set and assess connection, request, retry, and caller-level time budgets.
- Classify status, transport, body, and uncertain-write failures and test their final application outcomes.
Model an external dependency
An outbound HTTP call crosses a network and a service ownership boundary. Even a successful response can arrive slowly, contain an unexpected shape, or represent data that is no longer current. Define the caller’s deadline, the acceptable response fields, and what the application should do when the dependency is unavailable. Avoid forwarding provider error bodies or credentials directly to a public client. Keep the operation testable without contacting a real external system.
Bound waiting time
The following fragment uses Laravel’s HTTP client with distinct connection and overall timeout settings. The values are illustrative, not universal production recommendations; choose budgets from the calling request’s deadline and measured dependency behavior. A connection timeout concerns establishing the connection, while the request timeout bounds the request wait. Handle connection exceptions at the application boundary and leave enough time to return an intentional response.
use Illuminate\Support\Facades\Http;
$response = Http::connectTimeout(2)->timeout(5)
->get('https://example.com/api/status');
The endpoint is reserved for examples. These limits need adjustment to the real operation and its caller deadline.
Classify the outcome
Laravel’s HTTP client does not automatically throw solely because a response has a client or server error status. Inspect the status or deliberately call throw when an exception is appropriate. The example checks a successful response and selects a field only after inspecting the result. Validate the returned shape before passing it into domain logic; a 200 response is not proof that an upstream contract remains correct.
use Illuminate\Support\Facades\Http;
Http::fake(['example.com/*' => Http::response(['state' => 'ready'], 200)]);
$response = Http::get('https://example.com/api/status');
$state = $response->successful() ? $response->json('state') : null;
The fake isolates the client from the network. Production code should also validate the body and map connection failures.
Make retry safety explicit
Retries can help transient failures, but multiply load and consume the caller’s deadline. A timed-out write may already have succeeded upstream; retrying it without an agreed idempotency mechanism can duplicate a charge or message. Retry only bounded, classified failures for operations whose semantics permit it, with a provider-supported stable key where needed. Define what happens when the retry budget is exhausted and avoid printing secrets in logs.
Exercise controlled failures
Use a fake HTTP response to test the integration’s mapping without reaching the network, then assert the requested URL and intended response handling. Add cases for a rejected status, malformed successful body and a connection exception. A fake cannot establish real DNS, TLS, latency or provider behavior; use a separate approved integration environment for those boundaries. Track the final user outcome rather than calling every upstream failure a successful request.
Define the caller deadline and dependency contract
An outbound HTTP call crosses a network and an ownership boundary. Define what the caller needs, which fields and types are acceptable, how long the entire operation may take, and what the application returns if the dependency is unavailable. A connection timeout limits time spent establishing a connection; a request timeout limits the wait for an individual request. Neither value is a universal production recommendation. Leave time for application processing and a safe response, and include every retry and delay in the caller's overall budget rather than configuring attempts independently.
For example, a caller with a ten-second total budget cannot safely promise three five-second attempts plus two one-second delays. A conservative upper-bound calculation is seventeen seconds before local processing, so the policy must change or the work must move to a suitably designed asynchronous flow. Actual network timing and client behavior must be measured in an approved integration environment. The Laravel 12 fragments here use synthetic endpoints and fakes or require the stated application; they are illustrative, non-runnable, and have not contacted any service.
Classify transport, status, and body failures
A transport failure such as an inability to connect is different from receiving an HTTP response with status 404, 429, or 500. Laravel's HTTP client does not automatically throw solely for a client or server error status unless the code deliberately asks it to do so. Inspect the response or use throw with an intentional exception-mapping policy. A 200 response is also not proof of a valid business value: verify that required fields exist, have the expected types and allowed values, and are suitable for the operation before writing local state.
Map failure categories to application outcomes instead of passing an upstream body directly to a public client. A provider's error text can contain internals, identifiers, or other sensitive information; log a sanitized category and correlation identifier where needed. Treat a missing record according to the provider and product contract rather than assuming every 404 means the same thing. Test a successful body, an error status, a connection exception, and malformed success separately so a passing status test cannot hide a body or network failure.
Retry only when the operation and budget permit it
Retries add attempts, waiting time, and load on the dependency. Classify which failures are plausibly transient and bound the number of attempts and delays. An HTTP validation rejection may require correcting the request rather than repeating it, while a temporary connection failure may be retryable under the integration's documented contract. Laravel's retry behavior and exception handling should be verified for the configured call; use a fake sequence to prove the application's mapping and exhaustion path. Backoff and jitter are design choices, not a guarantee that a dependency will recover.
A timed-out write has an uncertain outcome: the provider may have committed the operation even though the client did not receive the response. Do not blindly repeat a charge or other non-idempotent effect. Where the provider supports it, send the same durable operation key on every attempt and reconcile the result using the provider's documented protocol. A newly generated key on retry can create a second operation. A local database transaction cannot roll back an unrelated remote service; define pending, confirmed, and uncertain outcomes and test them explicitly.
Validate destination, credentials, and returned data
Treat an external URL and the response as separate trust boundaries. Select the destination from application configuration or a strict allowlist, not an arbitrary user-provided URL that could reach internal services. Keep credentials in the application's secret configuration and send them using the provider's documented mechanism; never copy authorization headers, access tokens, or full sensitive response bodies into logs. Redirect behavior, proxy configuration, TLS verification, and provider certificates belong to the real integration configuration and need their own controlled evidence.
Parse and validate the response before domain work. For a status endpoint, require a recognized string such as ready or pending and reject a missing field, an array, or an unknown value according to the application's contract. If an upstream response contains extra fields, select only what the application needs rather than forwarding it wholesale. A fake HTTP client can exercise the application's transformation and confirm a request shape, but it does not establish DNS, TLS, provider latency, or actual remote semantics. Use synthetic data and avoid real credentials in every example.
Test the final outcome, not only the outbound call
Build a disposable test matrix for a valid 200 response, an upstream 4xx or 5xx, a connection failure, an invalid 200 body, a transient failure followed by success, and retry exhaustion. For each case assert the user-facing response or job state and whether a local write is permitted. Verify the destination and safe request fields with Http::assertSent where useful, and assert that secrets and raw provider errors do not appear in the response. Use a fake sequence and a controlled clock or test configuration rather than contacting a live provider or waiting on real timeouts.
A fake proves only the behavior of the application against the configured fake; it cannot establish a provider's idempotency guarantee or reproduce actual network timing. Test the real adapter separately in an approved isolated integration environment using synthetic accounts and the provider's documentation. Observe operation identity, attempts, failure class, and elapsed budget without logging secrets. On an uncertain remote write, choose a reconciliation or review path before declaring success or retrying. Record the tested client version, retry configuration, and omitted boundaries so the evidence remains interpretable.
20 worked examples
1. Separate timeout limits
Problem: Configure distinct connection and overall limits for a status request.
- The connection limit bounds the connection phase while the request timeout bounds the individual request wait.
- The selected limits must still fit inside the caller’s total budget and leave time to respond.
$response = Http::connectTimeout(2)->timeout(5)
->get('https://service.example.test/status');
// Fixture: configured Laravel client; values are illustrative seconds.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The request uses a 2-second connection limit and 5-second request limit.
Why this result follows: Explicit limits make the network waiting policy visible without claiming the synthetic endpoint was called.
2. Valid fake response
Problem: Read a required state from a successful synthetic HTTP response.
- The fake returns status 200 and a state field containing ready.
- The success branch reads that field without making an external request.
Http::fake(['service.example.test/*' => Http::response(['state' => 'ready'], 200)]);
$response = Http::get('https://service.example.test/status');
$state = $response->successful() ? $response->json('state') : null;
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: $state is ready in the stated fake fixture.
Why this result follows: A controlled fake isolates status handling while preserving the response shape being examined.
3. HTTP 500 is still a response
Problem: Classify a server error without assuming an automatic exception.
- The fake returns a response with status 500.
- The client returns a response object unless the code invokes an exception path such as throw.
Http::fake(['service.example.test/*' => Http::response(['error' => 'unavailable'], 500)]);
$response = Http::get('https://service.example.test/status');
$ok = $response->successful();
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: $ok is false; the application must map the failure.
Why this result follows: A server-error status and a transport exception are distinct HTTP client outcomes.
4. Explicit throw and mapping
Problem: Convert an upstream server error into an intentional application response.
- The throw call converts the unsuccessful HTTP response into a request exception.
- The catch branch returns a controlled public message rather than the provider body.
try {
Http::timeout(3)->get($url)->throw();
} catch (RequestException $e) {
return response()->json(['error' => 'dependency unavailable'], 503);
}
// Fixture: upstream returns 500; imports and application route configured.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The configured application response is 503 with a generic error.
Why this result follows: Explicit exception mapping prevents an upstream server error from being mistaken for success.
5. Connection failure
Problem: Handle a failed connection separately from an HTTP status.
- No valid HTTP response is available when the connection fails.
- The connection exception branch maps the transport failure to the chosen application response.
try {
$response = Http::connectTimeout(2)->timeout(5)->get($url);
} catch (ConnectionException $e) {
return response()->json(['error' => 'dependency unavailable'], 503);
}
// Fixture: fake client raises a connection exception.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The application returns the configured 503 error.
Why this result follows: A transport exception requires its own path rather than a status check on a nonexistent response.
6. Missing field in a 200
Problem: Reject a successful status with an incomplete body.
- The status is successful but the required state field is absent.
- The missing value violates the application contract and must not be passed to the write operation.
Http::fake(['service.example.test/*' => Http::response([], 200)]);
$response = Http::get('https://service.example.test/status');
$state = $response->json('state');
// Contract: state must be a recognized string before any local write.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The integration reports an invalid upstream body and performs no write.
Why this result follows: HTTP success does not establish that the body satisfies the downstream business contract.
7. Wrong field type
Problem: Reject an array where a status string is required.
- The fake response contains state but gives it an array value.
- A type check rejects that value before any domain decision uses it.
Http::fake(['service.example.test/*' => Http::response(['state' => ['ready']], 200)]);
$response = Http::get('https://service.example.test/status');
$state = $response->json('state');
// Contract: state is a string, not an array.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The integration treats the response as invalid.
Why this result follows: Presence alone is insufficient when the public dependency contract also requires a specific type.
8. Unknown state value
Problem: Reject a well-typed but unsupported upstream status value.
- The state is a string but is not one of the two recognized values.
- The validation branch rejects it before the application treats it as ready.
$state = $response->json('state');
if (! is_string($state) || ! in_array($state, ['ready', 'pending'], true)) {
throw new UnexpectedValueException('Invalid upstream state');
}
// Fixture: 200 response body has state='retired'.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The integration raises its controlled invalid-state failure.
Why this result follows: An allowlist protects domain decisions from unexpected but well-typed provider values such as retired.
9. Transient failure then success
Problem: Exercise a bounded retry with a fake response sequence.
- The first fake response is a temporary 503.
- The configured second attempt receives the ready response within the stated retry count.
Http::fakeSequence('service.example.test/*')
->push(['error' => 'temporary'], 503)
->push(['state' => 'ready'], 200);
$response = Http::retry(2, 100)->get('https://service.example.test/status');
// Fixture: this read is safe to retry and retry configuration permits 503.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The final response has status 200 and state ready.
Why this result follows: A bounded fake sequence makes the application’s retry path observable without real network traffic.
10. Retry exhaustion
Problem: Map failure after all configured attempts are exhausted.
- Both configured attempts receive the synthetic 503 response.
- The exhausted retry path raises the request exception under the stated default retry behavior.
Http::fake(['service.example.test/*' => Http::response([], 503)]);
try {
Http::retry(2, 100)->get('https://service.example.test/status');
} catch (RequestException $e) {
return response()->json(['error' => 'dependency unavailable'], 503);
}
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The application returns its generic 503 response.
Why this result follows: The caller receives a defined failure after a finite attempt budget rather than waiting indefinitely.
11. Budget arithmetic
Problem: Compare retry timing with a caller deadline before choosing a policy.
- The three attempt limits sum to fifteen seconds.
- Adding two seconds of delay gives a conservative seventeen-second bound before local processing.
caller budget: 10 seconds
attempts: 3 × 5 seconds maximum
delays: 2 × 1 second
local processing reserve: not yet included
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The proposed policy exceeds the ten-second caller budget.
Why this result follows: Retry count, attempt timeouts, and delays must be considered together as one end-to-end budget.
12. Timed-out remote write
Problem: Treat a POST timeout as an uncertain outcome, not proof of failure.
- The client did not receive a definitive response, but the provider may have completed the charge.
- Consult the provider-supported idempotency and reconciliation contract before retrying with the same operation key.
operation: charge invoice 17
POST attempt: submitted with key op-17
client result: connection timeout
provider outcome: unknown
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The local operation remains uncertain until reconciled.
Why this result follows: A timeout describes missing client confirmation and does not establish that a remote side effect was rolled back.
13. Stable idempotency key
Problem: Reuse a provider-supported key for repeated attempts of one operation.
- The key identifies the same synthetic charge across attempts.
- A retry must reuse that key and the agreed operation payload rather than generate a new identity.
$key = 'invoice-17-charge';
$response = Http::withHeaders(['Idempotency-Key' => $key])
->timeout(5)->post($providerUrl, ['invoice_id' => 17]);
// Fixture: provider explicitly supports this key contract.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: Repeated attempts carry invoice-17-charge.
Why this result follows: A stable provider-supported key can let the remote owner recognize the repeated business operation.
14. Do not retry a validation rejection
Problem: Stop a classified permanent request error instead of repeating it.
- The provider returned a response identifying invalid request data.
- Under the stated provider contract, repeating the same payload cannot repair that validation problem.
$response = Http::post($providerUrl, ['amount' => -1]);
if ($response->status() === 422) {
return response()->json(['error' => 'invalid request'], 422);
}
// Fixture: provider contract identifies 422 as a non-retryable validation error.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The application returns its mapped validation failure without an automatic retry.
Why this result follows: Retry classification must follow the operation and provider contract rather than treating every failure as transient.
15. Destination allowlist
Problem: Reject an arbitrary client-provided URL for an internal integration.
- The lookup accepts only names defined by the application-owned provider map.
- The unknown input has no configured destination and is rejected before an HTTP request.
$providers = ['status' => config('services.status.url')];
$url = $providers[$request->input('provider')] ?? null;
abort_unless($url !== null, 422);
// Fixture: configured status URL is trusted; input provider='unknown'.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The request is rejected with 422 and no outbound call.
Why this result follows: Selecting from trusted destinations prevents arbitrary input from becoming a network target.
16. Safe public error
Problem: Avoid exposing an upstream error body to the API caller.
- The server-error branch records a broad sanitized category.
- The public response contains a generic message rather than the provider’s internal body.
if ($response->serverError()) {
Log::warning('Status provider failed', ['category' => 'upstream_5xx']);
return response()->json(['error' => 'dependency unavailable'], 503);
}
// Fixture: provider body contains an internal diagnostic string.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The caller receives 503 without the internal diagnostic.
Why this result follows: Error mapping separates operational diagnosis from potentially sensitive upstream content in the public response.
17. Assert the outgoing request
Problem: Verify the destination and safe payload using a fake client.
- The fake prevents a network call while allowing the client to build a request.
- The assertion checks the expected synthetic destination for record 17.
Http::fake(['service.example.test/*' => Http::response(['state' => 'ready'], 200)]);
$client->checkStatus(17);
Http::assertSent(fn ($request) => $request->url() === 'https://service.example.test/status/17');
// Fixture: StatusClient uses the fake HTTP facade.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The test expects one matching status request.
Why this result follows: Request assertions verify the application’s outgoing contract without establishing real provider behavior or availability.
18. Fake connection exception
Problem: Exercise a transport failure without contacting the provider.
- The fake causes the outbound client to encounter a connection failure.
- The route maps that synthetic failure to the declared unavailable response.
Http::fake(['service.example.test/*' => Http::failedConnection()]);
$response = $this->getJson('/api/status/17');
$response->assertServiceUnavailable();
// Fixture: integration maps connection exceptions to 503.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The feature test expects 503 and no real network call.
Why this result follows: A controlled transport fake tests application error handling while leaving real DNS and TLS untested.
19. No write after malformed body
Problem: Assert that an invalid upstream success cannot mutate local state.
- The fake returns a 200 response without the required state field.
- The response and database assertions check failure mapping and unchanged state separately.
Http::fake(['service.example.test/*' => Http::response([], 200)]);
$this->postJson('/api/sync/17')->assertServiceUnavailable();
$this->assertDatabaseHas('records', ['id' => 17, 'state' => 'pending']);
// Fixture: missing state is mapped to 503; record starts pending.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The test expects 503 and record 17 still pending.
Why this result follows: A state assertion detects an incorrect local write even when the status response looks safe.
20. Fake versus real integration
Problem: State what a fake response can and cannot establish.
- The fake supplies the specified status and body to the application.
- It does not exercise the network or the provider’s actual behavior.
Http::fake(['service.example.test/*' => Http::response(['state' => 'ready'], 200)]);
$result = $client->checkStatus(17);
// Fixture: no DNS, TLS handshake, or provider service is contacted.
Illustrative fragment requiring the stated application and fake fixtures; it has not contacted a network service.
Expected result: The application transformation can be tested; real transport remains unproven.
Why this result follows: Evidence from a fake is limited to the configured simulated boundary and application code exercised.
Common errors and fixes
An upstream 500 is treated as a successful result
- Why it happens
- The response object was assumed to throw on every error status.
- How to fix it
- Inspect the status or deliberately throw and map the exception.
- Prevent it next time
- Test both success and error status responses.
A retry duplicates a remote write
- Why it happens
- The first attempt completed after the caller timed out.
- How to fix it
- Use provider-supported idempotency and reconcile uncertain outcomes.
- Prevent it next time
- Test duplicate attempts with the same operation key.
A request waits beyond its caller deadline
- Why it happens
- Timeouts and retry delay were selected independently.
- How to fix it
- Set a total budget and bound each attempt and delay.
- Prevent it next time
- Exercise timeout and exhaustion paths in tests.
20 practice exercises
1. A remote POST times out after submission. May it be sent again immediately?
Show hint
A timeout can mean the remote write succeeded without a received response.
Show worked solution
Not without understanding the provider’s idempotency contract. The first attempt might have completed. Reuse a stable supported operation key, reconcile the outcome where possible, and limit retries and total waiting time.
Treat the charge or other POST outcome as uncertain rather than immediately assuming failure. Follow the provider’s idempotency contract, reuse the same stable operation key if supported, and reconcile the result before deciding whether a bounded retry is safe. Define an exhaustion or review path and include all attempts and delays in the caller budget.
Check your solution
- The original operation key is preserved for a supported retry.
- The uncertain outcome is reconciled or handled explicitly.
2. A fake returns status 200 with a missing field. What should the application verify?
Show hint
Check the required field and its type before any domain effect.
Show worked solution
Validate the required field and its type before using it. Return or record an intentional dependency failure if the contract is violated, and assert that no downstream write occurs. A successful status alone is insufficient.
A 200 status is insufficient when the response lacks the required state. Validate presence, type, and allowed values, then map a contract violation to an intentional dependency failure. Test the missing field with a fake and verify that no downstream database write occurred.
Check your solution
- The missing required field is rejected.
- The local state remains unchanged.
3. A caller has ten seconds for two five-second attempts and one one-second delay. Assess the budget.
Show hint
Include every attempt, delay, and local processing.
Show worked solution
The conservative attempt and delay total is eleven seconds before local processing, already exceeding the ten-second caller budget. Reduce the attempt limits or count, adjust the overall design, or use a suitable asynchronous workflow. Measure real behavior in a controlled environment and reserve time for an intentional response.
Check your solution
- The proposed total is at least 11 seconds.
- The revised plan fits the caller deadline.
4. A status request has connection timeout 2 and request timeout 5. Explain the separate limits.
Show hint
Connection establishment and the request wait differ.
Show worked solution
The connection timeout limits the time allowed to establish the connection, while the request timeout bounds an individual request wait. Select both using the caller deadline and observed dependency behavior; these example numbers are not universal recommendations. Test the connection-failure mapping separately from an HTTP error response.
Check your solution
- The connection phase has its own limit.
- The individual request has an overall limit.
5. A fake upstream response is HTTP 500. Why must the application inspect or throw explicitly?
Show hint
An HTTP response is different from a connection exception.
Show worked solution
Laravel’s HTTP client normally returns a response object for an error status instead of automatically throwing solely because of that status. Check successful or serverError, or deliberately call throw and map the exception. Assert a generic user-facing failure and avoid exposing the provider body.
Check your solution
- The 500 is classified as failure.
- The provider body is not exposed publicly.
6. A connection exception occurs before any HTTP response. Design the application error path.
Show hint
There may be no response status to inspect.
Show worked solution
Catch the appropriate connection exception at the integration boundary and map it to the endpoint or job’s documented unavailable outcome. Test the path with a fake connection failure and assert no unintended local write. Preserve sanitized diagnostics without recording credentials or session-like secrets.
Check your solution
- The connection failure is handled separately.
- No unintended local effect occurs.
7. A provider returns 200 with state missing. Specify validation and state assertions.
Show hint
Success status does not prove a valid body.
Show worked solution
Require the state field to exist, have the expected type, and belong to the supported values before applying domain work. Simulate a missing field in a fake 200 response and assert a controlled dependency failure plus unchanged synthetic database state. Test a valid state separately to prove the integration can succeed.
Check your solution
- The missing field is rejected.
- The local record remains unchanged.
8. A provider returns state as an array instead of a string. Design a negative test.
Show hint
Check type as well as field presence.
Show worked solution
Return a fake 200 body with state=["ready"] and run the integration through its configured boundary. Assert the application rejects the body as invalid and does not treat the array as a valid ready state. Include a separate string ready case and inspect the resulting user response and durable state.
Check your solution
- The array is rejected.
- A valid ready string follows the intended path.
9. A safe read receives 503 then 200. Design a bounded fake retry test.
Show hint
Use a sequence and a finite attempt budget.
Show worked solution
Configure a fake sequence that returns the transient 503 followed by a valid 200 body, and use the application’s documented retry policy for the safe read. Assert the final response and intended number of outbound attempts. Test exhaustion separately so the suite does not assume every dependency recovers.
Check your solution
- The second fake response succeeds.
- Retry count remains within the configured bound.
10. Both permitted attempts return 503. Specify the exhausted outcome and assertions. explicitly.
Show hint
A finite retry budget needs a final failure.
Show worked solution
Configure the fake to return 503 for all allowed attempts and assert the application maps exhaustion to its documented unavailable response. Verify the attempt count, absence of a local success write, and sanitized logging. Avoid asserting a live provider behavior from a fake sequence.
Check your solution
- The application returns its defined failure.
- No success state is persisted.
11. A remote charge POST times out after submission. May it be retried immediately?
Show hint
The provider may already have completed the operation.
Show worked solution
Treat the outcome as uncertain until the provider’s idempotency and reconciliation contract is understood. If supported, reuse the same stable operation key for a bounded retry and reconcile the result; otherwise follow the documented review or recovery path. Do not generate a new key and blindly submit another charge.
Check your solution
- The uncertain outcome is recorded.
- A retry uses the original supported operation key.
12. A provider supports Idempotency-Key for invoice 17. Design a retry identity test.
Show hint
One business operation needs one durable key.
Show worked solution
Assign a stable key such as invoice-17-charge before the first attempt and reuse it with the same intended payload on retries under the provider contract. Use a fake to assert both outgoing attempts carry the same synthetic key. A fake does not prove that the real provider honors idempotency.
Check your solution
- Both attempts carry the same key.
- The provider guarantee remains a separate integration concern.
13. A provider returns 422 for invalid input. Explain whether to repeat the same payload.
Show hint
Classify the failure using the provider contract.
Show worked solution
If the provider documents 422 as a permanent validation rejection, do not automatically retry the unchanged payload. Map it to an appropriate application error and correct the input or business condition. Test that no retry occurs for this classified case and avoid exposing private provider diagnostics.
Check your solution
- The unchanged 422 request is not automatically retried.
- The public error is controlled.
14. A client supplies an arbitrary URL for a status check. Design a safer destination rule.
Show hint
The network target should be application owned.
Show worked solution
Map a small allowed provider name to an application-configured endpoint and reject unknown names before making any request. Test an unknown synthetic name and assert that the HTTP fake recorded no outbound call. Review redirect and network policies separately for the selected integration.
Check your solution
- Unknown provider names are rejected.
- No outbound call occurs for the rejected input.
15. An upstream 500 body contains an internal stack trace. Define public and operational responses.
Show hint
Do not forward the provider body.
Show worked solution
Return a generic dependency-unavailable error under the application’s response contract and record a sanitized failure category or correlation identifier. Do not log credentials, full sensitive payloads, or the raw stack trace in a public response. Test the response for absence of the synthetic internal diagnostic.
Check your solution
- The public response is generic.
- The internal diagnostic is absent from it.
16. A status client should request /status/17. Show how to verify its outgoing contract safely.
Show hint
Use an HTTP fake and a request assertion.
Show worked solution
Fake the synthetic provider host, invoke the client with record 17, and assert that the recorded request uses the intended URL and allowed method or payload. Check the mapped result as well. This verifies application request construction without contacting the provider or proving its real availability.
Check your solution
- The recorded URL ends in /status/17.
- No real provider is contacted.
17. A fake returns 200 with a valid state but an extra private provider field. Define the output contract.
Show hint
Select the required fields rather than forwarding the body.
Show worked solution
Validate the recognized state and construct the application response from approved fields only. Include an extra synthetic internal field in the fake body and assert that it does not appear in the client response or logs. Test the missing and wrong-type state cases separately.
Check your solution
- The valid state is processed.
- The extra internal field is not exposed.
18. A retry policy sleeps longer than the remaining caller budget. What should happen?
Show hint
The deadline includes delay as well as request time.
Show worked solution
Before another attempt, compare the remaining overall budget with the planned delay, request limit, and response reserve. Stop or choose a documented asynchronous recovery path when the attempt cannot fit. Test exhaustion using controlled timing or configuration rather than waiting for real network timeouts.
Check your solution
- The next attempt is not started beyond the budget.
- The caller receives the defined exhaustion outcome.
19. A fake test passes but production has TLS failures. What evidence was missing?
Show hint
A fake does not perform a real handshake.
Show worked solution
The fake established only the application behavior against a simulated response; it did not test DNS, certificates, TLS negotiation, proxy settings, or provider availability. Use an approved isolated integration environment with synthetic credentials to investigate the real adapter and transport. Avoid weakening certificate verification to make the test pass.
Check your solution
- The fake’s transport limit is stated.
- The real integration is investigated in isolation.
20. An upstream body is malformed after a local record was changed. Design a regression test.
Show hint
Response validation must precede the protected local effect.
Show worked solution
Start with a synthetic pending record, fake a 200 response missing the required field, and invoke the sync endpoint. Assert the documented dependency failure and reload the record to confirm it remains pending. Test a valid response separately so an always-failing integration cannot satisfy the suite.
Check your solution
- The malformed response is rejected.
- The original record state remains pending.
Key takeaways
- Set explicit time and retry budgets at network boundaries.
- Test status, transport and body failures independently.
- An HTTP error response, a connection exception, and an invalid success body are different failure classes.
- A timed-out remote write can have completed and needs a provider-supported idempotency or reconciliation contract.
- A fake verifies application behavior against a simulation, not real DNS, TLS, or provider guarantees.