Skip to content

Instantly share code, notes, and snippets.

@jaapio
Last active May 28, 2021 17:00
Show Gist options
  • Save jaapio/633ab8e53e059b11caae23c1d9e260c7 to your computer and use it in GitHub Desktop.
Save jaapio/633ab8e53e059b11caae23c1d9e260c7 to your computer and use it in GitHub Desktop.
Ratelimit Symfony messenger
framework:
messenger:
transports:
async:
dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
retry_strategy:
service: App\Symfony\Messenger\Retry\RateLimitHandlingRetryStrategy
<?php
declare(strict_types=1);
namespace App\Symfony\Messenger\Retry;
use App\Provider\Exception\RateLimitException;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Exception\HandlerFailedException;
use Symfony\Component\Messenger\Retry\RetryStrategyInterface;
class RateLimitHandlingRetryStrategy implements RetryStrategyInterface
{
/**
* @var RetryStrategyInterface
*/
private RetryStrategyInterface $retryStrategy;
public function __construct(RetryStrategyInterface $retryStrategy)
{
$this->retryStrategy = $retryStrategy;
}
/**
* @inheritDoc
*/
public function isRetryable(Envelope $message, \Throwable $throwable = null): bool
{
if ($throwable instanceof HandlerFailedException) {
$nestedException = current($throwable->getNestedExceptions());
if ($nestedException instanceof RateLimitException) {
return true;
}
}
return $this->retryStrategy->isRetryable($message, $throwable);
}
/**
* @inheritDoc
*/
public function getWaitingTime(Envelope $message, \Throwable $throwable = null): int
{
if ($throwable instanceof HandlerFailedException) {
$nestedException = current($throwable->getNestedExceptions());
if ($nestedException instanceof RateLimitException) {
return $nestedException->getDelay();
}
}
return $this->retryStrategy->getWaitingTime($message, $throwable);
}
}
services:
messenger.retry.fallback_retry_strategy:
class: Symfony\Component\Messenger\Retry\MultiplierRetryStrategy
arguments:
$maxRetries: 3
$delayMilliseconds: 1000
$multiplier: 1
$maxDelayMilliseconds: 0
App\Symfony\Messenger\Retry\RateLimitHandlingRetryStrategy:
arguments: ['@messenger.retry.fallback_retry_strategy']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment