Skip to content

Speed up the query for determining if a version is the first occurrence within a job - #6403

Closed
clarafu wants to merge 1 commit into
masterfrom
first-occ-query
Closed

clarafu wants to merge 1 commit into
masterfrom
first-occ-query

Conversation

@clarafu

@clarafu clarafu commented Jan 7, 2021

Copy link
Copy Markdown
Contributor

What does this PR accomplish?

Bug Fix | Feature | Documentation

On our large deployment, we were seeing that the first occurrence query was a bottleneck for the database.

WITH builds_of_job AS (
SELECT id FROM builds WHERE job_id = $1
)
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 = $2
AND i.version_md5 = $3
AND i.resource_id = $4

There were consistently 20 of these queries being run on the database, which ends up clogging up the database connections. When I ran an EXPLAIN ANALYZE on the query using a job that had 3000 builds, I saw that it was taking almost 15 seconds to run

Result  (cost=3317.61..3317.62 rows=1 width=1) (actual time=14950.212..14950.213 rows=1 loops=1)
  CTE builds_of_job
    ->  Index Only Scan using builds_ordered_by_job_id_idx on builds  (cost=0.43..3288.58 rows=860 width=4) (actual time=6.476..14916.978 rows=3190 loops=1)
          Index Cond: (job_id = 93253)
          Heap Fetches: 3190
  InitPlan 2 (returns $1)
    ->  Hash Join  (cost=8.59..29.03 rows=1 width=0) (actual time=14950.211..14950.211 rows=1 loops=1)
          Hash Cond: (b.id = i.build_id)
          ->  CTE Scan on builds_of_job b  (cost=0.00..17.20 rows=860 width=4) (actual time=6.478..14922.335 rows=3190 loops=1)
          ->  Hash  (cost=8.58..8.58 rows=1 width=4) (actual time=24.461..24.461 rows=6 loops=1)
                Buckets: 1024  Batches: 1  Memory Usage: 9kB
                ->  Index Scan using build_inputs_resource_versions_idx on build_resource_config_version_inputs i  (cost=0.56..8.58 rows=1 width=4) (actual time=24.452..24.453 rows=6 loops=1)
                      Index Cond: ((resource_id = 31188) AND (version_md5 = 'b5029cead24551c69709428a9543e078'::text))
                      Filter: (name = 'repository'::text)
Planning time: 0.282 ms
Execution time: 14950.289 ms

It looks like most of the time that it takes is due to the fetching of all the builds for that job. Knowing this, I can think of two ways to fix this:

  1. Refactor the query to make it not need to fetch all the builds for a job
  2. Denormalize the job_id column by adding it to the build_resource_config_version_inputs table

I think each of these options have its good and bad.

For the first option with refactoring the query, the way that I can think of to do this is to make it narrow down the builds by version first and then scope it down to the job id. This way there will be a smaller number of builds to work with, since the number of builds that match the version/resource will most likely and more commonly be smaller than the number of builds within a job. I say this with uncertainty because I understand that might not always be the case, for example, there might be some versions that are being used throughout many builds within a pipeline (a git version that has not been updated for 2 years but is being used for every build within several jobs). The following query would be how I imagine it would be written:

EXPLAIN ANALYZE WITH builds_of_version AS ( 
	SELECT build_id
	FROM build_resource_config_version_inputs
	WHERE name = 'repository'
	AND version_md5 = 'b5029cead24551c69709428a9543e078' 
	AND resource_id = 31188
) SELECT EXISTS ( 
	SELECT 1 
	FROM builds b
	JOIN builds_of_version v ON b.id = v.build_id
	WHERE job_id = 93253 
);

I tried running this option with EXPLAIN ANALYZE and this is the results I got.

Result  (cost=17.06..17.07 rows=1 width=1) (actual time=30.810..30.811 rows=1 loops=1)
  CTE builds_of_version
    ->  Index Scan using build_inputs_resource_versions_idx on build_resource_config_version_inputs  (cost=0.56..8.58 rows=1 width=4) (actual time=15.400..15.410 rows=5 loops=1)
          Index Cond: ((resource_id = 31188) AND (version_md5 = 'b5029cead24551c69709428a9543e078'::text))
          Filter: (name = 'repository'::text)
  InitPlan 2 (returns $2)
    ->  Nested Loop  (cost=0.43..8.48 rows=1 width=0) (actual time=30.807..30.807 rows=1 loops=1)
          ->  CTE Scan on builds_of_version v  (cost=0.00..0.02 rows=1 width=4) (actual time=15.402..15.416 rows=5 loops=1)
          ->  Index Only Scan using builds_ordered_by_job_id_idx on builds b  (cost=0.43..8.45 rows=1 width=4) (actual time=3.076..3.076 rows=0 loops=5)
                Index Cond: ((job_id = 93253) AND (id = v.build_id))
                Heap Fetches: 1
Planning time: 0.414 ms
Execution time: 30.864 ms

Which is a lot faster as it took 30 ms vs 15000 ms. But this is also because I chose a job that had 3000 builds, which means that in this specific case it would be faster to use the refactored query. If, lets say, I chose an example that had a version used throughout many builds then the results might not be so much of an improvement. One thing to note is that if there is a version that is used throughout many builds, most likely it would be used throughout many builds of the same job so that means that both the original and refactored query would be slow in that situation.

For the second option with denormalizing, this means adding a job_id column to the build_resource_config_version_inputs table. We would then be able to just do a simple query without any CTE to find a version of a resource within a job. It would look something like this

EXPLAIN ANALYZE SELECT EXISTS ( 
	SELECT 1 
	FROM builds
	WHERE name = 'repository'
	AND version_md5 = 'b5029cead24551c69709428a9543e078' 
	AND resource_id = 31188
	WHERE job_id = 93253 
);

I am unable to actually run the query without the column being there but I imagine it would be incredibly fast to run. This would remove any slowness due to needing to narrow down the set of builds first using a CTE, whether it is through a job_id or version, and would be directly using an index to fetch that exact row that we are looking for. This is probably the ideal choice, but it comes with the drawbacks of having to add a migration that will need to run for the incredibly large build_resource_config_version_inputs table to add the job_id into the table. It will also result in duplication of the job_id column, as the data already exists within the builds table. This is very similar to what already exists within the successful_build_outputs table (where it has a job_id) and also what is currently being added to the build_image_resource_caches table #5993. So I'm just unsure how far we want to go with this, or if it is actually a good idea to just spread that data throughout tables that we know are going to be really large and will benefit from this denormalization.

Changes proposed by this PR:

The change introduces a refactor to the first occurrence query that should help improve its speed. Previously, the query would fetch all the builds within a job and then try to find a version within those list of builds that match the version. But that causes a lot of slowness when the job has a looot of builds. (the CTE part of the query is slow)

The fix here is to have the first part of the query (the CTE) to find all the builds that have that version and then try to find a build that matches the job we are looking for. This will hopefully help reduce the number of rows from the CTE, because there are probably less builds that match the version than there are builds that are from the job. But at least in the most common case, I believe that there will be less rows from narrowing down with a version vs narrowing down with a job id.

Notes to reviewer:

I submitted this PR with the first option but I actually just wanted to start a conversation in order to find what the best decision is going forward. The solution doesn't need to be one of these two options, those are just the ones I thought of at this moment. I am totally open to doing anything else we come up with!

Release Note

Contributor Checklist

Reviewer Checklist

  • Code reviewed
  • Tests reviewed
  • Documentation reviewed
  • Release notes reviewed
  • PR acceptance performed
  • New config flags added? Ensure that they are added to the
    BOSH and
    Helm packaging; otherwise, ignored for
    the integration
    tests

    (for example, if they are Garden configs that are not displayed in the
    --help text).

This should help improve the speed of this query to find if a version is
the first occurrence within a job. Previously, the query would fetch all
the builds within a job and then try to find a version within those list
of builds that match the version. But that causes a lot of slowness when
the job has a looot of builds. (the CTE part of the query is slow)

The fix here is to have the first part of the query (the CTE) to find
all the builds that have that version and then try to find a build that
matches the job we are looking for. This will hopefully help reduce the
number of rows from the CTE, because there are probably less builds that
match the version than there are builds that are from the job. One
concern is that there can be some versions of a resource that are being
used by many builds within a pipeline, which can cause the query to be
slow too because it needs to fetch all of those rows. But at least in
the most common case, I believe that there will be less rows from
narrowing down with a version vs narrowing down with a job id.

Signed-off-by: Clara Fu <[email protected]>
@clarafu clarafu changed the title Refactor First Occurrence query Speed up the query for determining if a version is the first occurrence within a job Jan 7, 2021
@aoldershaw

aoldershaw commented Jan 11, 2021 •

Copy link
Copy Markdown
Contributor

