Skip to content

fix(backend): Eliminate N+1 queries for reaction_added events#385

Draft
sentry[bot] wants to merge 1 commit intomainfrom
seer/fix/n-plus-1-reaction-added
Draft

fix(backend): Eliminate N+1 queries for reaction_added events#385
sentry[bot] wants to merge 1 commit intomainfrom
seer/fix/n-plus-1-reaction-added

Conversation

@sentry
Copy link
Copy Markdown

@sentry sentry bot commented Mar 23, 2026

This PR addresses an N+1 query issue occurring during the processing of reaction_added events, specifically when saving messages.

Problem:
When a reaction_added event with multiple receivers was processed, the AwardService::gibToUser() method would save messages in a loop. Each saveOrFail() call triggered CakePHP's ORM validation rules (existsIn for sender_user_id and receiver_user_id) defined in MessagesTable::buildRules(). This resulted in two SELECT 1 queries to check for user existence for each message being saved, leading to an N+1 query pattern (where N is the number of receivers).

Solution:
Since the fromUser and toUser entities are already loaded and their existence is guaranteed before gibToUser() is called, the ORM's existsIn validation checks are redundant. The fix involves:

  1. Passing ['validate' => false] to the saveOrFail() method in AwardService::gibToUser(). This bypasses the unnecessary ORM-level existence checks.
  2. Adding a comment to MessagesTable::buildRules() to clarify that while the existsIn rules are defined, they can be conditionally skipped when the caller guarantees entity existence, relying on database-level foreign key constraints for referential integrity.

This change significantly reduces the number of database queries for reaction_added events with multiple receivers, improving performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants