Skip to the main content
{}
Back to all articles

Technical article

Build API integrations that remain reliable

Design Laravel integrations with timeouts, idempotency, error classification, safe logging, retries and reconciliation.

By Codegenie2 minute read
  • API & integrations
  • Build
  • API
  • integrations
  • that
  • remain
Central API hub connected to other services and dashboards.
In this article

A reliable API integration distinguishes rejected, successful and unknown outcomes. After a timeout, an external invoice may already exist. Recovery and the data contract matter as much as the successful HTTP call.

Model invoice states first

Illustrative invoice flow: persist an internal operation reference as pending before sending. Send only validated fields. For a 2xx response, check invoice ID, currency, amount and status before recording succeeded. An HTML error page returned with status 200 is not a valid invoice response.

  • Validation error: correct input; do not repeat unchanged.
  • 429 or temporary server error: respect provider limits and Retry-After, with bounded attempts for safely repeatable operations.
  • Timeout after sending: mark unknown and look up the operation reference or use documented provider idempotency.

Bound network time before retries

This fragment makes one attempt. The key was persisted earlier and stays the same for one operation; the provider must support it. Laravel may throw ConnectionException for connectivity failures, even with retry(..., throw: false). The RuntimeExceptions below are internal signals that the controller must translate into safe user feedback.

One attempt with an explicit unknown outcomeapp/Http/Clients/BillingClient.phpphp
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;

try {
    $response = Http::connectTimeout(3)
        ->timeout(10)
        ->withToken(config('services.billing.token'))
        ->withHeaders(['Idempotency-Key' => $idempotencyKey])
        ->post(config('services.billing.url').'/invoices', $payload);
} catch (ConnectionException $exception) {
    throw new RuntimeException('Invoice outcome unknown; reconcile before retry.', 0, $exception);
}

if (! $response->successful()) {
    throw new RuntimeException('Classify provider status before retry.');
}

// Validate the response contract before persisting business state.

Local repeatability needs a unique key

Recognise the same provider invoice againapp/Models/Invoice.phpphp
Invoice::query()->updateOrCreate(
    ['provider_id' => $providerInvoice['id']],
    [
        'status' => $providerInvoice['status'],
        'total' => $providerInvoice['total'],
    ],
);

Use updateOrCreate only for validated responses and add a unique database index on provider_id. With multiple providers or accounts, include that scope in both the unique key and the lookup. updateOrCreate alone does not prevent concurrent inserts. Log a correlation ID and error category without tokens or complete customer payloads.

Use Http::fake to test success, invalid 2xx bodies, 422, 429, 5xx and network failure separately. Repeat the same operation and simulate concurrent responses. Verify that recovery finds the existing invoice. These examples are not an executed provider integration.

Example verification: PHP fragments were syntax-checked with PHP 8.5.11. Laravel execution and hosting behaviour were not tested; use a suitable test application and configuration.

Technical deep dive: design retries without duplicating a business action.

Illustrative scenario: an external API responds too slowly, so your application retries. The first request may still have been processed. Adding a retry alone can therefore create a second payment, order or status change.

Technical decision

Make the business action identifiable with a stable idempotency or reference key and store enough state to recognise a repeated attempt safely. Timeouts, explicit errors and unknown outcomes need different follow-up behaviour.

Checks

  • Repeat the exact same request and verify that the business action is not created twice.
  • Simulate a timeout after sending and verify how an unknown external state is reconciled.
  • Verify that failed retries are bounded and log enough context without secrets or personal data.
  • Test webhooks or callbacks out of order and with a duplicate event.

This scenario is generic and does not imply that every provider offers the same idempotency capabilities.

Last updated:

Need technical context for your own project?

Codegenie helps with Laravel applications, existing codebases, shared-hosting deployments and technical improvements.