Denormalizing here is a bit spooky on such a huge table - the increased disk space isn't ideal, but more concerning to me is the migration that it requires. If there was a way to denormalize job_id here without making the upgrade more risky, I think I'd be for it, especially given the precedent on successful_build_outputs and build_image_resource_caches.

Without denormalization, I definitely expect this to be faster in the vast majority of cases, but as you note, some versions are used by many builds. e.g. on CI, version 1.2.2 of dumb-init has been around since 2018, and has amassed 1797 builds - which is more than the number of builds on the dev-image job (~700), so we'd see a performance dip here.

More dramatic examples are oxygen-mask and fly in the monitoring-stats pipeline. Each job is currently in the order of ~100,000 builds, and the same resource is being shared between 5 jobs. On CI, version cf462dd98d3c5f2129b5c86bac835305 of oxygen-mask currently has over 400000 entries in build_resource_config_version_inputs, for instance.

So with this change, you've greatly optimized the query for jobs that have frequently changing versions as inputs, but long-lived versions may take a performance hit. The thing about these long-lived versions is that they rarely change build-to-build (obviously) - so what if we added a hot path for that case.

  • Since we just need to find one previous instance of the version for the job, we could first check the version from the previous build of the job
    • If it's the same version, we're done (common case for long-lived versions)
    • Otherwise, we run the potentially slow query (common case for short-lived versions)

