Laravel에서 외부 API 스로틀 제한 확인 방법
발행: (2026년 1월 10일 오후 02:02 GMT+9)
2 min read
원문: Dev.to
Source: Dev.to
아이디어
- 외부 API를 호출한다.
- 응답 상태가 429 (Too Many Requests)인지 확인한다.
- 레이트‑리밋 헤더를 읽는다(제공되는 경우).
- 스로틀링을 우아하게 처리한다.
구현
기본 스로틀 체크
use Illuminate\Support\Facades\Http;
public function checkApiThrottle()
{
$response = Http::withOptions([
// Prevent exceptions on HTTP errors
'http_errors' => false,
])->get({API-ENDPOINT});
// Check if API is throttling
if ($response->status() === 429) {
return response()->json([
'throttled' => true,
'message' => 'API rate limit exceeded',
'retry_after' => $response->header('Retry-After'),
], 429);
}
// Read rate‑limit headers (if available)
$rateLimit = [
'limit' => $response->header('X-RateLimit-Limit'),
'remaining' => $response->header('X-RateLimit-Remaining'),
'reset' => $response->header('X-RateLimit-Reset'),
];
return response()->json([
'throttled' => false,
'rate_limit_headers'=> $rateLimit,
'data' => $response->json(),
]);
}
최대 호출 횟수를 이용한 대안적 접근법
use Illuminate\Support\Facades\Http;
public function checkApiThrottle()
{
$maxCall = 10;
$count = 0;
$responses = [];
while ($count status();
$count++;
$responses[] = [
'statusCode' => $statusCode,
'count' => $count,
];
// Stop if the request is not successful (e.g., throttled)
if ($statusCode !== 200) {
break;
}
}
echo "" . print_r($responses, true) . "";
}