Missing index on turns.state slows down scheduler queries

Open Beginner friendly
#379 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
72/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
sql
Domain
databases

Research direction

Start by locating the turns table schema and the project's database migration entry point, then inspect how existing indexes are defined. Add the partial index covering queued and running turns ordered by created_at, and verify the scheduler query uses it without breaking migration or schema checks.

Written by the indexing model from the issue text.

Description

Hey, was poking around the schema and noticed the turns table has indexes on (orgId, storyId, createdAt) and a few unique ones, but nothing on state alone or (state, createdAt).

The scheduler needs to find all queued turns globally:

SELECT * FROM turns WHERE state = 'queued' ORDER BY created_at LIMIT 10;

Without an index on that, it's a full table scan. Not a big deal when you've got a handful of turns, but as the system grows this becomes the bottleneck for turn dispatch.

Easy fix - a partial index that only covers active states:

CREATE INDEX turns_state_created_idx ON turns(state, created_at)
WHERE state IN ('queued', 'running');

Keeps it small and efficient since those are the only states the scheduler actually queries. Thought it was worth flagging before it becomes a problem.

Dominant language
TypeScript
Stars
71
Forks
64
Avg merge
15h 38m
Merged PRs (30d)
66

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from theam/facility

All issues in theam/facility

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.