제3자 API 충돌 방지: Laravel 작업 스루틀링 🚦

발행: (2026년 5월 4일 PM 01:47 GMT+9)
5 분 소요
원문: Dev.to

Source: Dev.to

Stop Crashing 3rd Party APIs: Throttling Laravel Jobs 🚦의 표지 이미지

API 속도 제한 재앙

스마트 테크 데브스에서 현대 B2B SaaS 개발을 할 때, 애플리케이션이 고립된 상태로 존재하는 경우는 거의 없습니다. Stripe를 통한 결제, Salesforce를 통한 CRM 동기화, Resend를 통한 이메일 캠페인 등 외부 서비스와 지속적으로 통신합니다. Laravel Queues의 엄청난 속도와 이러한 서드파티 API의 엄격한 속도 제한을 결합할 때 아키텍처 함정이 발생합니다.

만약 5,000개의 “Sync Customer” 백그라운드 작업을 디스패치한다면, Laravel Horizon 워커는 CPU가 허용하는 한도 내에서 가능한 빨리 작업을 실행하려고 합니다. 서드파티 API가 분당 50개의 요청만 허용한다면, 첫 번째 50개의 작업은 성공하고, 나머지 4,950개는 즉시 HTTP 429: Too Many Requests 오류와 함께 충돌합니다. 이로 인해 실패한 작업 테이블이 넘쳐나고, Sentry에서 잘못된 알림이 트리거되며, 데이터 동기화가 깨집니다.

엔터프라이즈 솔루션: Redis 작업 미들웨어

지속 가능한 백그라운드 처리를 설계하려면 큐 워커가 외부 경계를 존중하도록 가르쳐야 합니다. 이를 위해 Rate Limiting Middleware를 Redis를 사용해 대기 중인 작업에 직접 적용합니다.

API 제한에 도달했을 때 작업이 충돌하는 대신, 미들웨어가 작업을 안전하게 가로채고 일시 중지한 뒤, 제한이 초기화될 때 다시 시도하도록 큐에 반환합니다.

단계 1: Rate Limiter 정의

먼저 AppServiceProviderboot 메서드에서 외부 API의 엄격한 속도 제한을 정의합니다.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Cache\RateLimiting\Limit;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Define a strict limit: Max 50 requests per minute
        RateLimiter::for('salesforce-api', function ($job) {
            return Limit::perMinute(50);
        });
    }
}

단계 2: 작업에 Middleware 적용

middleware() 메서드를 사용해 특정 rate limiter를 작업 클래스에 연결하고, 제한에 걸렸을 때 작업이 재시도하기 전 대기할 시간을 설정합니다.

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\Middleware\RateLimited;

class SyncCustomerToSalesforce implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tenant;

    // Allow the job to be retried for up to 12 hours
    public $retryUntil;

    public function __construct($tenant)
    {
        $this->tenant = $tenant;
        $this->retryUntil = now()->addHours(12);
    }

    /**
     * Get the middleware the job should pass through.
     */
    public function middleware(): array
    {
        // 1. Apply the Redis limiter we defined in the provider
        // 2. If throttled, release the job back to the queue with a 60‑second delay
        return [
            (new RateLimited('salesforce-api'))->dontRelease()->releaseAfterMinutes(1)
        ];
    }

    /**
     * Execute the job (Safe from 429 errors!)
     */
    public function handle(): void
    {
        // Perform the external API HTTP request here...
        // We guarantee this will only execute 50 times per minute globally.
    }
}

The Architectural ROI

Redis‑backed job throttling을 구현함으로써 혼란스러운 API 통합을 완벽하게 조절되고 탄력적인 데이터 파이프라인으로 변환합니다. 로그에서 429 오류 소음을 제거하고, 공급업체 API 평판을 보호하며, 대규모 데이터 동기화가 안전하게 데이터를 점진적으로 전송하는 데 몇 시간이 걸리더라도 성공적으로 완료되도록 보장합니다.

0 조회
Back to Blog

관련 글

더 보기 »

Laravel에 SB Admin 2 통합

Laravel 11 요구사항 bash php -v >= 8.2 composer -v node -v >= v14.16 npm -v 웹 서버에서 Apache와 MySQL를 시작합니다. Laravel 11을 설치합니다. bash composer create…