Vojta BrtníkVojta Brtník

Sentry event filter

Want to avoid exceeding your Sentry API request limit and gain better control over what gets sent?

February 6, 2025|2 minutes read

Sentry event filter

Have you ever run into hitting your API request limit in Sentry? Want to avoid that and gain better control over what gets sent? Using the before_send callback, you can add the ability to filter outgoing events in Sentry and keep it more under control.

In your Sentry config, it might look something like this:

\Sentry\init([
    'dsn' => 'https://examplePublicKey@o0.ingest.sentry.io/0',
    'before_send' => $this->beforeSendFilter->filter(...),
]);

Your custom BeforeSendFilter will track the number of errors sent with the same fingerprint in its history. If I go over the set limit, I'll ignore the error, since Sentry already knows about it. When releasing a new version of the app, it's a good idea to clear the counter state.

private function getEventFingerprint(\Sentry\Event $event, ?\Sentry\EventHint $hint): string
{
    $parts = [];
    if ($hint !== null && $hint->exception !== null) {
        $parts[] = $hint->exception->getFile();
        $parts[] = $hint->exception->getLine();
    } else {
        $parts[] = $event->getMessage();
    }

    return md5(serialize($parts));
}

private function isOverLimit(string $eventFingerprint): bool
{
    ...
}

private function increaseCounter(string $eventFingerprint): void
{
    ...
}

public function filter(\Sentry\Event $event): ?\Sentry\Event
{
    $eventFingerprint = $this->getEventFingerprint($event);
    if ($this->isOverLimit($eventFingerprint)) {
        return null;
    }
    $this->increaseCounter($eventFingerprint);

    return $event;
} 

This approach helps minimize unnecessary API requests, reduce costs, and keep error reporting in Sentry cleaner.

Interested in frontend news?

Sign up for our newsletter or follow us on social media.