This would introduce a slight performance decrease for jobs with inputs that change frequently, but with the optimization you've already added, both queries should be quick in this case, so it hopefully wouldn't be too bad. For long-lived versions, we may still have to run the slow query (typically if an old version is pinned, given that the version doesn't change often by definition), but it should be much more rare

WDYT?

@clarafu

clarafu commented Jan 12, 2021

Copy link
Copy Markdown
Contributor Author

I definitely agree, seeing that data about those versions being used by so many builds is just confirmation that it might be super slow for some use cases. Just to get some more data, I ran the modified query using the oxygen-mask resource with the version_md5 of cf462dd98d3c5f2129b5c86bac835305 and this is what I get as the result

Result  (cost=66302.35..66302.36 rows=1 width=1) (actual time=69.091..69.091 rows=1 loops=1)
  CTE builds_of_version
    ->  Bitmap Heap Scan on build_resource_config_version_inputs  (cost=1665.49..66096.31 rows=5459 width=8) (actual time=69.062..69.062 rows=1 loops=1)
          Recheck Cond: ((resource_id = 11775) AND (version_md5 = 'cf462dd98d3c5f2129b5c86bac835305'::text))
          Filter: (name = 'oxygen-mask'::text)
          Heap Blocks: exact=1
          ->  Bitmap Index Scan on build_inputs_resource_versions_idx  (cost=0.00..1664.13 rows=35557 width=0) (actual time=57.969..57.969 rows=408109 loops=1)
                Index Cond: ((resource_id = 11775) AND (version_md5 = 'cf462dd98d3c5f2129b5c86bac835305'::text))
  InitPlan 2 (returns $2)
    ->  Nested Loop  (cost=0.43..23233.97 rows=113 width=0) (actual time=69.089..69.089 rows=1 loops=1)
          ->  CTE Scan on builds_of_version v  (cost=0.00..109.18 rows=5459 width=8) (actual time=69.065..69.065 rows=1 loops=1)
          ->  Index Only Scan using builds_ordered_by_job_id_idx on builds b  (cost=0.43..4.23 rows=1 width=8) (actual time=0.017..0.018 rows=1 loops=1)
                Index Cond: ((job_id = 5946) AND (id = v.build_id))
                Heap Fetches: 1
Planning time: 0.451 ms
Execution time: 70.635 ms

Which is suuuper slow compared to if I run the same inputs against the original query that takes about 0.1 ms to complete.

The idea you proposed is great! It would help to speed up the query for versions that have been used for many builds but still keeping the speed of versions that are changing often. I think the only times that it might have some performance drops are uncommon use cases like you mentioned, when versions are messed with.

So I was hoping to see if there can be some optimization that could make the query faster even for versions that are used for many builds because I think (of course) ideally there are no slow queries even during uncommon cases. I think if we add this index create index someindex on build_resource_config_version_inputs (resource_id, version_md5, name, build_id); it will help speed up the possibly slow query. If I run the exact same inputs and modified query using this index, it runs in 0.2 ms

Result  (cost=8683.46..8683.47 rows=1 width=1) (actual time=0.187..0.187 rows=1 loops=1)
  CTE builds_of_version
    ->  Index Only Scan using deleteme3 on build_resource_config_version_inputs  (cost=0.56..8477.38 rows=5460 width=8) (actual time=0.165..0.165 rows=1 loops=1)
          Index Cond: ((resource_id = 11775) AND (version_md5 = 'cf462dd98d3c5f2129b5c86bac835305'::text) AND (name = 'oxygen-mask'::text))
          Heap Fetches: 1
  InitPlan 2 (returns $2)
    ->  Nested Loop  (cost=0.43..23238.45 rows=113 width=0) (actual time=0.187..0.187 rows=1 loops=1)
          ->  CTE Scan on builds_of_version v  (cost=0.00..109.20 rows=5460 width=8) (actual time=0.168..0.168 rows=1 loops=1)
          ->  Index Only Scan using builds_ordered_by_job_id_idx on builds b  (cost=0.43..4.23 rows=1 width=8) (actual time=0.013..0.013 rows=1 loops=1)
                Index Cond: ((job_id = 5946) AND (id = v.build_id))
                Heap Fetches: 0
Planning time: 0.403 ms
Execution time: 0.228 ms

If we do add that index, we can remove the build_inputs_resource_versions_idx index because it will be a covered by this new index.

@aoldershaw

Copy link
Copy Markdown
Contributor

Interesting! Just adding an index seems like a better approach than I suggested given that it works in the general case.

Sounds like a pretty big index though - it's basically a complete clone of the table! Do we have an idea of how costly that migration would be? Or the additional storage requirements? Mostly just playing devil's advocate, I think your approach makes a lot of sense!

@clarafu

clarafu commented Jan 19, 2021

Copy link
Copy Markdown
Contributor Author

I was actually hoping to implement both ur suggestion and the addition of the index to fully optimize the first occurrence query! But it is a pretty big index, the migration would probably take a few minutes (which it took about 1-2 minutes when I tried it on the ci deployment). I was hoping that because we are just replacing an existing index with this one, there actually wont be much more additional storage required for this.

Just to give you an update on why I haven't been updating this PR, now that the hush-house deployment has stabilized when I run the original query with the exact same inputs it runs very fast. I think the high memory usage on hush-house before was causing the original query (because it had to fetch so many rows from the builds table) to be really slow but now that the memory usage has dropped, the query speed is super fast (under 1 ms). So without being able to fully compare the results of the original query to the approach we are discussing, I'm not confident that it will be necessarily faster when the database is under heavy memory usage.

I think that even though the query is really fast right now, we still want to refactor the query to not become a bottleneck when the database is under heavy memory usage. I'm just contemplating on whether to wait to properly compare the speeds of the approaches when the memory is high again or we could run a stress test or just go ahead with the new approach. 🤔

@aoldershaw

aoldershaw commented Jan 21, 2021 •

Copy link
Copy Markdown
Contributor

I was hoping that because we are just replacing an existing index with this one, there actually wont be much more additional storage required for this

Maybe, but I'd expect the index to be a fair bit bigger, since now the index includes much more data per entry. Not sure how much that matters, though, as it's likely to be overshadowed by the larger tables (like build_events)

I think the high memory usage on hush-house before was causing the original query (because it had to fetch so many rows from the builds table) to be really slow but now that the memory usage has dropped, the query speed is super fast (under 1 ms)

Woah, that's interesting that it gets 4 orders of magnitude slower when memory is constrained! In that case, I wonder if adding this index is worth it, given that in an unconstrained DB, the query speeds seem to be similarly fast.

I think that even though the query is really fast right now, we still want to refactor the query to not become a bottleneck when the database is under heavy memory usage

Yeah, makes sense - I think your original refactor makes sense (builds_of_version), and gives us the ability to add the index if things start getting bad without needing to upgrade Concourse

I'm just contemplating on whether to wait to properly compare the speeds of the approaches when the memory is high again or we could run a stress test or just go ahead with the new approach. 🤔

Not sure either...I feel like scaling hush-house down wouldn't be great for our tenants given the issues we were facing before. But yeah, maybe a stress test would be the way to go? Or maybe we should just deploy this on CI and see how things behave - we know this will be fast for frequently changing resources, but we could keep an eye on resources with a ton of versions like in oxygen-mask

@aoldershaw aoldershaw removed their assignment Aug 27, 2021
@clarafu clarafu self-assigned this Aug 30, 2021
@clarafu

clarafu commented Oct 29, 2021

Copy link
Copy Markdown
Contributor Author

I'm just going to close this for not until we find that we want to investigate it further!

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants