Skip to content

db: optimize IsFirstOccurrence query for jobs with many builds - #9422

Merged
taylorsilva merged 2 commits into
concourse:masterfrom
analytically:optim/isfirstocc
Mar 18, 2026
Merged

taylorsilva merged 2 commits into
concourse:masterfrom
analytically:optim/isfirstocc

Conversation

@analytically

Copy link
Copy Markdown
Contributor

The original query fetched all builds for a job before filtering by version, causing 2+ second queries for jobs with 35k+ builds.

Add fast-path that checks the last successful build first. This handles the common case where a version is reused across builds, avoiding the expensive fallback query entirely.

Change fallback to use nested EXISTS instead of CTE. This filters by version first then checks job membership, and allows Postgres to stop at the first match.

Fixes #8160 but without index. TBD later on if we'd like to add an index.

@analytically
analytically requested a review from a team January 12, 2026 18:54
The original query fetched all builds for a job before filtering by
version, causing 2+ second queries for jobs with 35k+ builds.

Add fast-path that checks the last successful build first. This
handles the common case where a version is reused across builds,
avoiding the expensive fallback query entirely.

Change fallback to use nested EXISTS instead of CTE. This filters
by version first then checks job membership, and allows Postgres
to stop at the first match.

Fixes concourse#8160 but without index. TBD later on if we'd like to add
an index.

Signed-off-by: Mathias Bogaert <[email protected]>

@taylorsilva taylorsilva left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good to me. Dig a bunch of digging into the issue and previous PR made (#6403). Also ran the queries against CI with a job that has over a million builds.

I was mostly interested in the fallback query and how it compared to the query it's replacing.

Original query:

explain analyze
WITH builds_of_job AS (
	SELECT id FROM builds WHERE job_id = 490
	)
SELECT EXISTS (
	SELECT 1
	FROM build_resource_config_version_inputs i
	JOIN builds_of_job b ON b.id = i.build_id
	WHERE i.name = 'every-30s'
	AND i.version_digest = '7f8b0bcb41db44b2efda116d3b3740a894df412a73c212e4c6c70bb3094e36c9'
);
Result  (cost=581.43..581.44 rows=1 width=1) (actual time=3.457..3.459 rows=1.00 loops=1)
  Buffers: shared hit=1544
  InitPlan 1
    ->  Nested Loop  (cost=1.12..4643.61 rows=8 width=0) (actual time=3.453..3.455 rows=1.00 loops=1)
          Buffers: shared hit=1544
          ->  Index Scan using build_inputs_resource_versions_idx on build_resource_config_version_inputs i  (cost=0.56..4424.46 rows=47 width=8) (actual time=3.423..3.424 rows=1.00 loops=1)
                Index Cond: (version_digest = '7f8b0bcb41db44b2efda116d3b3740a894df412a73c212e4c6c70bb3094e36c9'::text)
                Filter: (name = 'every-30s'::text)
                Index Searches: 332
                Buffers: shared hit=1538
          ->  Index Only Scan using builds_ordered_by_job_id_idx on builds  (cost=0.56..4.66 rows=1 width=8) (actual time=0.022..0.022 rows=1.00 loops=1)
                Index Cond: ((job_id = 490) AND (id = i.build_id))
                Heap Fetches: 1
                Index Searches: 1
                Buffers: shared hit=6
Planning:
  Buffers: shared hit=14
Planning Time: 0.639 ms
Execution Time: 3.512 ms

PR query

explain analyze SELECT EXISTS (
SELECT 1
FROM build_resource_config_version_inputs i
WHERE i.resource_id = 874
AND i.version_digest = '7f8b0bcb41db44b2efda116d3b3740a894df412a73c212e4c6c70bb3094e36c9'
AND i.name = 'every-30s'
AND EXISTS (
	SELECT 1 FROM builds b
	WHERE b.id = i.build_id
	AND b.job_id = 490
)
);
Result  (cost=65.01..65.02 rows=1 width=1) (actual time=0.050..0.051 rows=1.00 loops=1)
  Buffers: shared hit=11
  InitPlan 1
    ->  Nested Loop  (cost=1.12..65.01 rows=1 width=0) (actual time=0.048..0.049 rows=1.00 loops=1)
          Buffers: shared hit=11
          ->  Index Scan using build_inputs_resource_versions_idx on build_resource_config_version_inputs i  (cost=0.56..38.12 rows=5 width=8) (actual time=0.031..0.032 rows=1.00 loops=1)
                Index Cond: ((resource_id = 874) AND (version_digest = '7f8b0bcb41db44b2efda116d3b3740a894df412a73c212e4c6c70bb3094e36c9'::text))
                Filter: (name = 'every-30s'::text)
                Index Searches: 1
                Buffers: shared hit=5
          ->  Index Only Scan using builds_ordered_by_job_id_idx on builds b  (cost=0.56..5.38 rows=1 width=8) (actual time=0.014..0.014 rows=1.00 loops=1)
                Index Cond: ((job_id = 490) AND (id = i.build_id))
                Heap Fetches: 1
                Index Searches: 1
                Buffers: shared hit=6
Planning:
  Buffers: shared hit=14
Planning Time: 0.789 ms
Execution Time: 0.101 ms

It's a great improvement!

I checked the two new queries that check if the previous build is the first occurrence, and they both seem fast. Their query plans used indexes and ran in a few milliseconds.

Comment thread atc/db/versions_db.go Outdated
SELECT id FROM builds WHERE job_id = $1
)
SELECT id FROM builds
WHERE job_id = $1 AND status = 'succeeded'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm guessing you filtered by status because we need to avoid looking up the current job we're trying to schedule. The problem with this is that we want to know if this is the first occurrence of this resource for any build of the job, not just successful builds. We also need to consider any in-flight builds that are already running. I think flipping this to ignore any pending builds should satisfy that.

Suggested change
WHERE job_id = $1 AND status = 'succeeded'
WHERE job_id = $1 AND status <> 'pending'

ref:

const (
BuildStatusPending BuildStatus = "pending"
BuildStatusStarted BuildStatus = "started"
BuildStatusAborted BuildStatus = "aborted"
BuildStatusSucceeded BuildStatus = "succeeded"
BuildStatusFailed BuildStatus = "failed"
BuildStatusErrored BuildStatus = "errored"
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wondering if we even should filter by status since the previous query did not.

Locally checked the triggering behaviour using this pipeline

resources:
  - name: time
    type: time
    source:
      interval: 1s

jobs:
  - name: regular-trigger
    plan:
      - get: time
        trigger: true

  - name: every-trigger
    plan:
      - get: time
        trigger: true
        version: every

The every trigger worked as expected, and normal triggering did as well, only triggering on the latest version when multiple versions were emitted at once. I think we're good here!

@taylorsilva taylorsilva moved this from Todo to In Progress in Pull Requests Mar 17, 2026
@taylorsilva
taylorsilva merged commit dba6b86 into concourse:master Mar 18, 2026
12 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in Pull Requests Mar 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

Improve builds_of_job bottleneck query

2 participants