Skip to content

Speed up database queries by adding a job_id column to build image resource caches table and adding an index for ordering builds of a job - #5993

Merged
clarafu merged 3 commits into
masterfrom
optimizations
Jan 7, 2021
Merged

clarafu merged 3 commits into
masterfrom
optimizations

Conversation

@clarafu

@clarafu clarafu commented Aug 17, 2020 •

Copy link
Copy Markdown
Contributor

What does this PR accomplish?

Feature

This PR adds a few improvements to some database queries that are slow on large Concourse instances. A few that I noticed on our large environment are the query to delete build image resource caches

WITH caches AS ( 
  SELECT resource_cache_id, build_id
  FROM build_image_resource_caches brc 
  JOIN builds b ON b.id = brc.build_id 
  WHERE b.job_id = $1 )
SELECT * FROM build_image_resource_caches birc
JOIN caches c ON c.build_id = birc.build_id
AND birc.build_id < $2;

which takes 8100 ms with the following EXPLAIN ANALYZE

Nested Loop  (cost=5298.46..5815.01 rows=41 width=16) (actual time=8161.688..8161.688 rows=0 loops=1)
  CTE caches
    ->  Nested Loop  (cost=0.86..5298.04 rows=61 width=8) (actual time=8161.680..8161.682 rows=1 loops=1)
          ->  Index Only Scan Backward using builds_ordered_by_job_id_idx on builds b  (cost=0.43..985.76 rows=531 width=4) (actual time=8.074..5146.653 rows=3190 loops=1)
                Index Cond: (job_id = 93253)
                Heap Fetches: 1784
          ->  Index Scan using build_image_resource_caches_build_id on build_image_resource_caches brc  (cost=0.42..8.11 rows=1 width=8) (actual time=0.943..0.943 rows=0 loops=3190)
                Index Cond: (build_id = b.id)
  ->  CTE Scan on caches c  (cost=0.00..1.22 rows=61 width=8) (actual time=8161.683..8161.685 rows=1 loops=1)
  ->  Index Scan using build_image_resource_caches_build_id on build_image_resource_caches birc  (cost=0.42..8.45 rows=1 width=8) (actual time=0.001..0.001 rows=0 loops=1)
        Index Cond: ((build_id = c.build_id) AND (build_id < 2585615))
Planning time: 0.677 ms
Execution time: 8161.744 ms

and listing builds of a job

SELECT b.id, b.name, b.job_id, b.team_id, b.status, b.manually_triggered, b.scheduled, b.schema, b.private_plan, b.public_plan, b.create_time, b.start_time, b.end_time, b.reap_time, j.name, b.pipeline_id, p.name, t.name, b.nonce, b.drained, b.aborted, b.completed, b.inputs_ready, b.rerun_of, r.name, b.rerun_number, b.span_context
FROM builds b
LEFT OUTER JOIN jobs j ON b.job_id = j.id
LEFT OUTER JOIN pipelines p ON b.pipeline_id = p.id
LEFT OUTER JOIN teams t ON b.team_id = t.id
LEFT OUTER JOIN builds r ON r.id = b.rerun_of
WHERE b.job_id = $1
ORDER BY COALESCE(b.rerun_of, b.id) DESC, b.id DESC
LIMIT ?;

which takes 7800 ms and produces the following EXPLAIN ANALYZE

Limit  (cost=523713.99..523714.24 rows=100 width=707) (actual time=7871.041..7871.107 rows=100 loops=1)
  ->  Sort  (cost=523713.99..524320.32 rows=242532 width=707) (actual time=7871.039..7871.081 rows=100 loops=1)
        Sort Key: (COALESCE(b.rerun_of, b.id)) DESC, b.id DESC
        Sort Method: top-N heapsort  Memory: 76kB
        ->  Hash Left Join  (cost=254829.85..514444.59 rows=242532 width=707) (actual time=3659.911..7711.079 rows=242856 loops=1)
              Hash Cond: (b.team_id = t.id)
              ->  Hash Left Join  (cost=254828.70..511108.62 rows=242532 width=694) (actual time=3659.880..7632.151 rows=242856 loops=1)
                    Hash Cond: (b.pipeline_id = p.id)
                    ->  Nested Loop Left Join  (cost=254820.74..507766.01 rows=242532 width=682) (actual time=3659.815..7559.210 rows=242856 loops=1)
                          Join Filter: (b.job_id = j.id)
                          ->  Hash Left Join  (cost=254820.46..504119.73 rows=242532 width=669) (actual time=3659.795..7431.257 rows=242856 loops=1)
                                Hash Cond: (b.rerun_of = r.id)
                                ->  Bitmap Heap Scan on builds b  (cost=8856.05..205038.01 rows=242532 width=663) (actual time=70.277..3762.983 rows=242856 loops=1)
                                      Recheck Cond: (job_id = 473)
                                      Rows Removed by Index Recheck: 1196238
                                      Heap Blocks: exact=25699 lossy=105759
                                      ->  Bitmap Index Scan on builds_ordered_by_job_id_idx  (cost=0.00..8795.42 rows=242532 width=0) (actual time=60.807..60.809 rows=242858 loops=1)
                                            Index Cond: (job_id = 473)
                                ->  Hash  (cost=206215.96..206215.96 rows=2286596 width=10) (actual time=3588.710..3588.710 rows=2285788 loops=1)
                                      Buckets: 131072  Batches: 64  Memory Usage: 2562kB
                                      ->  Seq Scan on builds r  (cost=0.00..206215.96 rows=2286596 width=10) (actual time=0.018..3094.751 rows=2285788 loops=1)
                          ->  Materialize  (cost=0.28..8.30 rows=1 width=17) (actual time=0.000..0.000 rows=1 loops=242856)
                                ->  Index Scan using jobs_pkey on jobs j  (cost=0.28..8.29 rows=1 width=17) (actual time=0.010..0.011 rows=1 loops=1)
                                      Index Cond: (id = 473)
                    ->  Hash  (cost=6.87..6.87 rows=87 width=16) (actual time=0.040..0.040 rows=87 loops=1)
                          Buckets: 1024  Batches: 1  Memory Usage: 13kB
                          ->  Seq Scan on pipelines p  (cost=0.00..6.87 rows=87 width=16) (actual time=0.006..0.023 rows=87 loops=1)
              ->  Hash  (cost=1.07..1.07 rows=7 width=13) (actual time=0.012..0.012 rows=7 loops=1)
                    Buckets: 1024  Batches: 1  Memory Usage: 9kB
                    ->  Seq Scan on teams t  (cost=0.00..1.07 rows=7 width=13) (actual time=0.007..0.008 rows=7 loops=1)
Planning time: 2.279 ms
Execution time: 7871.430 ms

Changes proposed by this PR:

This PR modifies the query for deleting build image resource caches by adding a job_id column in the build_image_resource_caches table so it no longer needs to JOIN to the builds table and finding all the builds for a job (which is the part that takes the longest). By having a job_id column, I was able to simplify the query to

 SELECT * FROM build_image_resource_caches WHERE job_id = $1 AND build_id < $2

I was only able to test out this change on a smaller environment, which this is the EXPLAIN ANALYZE before the change

