N+1 queries activity feed

On-call incidentMedium30 min

Your task

After a feature launch that added an 'activity feed' to user dashboards, your DB's read load tripled and dashboard load times went from 300ms to 4s, worst for power users. APM shows the dashboard endpoint issuing 300+ near-identical small queries per request, one SELECT ... WHERE id = ? per feed item, each individually fast (under 1ms) but adding up. The feed query that fetches the item ids is itself quick. CPU is high but not pinned; connection count is elevated. Triage and mitigate.

It covers

  • Index only scan
  • Covering index
  • N+1