php 51 lines · 7 steps

Resilient HTTP retries with Laravel's client

A service class fetches exchange rates and retries intelligently based on the type of failure.

Explained by highlit
1<?php
2 
3namespace App\Services;
4 
5use Illuminate\Http\Client\ConnectionException;
6use Illuminate\Http\Client\Request;
7use Illuminate\Http\Client\RequestException;
8use Illuminate\Http\Client\Response;
9use Illuminate\Support\Facades\Http;
10use Illuminate\Support\Facades\Log;
11 
12class ExchangeRateClient
13{
14 public function latest(string $base, array $symbols): array
15 {
16 $response = Http::baseUrl(config('services.exchange.url'))
17 ->withToken(config('services.exchange.key'))
18 ->timeout(5)
19 ->acceptJson()
20 ->retry(4, 200, function (\Exception $exception, Request $request) {
21 if ($exception instanceof ConnectionException) {
22 return true;
23 }
24 
25 if ($exception instanceof RequestException) {
26 Log::warning('Exchange rate request failed, retrying.', [
27 'status' => $exception->response->status(),
28 'endpoint' => $request->url(),
29 ]);
30 
31 return $exception->response->status() === 429
32 || $exception->response->serverError();
33 }
34 
35 return false;
36 }, throw: true)
37 ->get('/v1/latest', [
38 'base' => $base,
39 'symbols' => implode(',', $symbols),
40 ]);
41 
42 return $this->normalize($response);
43 }
44 
45 protected function normalize(Response $response): array
46 {
47 return collect($response->json('rates', []))
48 ->map(fn (float $rate) => round($rate, 6))
49 ->all();
50 }
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A retry callback lets you decide per-exception whether an error is worth retrying instead of blindly repeating every request.
  2. 2Distinguishing transient failures (connection drops, 429s, 5xx) from permanent ones avoids hammering an API on unrecoverable errors.
  3. 3Isolating the fetch and its response shaping keeps external-API quirks from leaking into the rest of the app.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Resilient HTTP retries with Laravel's client — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code