Hash Join  (cost=78894.44..79307.21 rows=12695 width=16) (actual time=99.338..99.338 rows=0 loops=1)
  Hash Cond: (c.build_id = birc.build_id)
  CTE caches
    ->  Merge Join  (cost=5.56..77099.03 rows=6180 width=8) (actual time=86.448..86.465 rows=2 loops=1)
          Merge Cond: (brc.build_id = b.id)
          ->  Index Scan using build_image_resource_caches_build_id on build_image_resource_caches brc  (cost=0.41..6214.25 rows=58263 width=8) (actual time=0.003..23.379 rows=58366 loops=1)
          ->  Index Only Scan Backward using builds_ordered_by_job_id_idx on builds b  (cost=0.43..70843.52 rows=242334 width=4) (actual time=0.011..43.153 rows=242739 loops=1)
                Index Cond: (job_id = 473)
                Heap Fetches: 24271
  ->  CTE Scan on caches c  (cost=0.00..123.60 rows=6180 width=8) (actual time=86.451..86.469 rows=2 loops=1)
  ->  Hash  (cost=1067.29..1067.29 rows=58250 width=8) (actual time=12.782..12.782 rows=58345 loops=1)
        Buckets: 65536  Batches: 1  Memory Usage: 2792kB
        ->  Seq Scan on build_image_resource_caches birc  (cost=0.00..1067.29 rows=58250 width=8) (actual time=0.016..7.774 rows=58345 loops=1)
              Filter: (build_id < 2286147)
              Rows Removed by Filter: 21
Planning time: 0.494 ms
Execution time: 99.766 ms

and this is after adding the column

Index Scan using build_image_resource_caches_job_build_idx on build_image_resource_caches  (cost=0.29..30.08 rows=10 width=12) (actual time=0.010..0.010 rows=0 loops=1)
  Index Cond: ((job_id = 473) AND (build_id < 2286147))
Planning time: 0.140 ms
Execution time: 0.026 ms

The second part of this PR adds a new index to speed up the query for fetching the builds for a job in order while taking into account rerun builds. The following EXPLAIN ANALYZE is the difference after adding the index.

Limit  (cost=1.28..524.70 rows=100 width=707) (actual time=0.040..0.611 rows=100 loops=1)
  ->  Nested Loop Left Join  (cost=1.28..1269009.59 rows=242446 width=707) (actual time=0.039..0.603 rows=100 loops=1)
        ->  Nested Loop Left Join  (cost=0.85..546882.54 rows=242446 width=697) (actual time=0.038..0.554 rows=100 loops=1)
              Join Filter: (b.team_id = t.id)
              Rows Removed by Join Filter: 596
              ->  Nested Loop Left Join  (cost=0.85..521424.62 rows=242446 width=688) (actual time=0.029..0.417 rows=100 loops=1)
                    ->  Nested Loop Left Join  (cost=0.71..480176.80 rows=242446 width=676) (actual time=0.025..0.294 rows=100 loops=1)
                          Join Filter: (b.job_id = j.id)
                          ->  Index Scan using deleteme on builds b  (cost=0.43..476531.82 rows=242446 width=663) (actual time=0.016..0.229 rows=100 loops=1)
                                Index Cond: (job_id = 473)
                          ->  Materialize  (cost=0.28..8.30 rows=1 width=17) (actual time=0.000..0.000 rows=1 loops=100)
                                ->  Index Scan using jobs_pkey on jobs j  (cost=0.28..8.29 rows=1 width=17) (actual time=0.005..0.005 rows=1 loops=1)
                                      Index Cond: (id = 473)
                    ->  Index Scan using pipelines_pkey on pipelines p  (cost=0.14..0.16 rows=1 width=16) (actual time=0.001..0.001 rows=1 loops=100)
                          Index Cond: (b.pipeline_id = id)
              ->  Materialize  (cost=0.00..1.10 rows=7 width=13) (actual time=0.000..0.000 rows=7 loops=100)
                    ->  Seq Scan on teams t  (cost=0.00..1.07 rows=7 width=13) (actual time=0.005..0.007 rows=7 loops=1)
        ->  Index Scan using builds_pkey on builds r  (cost=0.43..2.97 rows=1 width=10) (actual time=0.000..0.000 rows=0 loops=100)
              Index Cond: (id = b.rerun_of)
Planning time: 1.116 ms
Execution time: 0.705 ms

Also removed an unused index in the builds table!

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).

@jamieklassen jamieklassen left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I've been pondering this for a while, trying to understand why the expensive query in Finish() exists. I tried commenting it out, and the only db test that fails as a result is

