Skip to content

Optimize Feed Query N+1 Problem #38

Description

@Techhackontime999

Description

The feed page makes 30+ database queries per page due to N+1 query problems - each post triggers separate queries for likes, comments, and user data.

Steps to Reproduce

  1. Enable Django Debug Toolbar or SQL logging
  2. Navigate to the feed page
  3. Count the number of SQL queries executed
  4. Notice 30+ queries for 10 posts (should be <10)

Expected Behavior

The feed should use at most 3-5 queries regardless of the number of posts, using select_related and prefetch_related for all related data.

Root Cause

The feed view doesn't use select_related for user and prefetch_related for likes, comments, or �ttachments.

Files to Fix

  • linkup/feed/views.py - Optimize the feed queryset with:
    • select_related('user', 'user__profile')
    • prefetch_related('likes', 'comments__user', 'attachments')
  • linkup/feed/models.py - Add likes_count and comments_count properties using annotated queries

Acceptance Criteria

  • Feed page uses <10 queries for 10 posts
  • Like counts, comment counts, and user data load in bulk
  • No visible change in functionality
  • Performance improvement measurable with debug toolbar

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    backendBackend/API workbugSomething isn't workingenhancementNew feature or requestintermediateIntermediate level

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions