Skip to content

Compute has_unread from unread_count in channel and DM lists - #63

Merged
danielcorin merged 1 commit into
danielcorin:mainfrom
filaebot:fix/unread-query-cost
Nov 14, 2026
Merged

danielcorin merged 1 commit into
danielcorin:mainfrom
filaebot:fix/unread-query-cost

Conversation

@filaebot

Copy link
Copy Markdown
Contributor

What

GET /channels and GET /dms computed has_unread with two MAX(m.id) subqueries per channel, on top of the unread_count COUNT subquery. All three used the same filters. This PR derives has_unread as unread_count > 0 and drops the two MAX subqueries.

Why

handleListChannels was the top D1 reader on the dan tenant: 52% of query time, 6,243 calls and 671M rows read in 24h, about 107K rows per call. The MAX subqueries can't use idx_messages_channel, so every request scanned each channel's history three times.

Behavior

No change. A message that qualifies and is newer than the read cursor exists exactly when unread_count > 0. The response shape and wire contract are unchanged.

Verify

  • All 790 API tests pass locally.
  • On staging, check that channel and DM unread badges still look right before deploying to the tenant.

Related

  • filae adapter (filae 5a11159) cut its /channels + /dms refresh from every 30s to every 10 min. That was roughly 45% of the calls.
  • Not in this PR: an index on messages(channel_id, id) WHERE deleted_at IS NULL. It should wait until we've measured the query cost after this lands.

🤖 Generated with Claude Code

The list queries computed has_unread with two MAX(m.id) subqueries per
channel on top of the unread COUNT, all with the same filters. MAX(id)
can't use idx_messages_channel, so every request scanned each channel's
history three times. This query was the top D1 reader on Dan's tenant
(52% of query time, ~107K rows read per call).

A qualifying message newer than the read cursor exists exactly when
unread_count > 0, so the response is unchanged. Wire contract unchanged.
@danielcorin
danielcorin merged commit b4e9c86 into danielcorin:main Nov 14, 2026
3 of 5 checks passed
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.

2 participants