ResourceCacheLifecycle CleanUpInvalidCaches the resource cache is used by a build when its a build of a job in a pipeline when the cache is for a saved image resource version for a finished build when the build has succeeded [It] removes resource caches for previous finished builds

what is not clear to me is this -- is this a functional requirement, or an optimization? If you fail to remove image_resource caches from older builds, is there some risk of them being erroneously reused in subsequent builds? I will try to test this myself now but I figured I'd just ask the question to avoid an even longer feedback loop.

@@ -0,0 +1,12 @@
BEGIN;
ALTER TABLE build_image_resource_caches
ADD COLUMN job_id integer REFERENCES jobs(id);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is the controversial part of this change, since it denormalizes (there is redundancy between job_id on build_image_resource_caches and the result of joining builds on builds.id = build_image_resource_caches.build_id and selecting builds.job_id). I have to wonder if there's a better way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right I wanted to remove the need to join to the builds table in order to fetch the job_id from the build because that is the part that makes the current query slow. This is definitely something I am open to finding a different way to not need to duplicate the job_id data everywhere because this is something I run into a lot, where the thing that makes a query slow is the joining to the builds table in order to grab the job_id from it.

Comment on lines +5 to +8
UPDATE build_image_resource_caches
SET job_id = builds.job_id
FROM builds
WHERE builds.id = build_id;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

have you profiled this migration? I imagine it must sequentially scan build_image_resource_caches... but not every build has image_resource caches, and that table should be regularly cleaned up by the existing query in Finish() on db.Build as well as the CleanBuildImageResourceCaches method on db.resourceCacheLifecycle... so it's fast?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I haven't profiled the migration but in a deployment like hush-house, there is approx 600k rows and in our prod environment there is 9k rows. I imagined the caches should be cleaned up pretty often so it shouldn't have too many rows to update?

@jamieklassen

jamieklassen commented Sep 9, 2020 •

Copy link
Copy Markdown

tl;dr - what about outright deleting the complex query in the Finish method? I believe concourse will still work, but resource caches associated to image_resources would always stick around for 24 hours. So my suggestion equates to trading CPU pressure on the DB for disk pressure on the worker, but only when builds are running often in a 24-hour period and image_resources are changing frequently during the same time period. Otherwise I think we would be keeping around rows in the build_image_resource_caches table, but this would not represent significantly more disk pressure on the DB than would otherwise be occurring due to the referenced builds.

I just spent a while investigating the history of the build_image_resource_caches table. Turns out it exists purely to prevent certain resource_caches rows from being deleted:

ALTER TABLE ONLY build_image_resource_caches
ADD CONSTRAINT build_image_resource_caches_resource_cache_id_fkey FOREIGN KEY (resource_cache_id) REFERENCES resource_caches(id) ON DELETE RESTRICT;

Actually the restriction is more of a last resort, since the resource cache lifecycle explicitly avoids deleting resource caches that are referenced by build_image_resource_caches:

buildImageCacheIds,

I asked before if explicitly deleting build_image_resource_caches entries for older builds was necessary for the correct functioning of build execution, and I think it really is an optimization, since there is a separate lifecycle method for cleaning them:

err := rcuc.cacheLifecycle.CleanBuildImageResourceCaches(logger.Session("clean-build-images"))

which unilaterally deletes all entries associated to builds that finished at least 24h ago:

Where(sq.Expr("((now() - b.end_time) > '24 HOURS'::INTERVAL)")).

@jamieklassen

jamieklassen commented Sep 9, 2020 •

Copy link
Copy Markdown

I wonder if it's worth having an operator flag to allow you to choose between the old and new db.Build.Finish queries, so we can run a controlled experiment in a real environment? I am grateful for the EXPLAIN ANALYZE queries, but that's looking at a single query running on the DB in isolation -- I think it would be more valuable to see timeseries data (saturation: CPU on the DB, as well as latency, i.e. more blackbox-/SLI-type metrics - e.g. does this reduce load on the DB enough that build scheduling speeds up?) to really validate the usefulness of this change. If it runs infrequently enough, the performance benefit might be negligible whereas the maintenance cost (risk for future changes mostly), while not huge, is already apparent.

@clarafu

clarafu commented Sep 10, 2020

Copy link
Copy Markdown
Contributor Author

I think that's fair to set up a controlled environment in order to see if this is a real problem/if the solution is a good fix. The reason why I pin pointed these two queries to optimize is because I saw them being the 1st and 2nd worst culprits for the slowest average and total time spent on these queries throughout the deployment.

Your suggestion for removing the query is interesting, I haven't even thought of the possibility of removing the query entirely! In most cases it won't have much of an impact because image resource caches shouldn't be changing often and keeping them around for 24 hours is fine in my opinion. I guess the only thing I would be worried about is jobs that run often and are constantly using new images as the image_resource (for example, building a new image and using them). But in those cases, they should be using the image configuration rather than image_resource. Maybe we can just document that if you are using image_resource, you will see your image caches stick around for 24 hours so if you are constantly building images to use in your task then you should use image?

@jamieklassen

Copy link
Copy Markdown

Another option (which is verging on anti-pattern territory, but also is maybe justified) would be for the 24 hour lifetime of an image_resource cache to be configurable -- if operators want to trade disk pressure for network pressure, they can shorten that lifespan.

@clarafu

clarafu commented Sep 10, 2020

Copy link
Copy Markdown
Contributor Author

Okay I think I might separate that out into another PR for removing the query and allowing the gc interval for build image caches to be configurable.

@clarafu

clarafu commented Sep 24, 2020

Copy link
Copy Markdown
Contributor Author

@jamieklassen Sorry its taken me a while to get to this, I took a stab at splitting this into two PRs and I noticed that the CleanBuildImageResourceCache query actually removes any build image caches for builds with no job id that have finished longer than 24 hours ago.

Where(sq.Eq{"job_id": nil}).

So it seems like the cleaning of build images in the Finish method was actually used to clean up build image caches for regular job builds while the CleanBuildImageResourceCache was used for cleaning one off builds. I could change the CleanBuildImageResourceCache to remove all types of build image caches but I wanted to get your opinion first.

@jamieklassen

Copy link
Copy Markdown

@clarafu good point, I'm pretty sure I hadn't noticed that. I guess this means that build image resource caches currently stick around until a subsequent build of the same job succeeds, even if that means sticking around for a very long time. I haven't really thought through this model, and I haven't thought much about the disk saturation induced by long-lived volumes (i might think about it more if we make ft account for volumes). but my wild guess is that it would be OK for image_resource caches to always have a fixed lifespan? maybe that should be a separate conversation, as you say...

@clarafu

clarafu commented Sep 25, 2020 •

Copy link
Copy Markdown
Contributor Author

@jamieklassen Hm if we did make it have a fixed lifespan, the situation I can think of is a user has a job that typically runs a build every day or two. Before switching images to have a fixed lifespan, each time a build runs it can reuse the same resource cache (no pulling of the image if it never got a new version) but if we did make it a fixed lifespan of 24 hours, any build that runs after that time will need to re-fetch the resource cache everytime. Knowing this, I think I'm a lot more hesitant to remove the slow query from Finish :(

@aoldershaw

Copy link
Copy Markdown
Contributor

Took a quick look at alternatives to the denormalization. One thing I found was MATERIALIZED VIEWS, which precomputes a query as a relation, allowing us to add indexes to that (table-spanning) relation. However, materialized views are eventually consistent and would add extra complexity that I don't think is any better than denormalizing job_id

@aoldershaw

Copy link
Copy Markdown
Contributor

