Skip to content

perf: batch-load reaction counts for posts embedded in discussion endpoints#105

Merged
imorland merged 3 commits into2.xfrom
im/fix-discussion-list-n1-queries
Mar 31, 2026
Merged

perf: batch-load reaction counts for posts embedded in discussion endpoints#105
imorland merged 3 commits into2.xfrom
im/fix-discussion-list-n1-queries

Conversation

@imorland
Copy link
Copy Markdown
Member

Problem

When the reactions extension is active, loading the discussion list triggered 3 extra queries per discussion — one for reaction counts, one for the actor's reaction, and one for all reaction types. With 20 discussions on a page, that's 60 additional queries.

The existing beforeSerialization hook on PostResource::Index correctly batches these queries when posts are loaded directly (e.g. when opening a discussion). However, it does not fire when posts are embedded as firstPost/lastPost within discussion responses — the DiscussionResource::Index and DiscussionResource::Show endpoints have no equivalent hook.

Solution

Add beforeSerialization hooks on DiscussionResource::Index and DiscussionResource::Show that collect the embedded firstPost/lastPost models and pass them all to LoadReactionCounts::forPosts() in a single batch before serialization begins.

  • Index: collects firstPost from all discussions in the result set — 3 queries total regardless of page size
  • Show: collects firstPost and lastPost from the single discussion — 3 queries total

Changes

  • extend.php: add beforeSerialization on DiscussionResource::Index and DiscussionResource::Show

Relates to flarum/framework#4502

…points

When reactions are displayed on the discussion list or discussion show page,
the firstPost (and lastPost on show) are serialized as embedded resources.
The existing beforeSerialization hook on PostResource::Index only fires for
direct post listing requests, not for posts embedded within discussions.

Add beforeSerialization hooks on DiscussionResource::Index and Show to
pre-load reaction counts for all embedded posts in a single batch query,
eliminating per-post reaction queries (3 queries per discussion previously).
@imorland imorland marked this pull request as ready for review March 31, 2026 22:39
@imorland imorland requested a review from a team as a code owner March 31, 2026 22:39
@imorland imorland merged commit b90b252 into 2.x Mar 31, 2026
20 checks passed
@imorland imorland deleted the im/fix-discussion-list-n1-queries branch March 31, 2026 22:39
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.

1 participant