Personally, I'm of the opinion that denormalizing job_id isn't so harmful in this case. One of the main challenges with denormalization is that data can become stale - but in this case, job_id never changes, so there isn't much concern of it going out of date. While it's nicer to have a single source of truth, duplication for the sake of optimizing a known slow query seems like a fair trade-off to me.

One thing I'm not so sure about is whether job_id alone will always be sufficient. Now that builds run for resources and resource_types, will we ever want to take that into account when we clear out old build_image_resource_caches? I guess they're currently being treated as one-off builds and being deleted in GC (resource_cache_lifecycle.go)? But if we wanted to change that behaviour, that'd require more migrations/denormalization

@clarafu

clarafu commented Nov 25, 2020

Copy link
Copy Markdown
Contributor Author

@aoldershaw That's a really good point! I think right now build_image_resource_caches for check builds created for resources and resource types are most likely always being deleted during the cascade delete of the build. Whenever we create a new build for a check, it will delete any past builds created for that resource check and this will cascade to deleting the build_image_resource_cache for that build. So the gc for build_image_resource_caches or the build finishing delete query should only be for builds created by a job.

I think Jamie was mostly concerned with how far we want to go with the denormalizing things for performance reasons and if we could find another way that didn't involve denormalizing. The current way the database is modelled is very much normalized, and I kind of broke that when I added the successful_build_outputs table in order to improve performance. 😅 I think it might just be something we have to get aligned with, since previously we always followed the normalized database model. I also think its fine if we want to denormalize the database in order to improve performance, as long as it makes sense and doesn't cause problems with database disk usage.

If you are fine with it, I think it would really help with the performance of the query. I've tried many different things to try to have the same result as just adding the job_id to the table, but nothing really worked because it will always need to do a join to the builds table in order to fetch the job_id. I thought about maybe partitioning the builds table by job_id, which might help with the speed of querying to the builds but that would be a huge change (and Im still not sure if I want to go that route because it does have it's tradeoffs). One minor weird thing is that if we do denormalize the job_id, now that we have builds that are tied to resource_id or resource_type_id, there will be plenty of rows in the build_image_resource_caches table that won't have the job_id column filled out. That being said, this is also the same as before when we can have one-off builds which also wouldn't have their job_id column set.

@aoldershaw

Copy link
Copy Markdown
Contributor

Whenever we create a new build for a check, it will delete any past builds created for that resource check and this will cascade to deleting the build_image_resource_cache for that build.

Ah, right - that makes me feel better about it!

If you are fine with it, I think it would really help with the performance of the query

It's fine with me - it seems like any alternatives also have their downsides, and I don't think a little denormalization is so scary in this particular case, given that the denormalized state is effectively immutable and the build_image_resource_caches table shouldn't ever be so massive. So I think the benefits outweigh the risks

Adding the job id column to the build image resource caches table will
be denormalizing the tables as the information is able to be fetched
from joining to the builds table. Even though it is breaking the current
norm of normalized tables within the database, it greatly improves the
speed of queries so that the queries no longer need to join to the large
builds table.

Signed-off-by: Clara Fu <[email protected]>
Signed-off-by: Clara Fu <[email protected]>
@aoldershaw

Copy link
Copy Markdown
Contributor

By the way, do you think it's worth backporting this optimization to 6.7.3?

@clarafu

clarafu commented Jan 7, 2021

Copy link
Copy Markdown
Contributor Author

@aoldershaw Is it because that is going to be the enterprise version?

@clarafu
clarafu merged commit 67f03e7 into master Jan 7, 2021
@clarafu
clarafu deleted the optimizations branch January 7, 2021 19:31
aoldershaw added a commit that referenced this pull request Feb 4, 2021
This reverts a dropped index from #5993. Since this
was never released, it shouldn't be a problem modifying the migration -
we'll just need to be careful when we deploy CI/Hush House

Signed-off-by: Aidan Oldershaw <[email protected]>
@aoldershaw aoldershaw mentioned this pull request Feb 4, 2021
11 tasks
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.

3 participants