[{"data":1,"prerenderedAt":834},["ShallowReactive",2],{"/en-us/blog/why-we-spent-the-last-month-eliminating-postgresql-subtransactions":3,"navigation-en-us":41,"banner-en-us":452,"footer-en-us":462,"blog-post-authors-en-us-Grzegorz Bizon|Stan Hu":704,"blog-related-posts-en-us-why-we-spent-the-last-month-eliminating-postgresql-subtransactions":730,"blog-promotions-en-us":771,"next-steps-en-us":824},{"id":4,"title":5,"authorSlugs":6,"authors":9,"body":12,"category":13,"categorySlug":13,"config":14,"content":18,"date":22,"description":19,"extension":27,"externalUrl":28,"featured":16,"heroImage":21,"isFeatured":16,"meta":29,"navigation":30,"path":31,"publishedDate":22,"rawbody":32,"seo":33,"slug":15,"stem":37,"tagSlugs":38,"tags":39,"template":17,"updatedDate":28,"__hash__":40},"blogPosts/en-us/blog/why-we-spent-the-last-month-eliminating-postgresql-subtransactions.yml","Why we spent the last month eliminating PostgreSQL subtransactions",[7,8],"grzegorz-bizon","stan-hu",[10,11],"Grzegorz Bizon","Stan Hu","Since last June, we noticed the database on GitLab.com would\nmysteriously stall for minutes, which would lead to users seeing 500\nerrors during this time. Through a painstaking investigation over\nseveral weeks, we finally uncovered the cause of this: initiating a\nsubtransaction via the [`SAVEPOINT` SQL query](https://www.postgresql.org/docs/current/sql-savepoint.html) while\na long transaction is in progress can wreak havoc on database\nreplicas. Thus launched a race, which we recently completed, to\neliminate all `SAVEPOINT` queries from our code. Here's what happened,\nhow we discovered the problem, and what we did to fix it.\n\n### The symptoms begin\n\nOn June 24th, we noticed that our CI/CD runners service reported a high\nerror rate:\n\n![runners errors](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/ci-runners-errors.png)\n\nA quick investigation revealed that database queries used to retrieve\nCI/CD builds data were timing out and that the unprocessed builds\nbacklog grew at a high rate:\n\n![builds queue](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/builds-queue.png)\n\nOur monitoring also showed that some of the SQL queries were waiting for\nPostgreSQL lightweight locks (`LWLocks`):\n\n![aggregated lwlocks](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/aggregated-lwlocks.png)\n\nIn the following weeks we had experienced a few incidents like this. We were\nsurprised to see how sudden these performance degradations were, and how\nquickly things could go back to normal:\n\n![ci queries latency](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/ci-queries-latency.png)\n\n### Introducing Nessie: Stalled database queries\n\nIn order to learn more, we extended our observability tooling [to sample\nmore data from `pg_stat_activity`](https://gitlab.com/gitlab-cookbooks/gitlab-exporters/-/merge_requests/231). In PostgreSQL, the `pg_stat_activity`\nvirtual table contains the list of all database connections in the system as\nwell as what they are waiting for, such as a SQL query from the\nclient. We observed a consistent pattern: the queries were waiting on\n`SubtransControlLock`. Below shows a graph of the URLs or jobs that were\nstalled:\n\n![endpoints locked](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/endpoints-locked.png)\n\nThe purple line shows the sampled number of transactions locked by\n`SubtransControlLock` for the `POST /api/v4/jobs/request` endpoint that\nwe use for internal communication between GitLab and GitLab Runners\nprocessing CI/CD jobs.\n\nAlthough this endpoint was impacted the most, the whole database cluster\nappeared to be affected as many other, unrelated queries timed out.\n\nThis same pattern would rear its head on random days. A week would pass\nby without incident, and then it would show up for 15 minutes and\ndisappear for days. Were we chasing the Loch Ness Monster?\n\nLet's call these stalled queries Nessie for fun and profit.\n\n### What is a `SAVEPOINT`?\n\nTo understand `SubtransControlLock` ([PostgreSQL\n13](https://www.postgresql.org/docs/13/monitoring-stats.html#MONITORING-PG-STAT-ACTIVITY-VIEW)\nrenamed this to `SubtransSLRU`), we first must understand how\nsubtransactions work in PostgreSQL. In PostgreSQL, a transaction can\nstart via a `BEGIN` statement, and a subtransaction can be started with\na subsequent `SAVEPOINT` query. PostgreSQL assigns each of these a\ntransaction ID (XID for short) [when a transaction or a subtransaction\nneeds one, usually before a client modifies data](https://gitlab.com/postgres/postgres/blob/a00c138b78521b9bc68b480490a8d601ecdeb816/src/backend/access/transam/README#L193-L198).\n\n#### Why would you use a `SAVEPOINT`?\n\nFor example, let's say you were running an online store and a customer\nplaced an order. Before the order is fullfilled, the system needs to\nensure a credit card account exists for that user. In Rails, a common\npattern is to start a transaction for the order and call\n[`find_or_create_by`](https://apidock.com/rails/v5.2.3/ActiveRecord/Relation/find_or_create_by). For\nexample:\n\n```ruby\nOrder.transaction do\n  begin\n    CreditAccount.transaction(requires_new: true) do\n      CreditAccount.find_or_create_by(customer_id: customer.id)\n  rescue ActiveRecord::RecordNotUnique\n    retry\n  end\n  # Fulfill the order\n  # ...\nend\n```\n\nIf two orders were placed around the same time, you wouldn't want the\ncreation of a duplicate account to fail one of the orders. Instead, you\nwould want the system to say, \"Oh, an account was just created; let me\nuse that.\"\n\nThat's where subtransactions come in handy: the `requires_new: true`\ntells Rails to start a new subtransaction if the application already is\nin a transaction. The code above translates into several SQL calls that\nlook something like:\n```sql\n--- Start a transaction\nBEGIN\nSAVEPOINT active_record_1\n--- Look up the account\nSELECT * FROM credit_accounts WHERE customer_id = 1\n--- Insert the account; this may fail due to a duplicate constraint\nINSERT INTO credit_accounts (customer_id) VALUES (1)\n--- Abort this by rolling back\nROLLBACK TO active_record_1\n--- Retry here: Start a new subtransaction\nSAVEPOINT active_record_2\n--- Find the newly-created account\nSELECT * FROM credit_accounts WHERE customer_id = 1\n--- Save the data\nRELEASE SAVEPOINT active_record_2\nCOMMIT\n```\n\nOn line 7 above, the `INSERT` might fail if the customer account was\nalready created, and the database unique constraint would prevent a\nduplicate entry. Without the first `SAVEPOINT` and `ROLLBACK` block, the\nwhole transaction would have failed. With that subtransaction, the\ntransaction can retry gracefully and look up the existing account.\n\n### What is `SubtransControlLock`?\n\nAs we mentioned earlier, Nessie returned at random times with queries\nwaiting for `SubtransControlLock`. `SubtransControlLock` indicates that\nthe query is waiting for PostgreSQL to load subtransaction data from\ndisk into shared memory.\n\nWhy is this data needed? When a client runs a `SELECT`, for example,\nPostgreSQL needs to decide whether each version of a row, known as a\ntuple, is actually visible within the current transaction. It's possible\nthat a tuple has been deleted or has yet to be committed by another\ntransaction. Since only a top-level transaction can actually commit\ndata, PostgreSQL needs to map a subtransaction ID (subXID) to its parent\nXID.\n\nThis mapping of subXID to parent XID is stored on disk in the\n`pg_subtrans` directory. Since reading from disk is slow, PostgreSQL\nadds a simple least-recently used (SLRU) cache in front for each\nbackend process. The lookup is fast if the desired page is already\ncached. However, as [Laurenz Albe discussed in his blog\npost](https://www.cybertec-postgresql.com/en/subtransactions-and-performance-in-postgresql/),\nPostgreSQL may need to read from disk if the number of active\nsubtransactions exceeds 64 in a given transaction, a condition\nPostgreSQL terms `suboverflow`. Think of it as the feeling you might get\nif you ate too many Subway sandwiches.\n\nSuboverflowing (is that a word?) can bog down performance because as\nLaurenz said, \"Other transactions have to update `pg_subtrans` to\nregister subtransactions, and you can see in the perf output how they\nvie for lightweight locks with the readers.\"\n\n### Hunting for nested subtransactions\n\nLaurenz's blog post suggested that we might be using too many\nsubtransactions in one transaction. At first, we suspected we might be\ndoing this in some of our expensive background jobs, such as project\nexport or import. However, while we did see numerous `SAVEPOINT` calls\nin these jobs, we didn't see an unusual degree of nesting in local\ntesting.\n\nTo isolate the cause, we started by [adding Prometheus metrics to track\nsubtransactions as a Prometheus metric by model](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66477).\nThis led to nice graphs as the following:\n\n![subtransactions plot](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/subtransactions-plot.png)\n\nWhile this was helpful in seeing the rate of subtransactions over time,\nwe didn't see any obvious spikes that occurred around the time of the\ndatabase stalls. Still, it was possible that suboverflow was happening.\n\nTo see if that was happening, we [instrumented our application to track\nsubtransactions and log a message whenever we detected more than 32\n`SAVEPOINT` calls in a given transaction](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67918). Rails\nmakes it possible for the application to subscribe to all of its SQL\nqueries via `ActiveSupport` notifications. Our instrumentation looked\nsomething like this, simplified for the purposes of discussion:\n\n```ruby\nActiveSupport::Notifications.subscribe('sql.active_record') do |event|\n  sql = event.payload.dig(:sql).to_s\n  connection = event.payload[:connection]\n  manager = connection&.transaction_manager\n\n  context = manager.transaction_context\n  return if context.nil?\n\n  if sql.start_with?('BEGIN')\n    context.set_depth(0)\n  elsif cmd.start_with?('SAVEPOINT', 'EXCEPTION')\n    context.increment_savepoints\n  elsif cmd.start_with?('ROLLBACK TO SAVEPOINT')\n    context.increment_rollbacks\n  elsif cmd.start_with?('RELEASE SAVEPOINT')\n    context.increment_releases\n  elsif sql.start_with?('COMMIT', 'ROLLBACK')\n    context.finish_transaction\n  end\nend\n```\n\nThis code looks for the key SQL commands that initiate transactions and\nsubtransactions and increments counters when they occurred. After a\n`COMMIT,` we log a JSON message that contained the backtrace and the\nnumber of `SAVEPOINT` and `RELEASES` calls. For example:\n\n```json\n{\n  \"sql\": \"/*application:web,correlation_id:01FEBFH1YTMSFEEHS57FA8C6JX,endpoint_id:POST /api/:version/projects/:id/merge_requests/:merge_request_iid/approve*/ BEGIN\",\n  \"savepoints_count\": 1,\n  \"savepoint_backtraces\": [\n    [\n      \"app/models/application_record.rb:75:in `block in safe_find_or_create_by'\",\n      \"app/models/application_record.rb:75:in `safe_find_or_create_by'\",\n      \"app/models/merge_request.rb:1859:in `ensure_metrics'\",\n      \"ee/lib/analytics/merge_request_metrics_refresh.rb:11:in `block in execute'\",\n      \"ee/lib/analytics/merge_request_metrics_refresh.rb:10:in `each'\",\n      \"ee/lib/analytics/merge_request_metrics_refresh.rb:10:in `execute'\",\n      \"ee/app/services/ee/merge_requests/approval_service.rb:57:in `calculate_approvals_metrics'\",\n      \"ee/app/services/ee/merge_requests/approval_service.rb:45:in `block in create_event'\",\n      \"ee/app/services/ee/merge_requests/approval_service.rb:43:in `create_event'\",\n      \"app/services/merge_requests/approval_service.rb:13:in `execute'\",\n      \"ee/app/services/ee/merge_requests/approval_service.rb:14:in `execute'\",\n      \"lib/api/merge_request_approvals.rb:58:in `block (3 levels) in \u003Cclass:MergeRequestApprovals>'\",\n    ]\n  \"rollbacks_count\": 0,\n  \"releases_count\": 1\n}\n```\n\nThis log message contains not only the number of subtransactions via\n`savepoints_count`, but it also contains a handy backtrace that\nidentifies the exact source of the problem. The `sql` field also\ncontains [Marginalia comments](https://github.com/basecamp/marginalia)\nthat we tack onto every SQL query. These comments make it possible to\nidentify what HTTP request initiated the SQL query.\n\n### Taking a hard look at PostgreSQL\n\nThe new instrumentation showed that while the application regularly used\nsubtransactions, it never exceeded 10 nested `SAVEPOINT` calls.\n\nMeanwhile, [Nikolay Samokhvalov](https://gitlab.com/NikolayS), founder\nof [Postgres.ai](https://postgres.ai/), performed a battery of tests [trying to replicate the problem](https://gitlab.com/postgres-ai/postgresql-consulting/tests-and-benchmarks/-/issues/20).\nHe replicated Laurenz's results when a single transaction exceeded 64\nsubtransactions, but that wasn't happening here.\n\nWhen the database stalls occurred, we observed a number of patterns:\n\n1. Only the replicas were affected; the primary remained unaffected.\n1. There was a long-running transaction, usually relating to\nPostgreSQL's autovacuuming, during the time. The stalls stopped quickly after the transaction ended.\n\nWhy would this matter? Analyzing the PostgreSQL source code, Senior\nSupport Engineer [Catalin Irimie](https://gitlab.com/cat) [posed an\nintriguing question that led to a breakthrough in our understanding](https://gitlab.com/gitlab-org/gitlab/-/issues/338410#note_652056284):\n\n> Does this mean that, having subtransactions spanning more than 32 cache pages, concurrently, would trigger the exclusive SubtransControlLock because we still end up reading them from the disk?\n\n### Reproducing the problem with replicas\n\nTo answer this, Nikolay immediately modified his test [to involve replicas and long-running transactions](https://gitlab.com/postgres-ai/postgresql-consulting/tests-and-benchmarks/-/issues/21#note_653453774). Within a day, he reproduced the problem:\n\n![Nikolay experiment](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/nikolay-experiment.png)\n\nThe image above shows that transaction rates remain steady around\n360,000 transactions per second (TPS). Everything was proceeding fine\nuntil the long-running transaction started on the primary. Then suddenly\nthe transaction rates plummeted to 50,000 TPS on the replicas. Canceling\nthe long transaction immediately caused the transaction rate to return.\n\n### What is going on here?\n\nIn his blog post, Nikolay called the problem [Subtrans SLRU overflow](https://v2.postgres.ai/blog/20210831-postgresql-subtransactions-considered-harmful#problem-4-subtrans-slru-overflow).\nIn a busy database, it's possible for the size of the subtransaction log\nto grow so large that the working set no longer fits into memory. This\nresults in a lot of cache misses, which in turn causes a high amount of\ndisk I/O and CPU as PostgreSQL furiously tries to load data from disk to\nkeep up with all the lookups.\n\nAs mentioned earlier, the subtransaction cache holds a mapping of the\nsubXID to the parent XID. When PostgreSQL needs to look up the subXID,\nit calculates in which memory page this ID would live, and then does a\nlinear search to find in the memory page. If the page is not in the\ncache, it evicts one page and loads the desired one into memory. The\ndiagram below shows the memory layout of the subtransaction SLRU.\n\n![Subtrans SLRU](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/subtrans-slru.png)\n\nBy default, each SLRU page is an 8K buffer holding 4-byte parent\nXIDs. This means 8192/4 = 2048 transaction IDs can be stored in each\npage.\n\nNote that there may be gaps in each page. PostgreSQL will cache XIDs as\nneeded, so a single XID can occupy an entire page.\n\nThere are 32 (`NUM_SUBTRANS_BUFFERS`) pages, which means up to 65K\ntransaction IDs can be stored in memory. Nikolay demonstrated that in a\nbusy system, it took about 18 seconds to fill up all 65K entries. Then\nperformance dropped off a cliff, making the database replicas unusable.\n\nTo our surprise, our experiments also demonstrated that a single\n`SAVEPOINT` during a long-transaction [could initiate this problem if\nmany writes also occurred simultaneously](https://gitlab.com/gitlab-org/gitlab/-/issues/338865#note_655312474). That\nis, it wasn't enough just to reduce the frequency of `SAVEPOINT`; we had\nto eliminate them completely.\n\n#### Why does a single `SAVEPOINT` cause problems?\n\nTo answer this question, we need to understand what happens when a\n`SAVEPOINT` occurs in one query while a long-running transaction is\nrunning.\n\nWe mentioned earlier that PostgreSQL needs to decide whether a given row\nis visible to support a feature called [multi-version concurrency control](https://www.postgresql.org/docs/current/mvcc.html), or MVCC for\nshort. It does this by storing hidden columns, `xmin` and `xmax`, in\neach tuple.\n\n`xmin` holds the XID of when the tuple was created, and `xmax` holds the\nXID when it was marked as dead (0 if the row is still present). In\naddition, at the beginning of a transaction, PostgreSQL records metadata\nin a database snapshot. Among other items, this snapshot records the\noldest XID and the newest XID in its own `xmin` and `xmax` values.\n\nThis metadata helps [PostgreSQL determine whether a tuple is visible](https://www.interdb.jp/pg/pgsql05.html).\nFor example, a committed XID that started before `xmin` is definitely\nvisible, while anything after `xmax` is invisible.\n\n### What does this have to do with long transactions?\n\nLong transactions are bad in general because they can tie up\nconnections, but they can cause a subtly different problem on a\nreplica. On the replica, a single `SAVEPOINT` during a long transaction\ncauses a snapshot to suboverflow. Remember that dragged down performance\nin the case where we had more than 64 subtransactions.\n\nFundamentally, the problem happens because a replica behaves differently\nfrom a primary when creating snapshots and checking for tuple\nvisibility. The diagram below illustrates an example with some of the\ndata structures used in PostgreSQL:\n\n![Diagram of subtransaction handling in replicas](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/pg-replica-subtransaction-diagram.png)\n\nOn the top of this diagram, we can see the XIDs increase at the\nbeginning of a subtransaction: the `INSERT` after the `BEGIN` gets 1,\nand the subsequent `INSERT` in `SAVEPOINT` gets 2. Another client comes\nalong and performs a `INSERT` and `SELECT` at XID 3.\n\nOn the primary, PostgreSQL stores the transactions in progress in a\nshared memory segment. The process array (`procarray`) stores XID 1 with\nthe first connection, and the database also writes that information to\nthe `pg_xact` directory. XID 2 gets stored in the `pg_subtrans`\ndirectory, mapped to its parent, XID 1.\n\nIf a read happens on the primary, the snapshot generated contains `xmin`\nas 1, and `xmax` as 3. `txip` holds a list of transactions in progress,\nand `subxip` holds a list of subtransactions in progress.\n\nHowever, neither the `procarray` nor the snapshot are shared directly\nwith the replica. The replica receives all the data it needs from the\nwrite-ahead log (WAL).\n\nPlaying the WAL back one entry at time, the replica populates a shared data\nstructure called `KnownAssignedIds`. It contains all the transactions in\nprogress on the primary. Since this structure can only hold a limited number of\nIDs, a busy database with a lot of active subtransactions could easily fill\nthis buffer. PostgreSQL made a design choice to kick out all subXIDs from this\nlist and store them in the `pg_subtrans` directory.\n\nWhen a snapshot is generated on the replica, notice how `txip` is\nblank. A PostgreSQL replica treats **all** XIDs as though they are\nsubtransactions and throws them into the `subxip` bucket. That works\nbecause if a XID has a parent XID, then it's a subtransaction. Otherwise, it's a normal transaction. [The code comments\nexplain the rationale](https://gitlab.com/postgres/postgres/blob/9f540f840665936132dd30bd8e58e9a67e648f22/src/backend/storage/ipc/procarray.c#L1665-L1681).\n\nHowever, this means the snapshot is missing subXIDs, and that could be\nbad for MVCC. To deal with that, the [replica also updates `lastOverflowedXID`](https://gitlab.com/postgres/postgres/blob/9f540f840665936132dd30bd8e58e9a67e648f22/src/backend/storage/ipc/procarray.c#L3176-L3182):\n\n```c\n\n * When we throw away subXIDs from KnownAssignedXids, we need to keep track of\n * that, similarly to tracking overflow of a PGPROC's subxids array.  We do\n * that by remembering the lastOverflowedXID, ie the last thrown-away subXID.\n * As long as that is within the range of interesting XIDs, we have to assume\n * that subXIDs are missing from snapshots.  (Note that subXID overflow occurs\n * on primary when 65th subXID arrives, whereas on standby it occurs when 64th\n * subXID arrives - that is not an error.)\n\n```\n\nWhat is this \"range of interesting XIDs\"? We can see this in [the code below](https://gitlab.com/postgres/postgres/blob/4bf0bce161097869be5a56706b31388ba15e0113/src/backend/storage/ipc/procarray.c#L1702-L1703):\n\n```c\nif (TransactionIdPrecedesOrEquals(xmin, procArray->lastOverflowedXid))\n    suboverflowed = true;\n\n```\n\nIf `lastOverflowedXid` is smaller than our snapshot's `xmin`, it means\nthat all subtransactions have completed, so we don't need to check for\nsubtransactions. However, in our example:\n\n1. `xmin` is 1 because of the transaction.\n2. `lastOverflowXid` is 2 because of the `SAVEPOINT`.\n\nThis means `suboverflowed` is set to `true` here, which tells PostgreSQL\nthat whenever a XID needs to be checked, check to see if it has a parent\nXID. Remember that this causes PostgreSQL to:\n\n1. Look up the subXID for the parent XID in the SLRU cache.\n1. If this doesn't exist in the cache, fetch the data from `pg_trans`.\n\nIn a busy system, the requested XIDs could span an ever-growing range of\nvalues, which could easily exhaust the 64K entries in the SLRU\ncache. This range will continue to grow as long as the transaction runs;\nthe rate of increase depends on how many updates are happening on the\nprmary. As soon as the transaction terminates, the `suboverflowed` state\ngets set to `false`.\n\nIn other words, we've replicated the same conditions as we saw with 64\nsubtransactions, only with a single `SAVEPOINT` and a long transaction.\n\n### What can we do about getting rid of Nessie?\n\nThere are three options:\n\n1. Eliminate `SAVEPOINT` calls completely.\n1. Eliminate all long-running transactions.\n1. Apply [Andrey Borodin's patches to PostgreSQL and increase the subtransaction cache](https://www.postgresql.org/message-id/flat/494C5E7F-E410-48FA-A93E-F7723D859561%40yandex-team.ru#18c79477bf7fc44a3ac3d1ce55e4c169).\n\nWe chose the first option because most uses of subtransaction could be\nremoved fairly easily. There were a [number of approaches](https://gitlab.com/groups/gitlab-org/-/epics/6540) we took:\n\n1. Perform updates outside of a subtransaction. Examples: [1](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68471), [2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68690)\n1. Rewrite a query to use a `INSERT` or an `UPDATE` with an `ON CONFLICT` clause to deal with duplicate constraint violations. Examples: [1](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68433), [2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/69240), [3](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68509)\n1. Live with a non-atomic `find_or_create_by`. We used this approach sparingly. Example: [1](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68649)\n\nIn addition, we added [an alert whenever the application used a a single `SAVEPOINT`](https://gitlab.com/gitlab-com/runbooks/-/merge_requests/3881):\n\n![subtransaction alert](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/subtransactions-alert-example.png)\n\nThis had the side benefit of flagging a [minor bug](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/70889).\n\n#### Why not eliminate all long-running transactions?\n\nIn our database, it wasn't practical to eliminate all long-running\ntransactions because we think many of them happened via [database\nautovacuuming](https://www.postgresql.org/docs/current/runtime-config-autovacuum.html),\nbut [we're not able to reproduce this yet](https://gitlab.com/postgres-ai/postgresql-consulting/tests-and-benchmarks/-/issues/21#note_669698320).\nWe are working on partitioning the tables and sharding the database, but this is a much more time-consuming problem\nthan removing all subtransactions.\n\n#### What about the PostgreSQL patches?\n\nAlthough we tested Andrey's PostgreSQL patches, we did not feel comfortable\ndeviating from the official PostgreSQL releases. Plus, maintaining a\ncustom patched release over upgrades would add a significant maintenance\nburden for our infrastructure team. Our self-managed customers would\nalso not benefit unless they used a patched database.\n\nAndrey's patches do two main things:\n\n1. Allow administrators to change the SLRU size to any value.\n1. Adds an [associative cache](https://www.youtube.com/watch?v=A0vR-ks3hsQ).\nto make it performant to use a large cache value.\n\nRemember that the SLRU cache does a linear search for the desired\npage. That works fine when there are only 32 pages to search, but if you\nincrease the cache size to 100 MB the search becomes much more\nexpensive. The associative cache makes the lookup fast by indexing pages\nwith a bitmask and looking up the entry with offsets from the remaining\nbits. This mitigates the problem because a transaction would need to be\nseveral magnitudes longer to cause a problem.\n\nNikolay demonstrated that the `SAVEPOINT` problem disappeared as soon as\nwe increased the SLRU size to 100 MB with those patches. With a 100 MB\ncache, PostgreSQL can cache 26.2 million IDs (104857600/4), far more\nthan the measely 65K.\n\nThese [patches are currently awaiting review](https://postgres.ai/blog/20210831-postgresql-subtransactions-considered-harmful#ideas-for-postgresql-development),\nbut in our opinion they should be given high priority for PostgreSQL 15.\n\n### Conclusion\n\nSince removing all `SAVEPOINT` queries, we have not seen Nessie rear her\nhead again. If you are running PostgreSQL with read replicas, we\nstrongly recommend that you also remove *all* subtransactions until\nfurther notice.\n\nPostgreSQL is a fantastic database, and its well-commented code makes it\npossible to understand its limitations under different configurations.\n\nWe would like to thank the GitLab community for bearing with us while we\niron out this production issue.\n\nWe are also grateful for the support from [Nikolay\nSamokhvalov](https://gitlab.com/NikolayS) and [Catalin\nIrimie](https://gitlab.com/cat), who contributed to understanding where our\nLoch Ness Monster was hiding.\n\nCover image by [Khadi Ganiev](https://www.istockphoto.com/portfolio/Ganiev?mediatype=photography) on [iStock](https://istock.com), licensed under [standard license](https://www.istockphoto.com/legal/license-agreement)\n","engineering",{"slug":15,"featured":16,"template":17},"why-we-spent-the-last-month-eliminating-postgresql-subtransactions",false,"BlogPost",{"title":5,"description":19,"authors":20,"heroImage":21,"date":22,"body":12,"category":13,"tags":23},"How a mysterious stall in database queries uncovered a performance limitation with PostgreSQL.",[10,11],"https://res.cloudinary.com/about-gitlab-com/image/upload/v1749669470/Blog/Hero%20Images/nessie.jpg","2021-09-29",[24,25,26],"performance","contributors","frontend","yml",null,{},true,"/en-us/blog/why-we-spent-the-last-month-eliminating-postgresql-subtransactions","seo:\n  title: Why we spent the last month eliminating PostgreSQL subtransactions\n  description: >-\n    How a mysterious stall in database queries uncovered a performance\n    limitation with PostgreSQL.\n  ogTitle: Why we spent the last month eliminating PostgreSQL subtransactions\n  ogDescription: >-\n    How a mysterious stall in database queries uncovered a performance\n    limitation with PostgreSQL.\n  noIndex: false\n  ogImage: >-\n    https://res.cloudinary.com/about-gitlab-com/image/upload/v1749669470/Blog/Hero%20Images/nessie.jpg\n  ogUrl: >-\n    https://about.gitlab.com/blog/why-we-spent-the-last-month-eliminating-postgresql-subtransactions\n  ogSiteName: https://about.gitlab.com\n  ogType: article\n  canonicalUrls: >-\n    https://about.gitlab.com/blog/why-we-spent-the-last-month-eliminating-postgresql-subtransactions\ncontent:\n  title: Why we spent the last month eliminating PostgreSQL subtransactions\n  description: >-\n    How a mysterious stall in database queries uncovered a performance\n    limitation with PostgreSQL.\n  authors:\n    - Grzegorz Bizon\n    - Stan Hu\n  heroImage: >-\n    https://res.cloudinary.com/about-gitlab-com/image/upload/v1749669470/Blog/Hero%20Images/nessie.jpg\n  date: '2021-09-29'\n  body: >\n    Since last June, we noticed the database on GitLab.com would\n\n    mysteriously stall for minutes, which would lead to users seeing 500\n\n    errors during this time. Through a painstaking investigation over\n\n    several weeks, we finally uncovered the cause of this: initiating a\n\n    subtransaction via the [`SAVEPOINT` SQL\n    query](https://www.postgresql.org/docs/current/sql-savepoint.html) while\n\n    a long transaction is in progress can wreak havoc on database\n\n    replicas. Thus launched a race, which we recently completed, to\n\n    eliminate all `SAVEPOINT` queries from our code. Here's what happened,\n\n    how we discovered the problem, and what we did to fix it.\n\n\n    ### The symptoms begin\n\n\n    On June 24th, we noticed that our CI/CD runners service reported a high\n\n    error rate:\n\n\n    ![runners\n    errors](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/ci-runners-errors.png)\n\n\n    A quick investigation revealed that database queries used to retrieve\n\n    CI/CD builds data were timing out and that the unprocessed builds\n\n    backlog grew at a high rate:\n\n\n    ![builds\n    queue](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/builds-queue.png)\n\n\n    Our monitoring also showed that some of the SQL queries were waiting for\n\n    PostgreSQL lightweight locks (`LWLocks`):\n\n\n    ![aggregated\n    lwlocks](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/aggregated-lwlocks.png)\n\n\n    In the following weeks we had experienced a few incidents like this. We were\n\n    surprised to see how sudden these performance degradations were, and how\n\n    quickly things could go back to normal:\n\n\n    ![ci queries\n    latency](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/ci-queries-latency.png)\n\n\n    ### Introducing Nessie: Stalled database queries\n\n\n    In order to learn more, we extended our observability tooling [to sample\n\n    more data from\n    `pg_stat_activity`](https://gitlab.com/gitlab-cookbooks/gitlab-exporters/-/merge_requests/231).\n    In PostgreSQL, the `pg_stat_activity`\n\n    virtual table contains the list of all database connections in the system as\n\n    well as what they are waiting for, such as a SQL query from the\n\n    client. We observed a consistent pattern: the queries were waiting on\n\n    `SubtransControlLock`. Below shows a graph of the URLs or jobs that were\n\n    stalled:\n\n\n    ![endpoints\n    locked](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/endpoints-locked.png)\n\n\n    The purple line shows the sampled number of transactions locked by\n\n    `SubtransControlLock` for the `POST /api/v4/jobs/request` endpoint that\n\n    we use for internal communication between GitLab and GitLab Runners\n\n    processing CI/CD jobs.\n\n\n    Although this endpoint was impacted the most, the whole database cluster\n\n    appeared to be affected as many other, unrelated queries timed out.\n\n\n    This same pattern would rear its head on random days. A week would pass\n\n    by without incident, and then it would show up for 15 minutes and\n\n    disappear for days. Were we chasing the Loch Ness Monster?\n\n\n    Let's call these stalled queries Nessie for fun and profit.\n\n\n    ### What is a `SAVEPOINT`?\n\n\n    To understand `SubtransControlLock` ([PostgreSQL\n\n    13](https://www.postgresql.org/docs/13/monitoring-stats.html#MONITORING-PG-STAT-ACTIVITY-VIEW)\n\n    renamed this to `SubtransSLRU`), we first must understand how\n\n    subtransactions work in PostgreSQL. In PostgreSQL, a transaction can\n\n    start via a `BEGIN` statement, and a subtransaction can be started with\n\n    a subsequent `SAVEPOINT` query. PostgreSQL assigns each of these a\n\n    transaction ID (XID for short) [when a transaction or a subtransaction\n\n    needs one, usually before a client modifies\n    data](https://gitlab.com/postgres/postgres/blob/a00c138b78521b9bc68b480490a8d601ecdeb816/src/backend/access/transam/README#L193-L198).\n\n\n    #### Why would you use a `SAVEPOINT`?\n\n\n    For example, let's say you were running an online store and a customer\n\n    placed an order. Before the order is fullfilled, the system needs to\n\n    ensure a credit card account exists for that user. In Rails, a common\n\n    pattern is to start a transaction for the order and call\n\n    [`find_or_create_by`](https://apidock.com/rails/v5.2.3/ActiveRecord/Relation/find_or_create_by).\n    For\n\n    example:\n\n\n    ```ruby\n\n    Order.transaction do\n      begin\n        CreditAccount.transaction(requires_new: true) do\n          CreditAccount.find_or_create_by(customer_id: customer.id)\n      rescue ActiveRecord::RecordNotUnique\n        retry\n      end\n      # Fulfill the order\n      # ...\n    end\n\n    ```\n\n\n    If two orders were placed around the same time, you wouldn't want the\n\n    creation of a duplicate account to fail one of the orders. Instead, you\n\n    would want the system to say, \"Oh, an account was just created; let me\n\n    use that.\"\n\n\n    That's where subtransactions come in handy: the `requires_new: true`\n\n    tells Rails to start a new subtransaction if the application already is\n\n    in a transaction. The code above translates into several SQL calls that\n\n    look something like:\n\n    ```sql\n\n    --- Start a transaction\n\n    BEGIN\n\n    SAVEPOINT active_record_1\n\n    --- Look up the account\n\n    SELECT * FROM credit_accounts WHERE customer_id = 1\n\n    --- Insert the account; this may fail due to a duplicate constraint\n\n    INSERT INTO credit_accounts (customer_id) VALUES (1)\n\n    --- Abort this by rolling back\n\n    ROLLBACK TO active_record_1\n\n    --- Retry here: Start a new subtransaction\n\n    SAVEPOINT active_record_2\n\n    --- Find the newly-created account\n\n    SELECT * FROM credit_accounts WHERE customer_id = 1\n\n    --- Save the data\n\n    RELEASE SAVEPOINT active_record_2\n\n    COMMIT\n\n    ```\n\n\n    On line 7 above, the `INSERT` might fail if the customer account was\n\n    already created, and the database unique constraint would prevent a\n\n    duplicate entry. Without the first `SAVEPOINT` and `ROLLBACK` block, the\n\n    whole transaction would have failed. With that subtransaction, the\n\n    transaction can retry gracefully and look up the existing account.\n\n\n    ### What is `SubtransControlLock`?\n\n\n    As we mentioned earlier, Nessie returned at random times with queries\n\n    waiting for `SubtransControlLock`. `SubtransControlLock` indicates that\n\n    the query is waiting for PostgreSQL to load subtransaction data from\n\n    disk into shared memory.\n\n\n    Why is this data needed? When a client runs a `SELECT`, for example,\n\n    PostgreSQL needs to decide whether each version of a row, known as a\n\n    tuple, is actually visible within the current transaction. It's possible\n\n    that a tuple has been deleted or has yet to be committed by another\n\n    transaction. Since only a top-level transaction can actually commit\n\n    data, PostgreSQL needs to map a subtransaction ID (subXID) to its parent\n\n    XID.\n\n\n    This mapping of subXID to parent XID is stored on disk in the\n\n    `pg_subtrans` directory. Since reading from disk is slow, PostgreSQL\n\n    adds a simple least-recently used (SLRU) cache in front for each\n\n    backend process. The lookup is fast if the desired page is already\n\n    cached. However, as [Laurenz Albe discussed in his blog\n\n    post](https://www.cybertec-postgresql.com/en/subtransactions-and-performance-in-postgresql/),\n\n    PostgreSQL may need to read from disk if the number of active\n\n    subtransactions exceeds 64 in a given transaction, a condition\n\n    PostgreSQL terms `suboverflow`. Think of it as the feeling you might get\n\n    if you ate too many Subway sandwiches.\n\n\n    Suboverflowing (is that a word?) can bog down performance because as\n\n    Laurenz said, \"Other transactions have to update `pg_subtrans` to\n\n    register subtransactions, and you can see in the perf output how they\n\n    vie for lightweight locks with the readers.\"\n\n\n    ### Hunting for nested subtransactions\n\n\n    Laurenz's blog post suggested that we might be using too many\n\n    subtransactions in one transaction. At first, we suspected we might be\n\n    doing this in some of our expensive background jobs, such as project\n\n    export or import. However, while we did see numerous `SAVEPOINT` calls\n\n    in these jobs, we didn't see an unusual degree of nesting in local\n\n    testing.\n\n\n    To isolate the cause, we started by [adding Prometheus metrics to track\n\n    subtransactions as a Prometheus metric by\n    model](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/66477).\n\n    This led to nice graphs as the following:\n\n\n    ![subtransactions\n    plot](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/subtransactions-plot.png)\n\n\n    While this was helpful in seeing the rate of subtransactions over time,\n\n    we didn't see any obvious spikes that occurred around the time of the\n\n    database stalls. Still, it was possible that suboverflow was happening.\n\n\n    To see if that was happening, we [instrumented our application to track\n\n    subtransactions and log a message whenever we detected more than 32\n\n    `SAVEPOINT` calls in a given\n    transaction](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/67918).\n    Rails\n\n    makes it possible for the application to subscribe to all of its SQL\n\n    queries via `ActiveSupport` notifications. Our instrumentation looked\n\n    something like this, simplified for the purposes of discussion:\n\n\n    ```ruby\n\n    ActiveSupport::Notifications.subscribe('sql.active_record') do |event|\n      sql = event.payload.dig(:sql).to_s\n      connection = event.payload[:connection]\n      manager = connection&.transaction_manager\n\n      context = manager.transaction_context\n      return if context.nil?\n\n      if sql.start_with?('BEGIN')\n        context.set_depth(0)\n      elsif cmd.start_with?('SAVEPOINT', 'EXCEPTION')\n        context.increment_savepoints\n      elsif cmd.start_with?('ROLLBACK TO SAVEPOINT')\n        context.increment_rollbacks\n      elsif cmd.start_with?('RELEASE SAVEPOINT')\n        context.increment_releases\n      elsif sql.start_with?('COMMIT', 'ROLLBACK')\n        context.finish_transaction\n      end\n    end\n\n    ```\n\n\n    This code looks for the key SQL commands that initiate transactions and\n\n    subtransactions and increments counters when they occurred. After a\n\n    `COMMIT,` we log a JSON message that contained the backtrace and the\n\n    number of `SAVEPOINT` and `RELEASES` calls. For example:\n\n\n    ```json\n\n    {\n      \"sql\": \"/*application:web,correlation_id:01FEBFH1YTMSFEEHS57FA8C6JX,endpoint_id:POST /api/:version/projects/:id/merge_requests/:merge_request_iid/approve*/ BEGIN\",\n      \"savepoints_count\": 1,\n      \"savepoint_backtraces\": [\n        [\n          \"app/models/application_record.rb:75:in `block in safe_find_or_create_by'\",\n          \"app/models/application_record.rb:75:in `safe_find_or_create_by'\",\n          \"app/models/merge_request.rb:1859:in `ensure_metrics'\",\n          \"ee/lib/analytics/merge_request_metrics_refresh.rb:11:in `block in execute'\",\n          \"ee/lib/analytics/merge_request_metrics_refresh.rb:10:in `each'\",\n          \"ee/lib/analytics/merge_request_metrics_refresh.rb:10:in `execute'\",\n          \"ee/app/services/ee/merge_requests/approval_service.rb:57:in `calculate_approvals_metrics'\",\n          \"ee/app/services/ee/merge_requests/approval_service.rb:45:in `block in create_event'\",\n          \"ee/app/services/ee/merge_requests/approval_service.rb:43:in `create_event'\",\n          \"app/services/merge_requests/approval_service.rb:13:in `execute'\",\n          \"ee/app/services/ee/merge_requests/approval_service.rb:14:in `execute'\",\n          \"lib/api/merge_request_approvals.rb:58:in `block (3 levels) in \u003Cclass:MergeRequestApprovals>'\",\n        ]\n      \"rollbacks_count\": 0,\n      \"releases_count\": 1\n    }\n\n    ```\n\n\n    This log message contains not only the number of subtransactions via\n\n    `savepoints_count`, but it also contains a handy backtrace that\n\n    identifies the exact source of the problem. The `sql` field also\n\n    contains [Marginalia comments](https://github.com/basecamp/marginalia)\n\n    that we tack onto every SQL query. These comments make it possible to\n\n    identify what HTTP request initiated the SQL query.\n\n\n    ### Taking a hard look at PostgreSQL\n\n\n    The new instrumentation showed that while the application regularly used\n\n    subtransactions, it never exceeded 10 nested `SAVEPOINT` calls.\n\n\n    Meanwhile, [Nikolay Samokhvalov](https://gitlab.com/NikolayS), founder\n\n    of [Postgres.ai](https://postgres.ai/), performed a battery of tests [trying\n    to replicate the\n    problem](https://gitlab.com/postgres-ai/postgresql-consulting/tests-and-benchmarks/-/issues/20).\n\n    He replicated Laurenz's results when a single transaction exceeded 64\n\n    subtransactions, but that wasn't happening here.\n\n\n    When the database stalls occurred, we observed a number of patterns:\n\n\n    1. Only the replicas were affected; the primary remained unaffected.\n\n    1. There was a long-running transaction, usually relating to\n\n    PostgreSQL's autovacuuming, during the time. The stalls stopped quickly\n    after the transaction ended.\n\n\n    Why would this matter? Analyzing the PostgreSQL source code, Senior\n\n    Support Engineer [Catalin Irimie](https://gitlab.com/cat) [posed an\n\n    intriguing question that led to a breakthrough in our\n    understanding](https://gitlab.com/gitlab-org/gitlab/-/issues/338410#note_652056284):\n\n\n    > Does this mean that, having subtransactions spanning more than 32 cache\n    pages, concurrently, would trigger the exclusive SubtransControlLock because\n    we still end up reading them from the disk?\n\n\n    ### Reproducing the problem with replicas\n\n\n    To answer this, Nikolay immediately modified his test [to involve replicas\n    and long-running\n    transactions](https://gitlab.com/postgres-ai/postgresql-consulting/tests-and-benchmarks/-/issues/21#note_653453774).\n    Within a day, he reproduced the problem:\n\n\n    ![Nikolay\n    experiment](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/nikolay-experiment.png)\n\n\n    The image above shows that transaction rates remain steady around\n\n    360,000 transactions per second (TPS). Everything was proceeding fine\n\n    until the long-running transaction started on the primary. Then suddenly\n\n    the transaction rates plummeted to 50,000 TPS on the replicas. Canceling\n\n    the long transaction immediately caused the transaction rate to return.\n\n\n    ### What is going on here?\n\n\n    In his blog post, Nikolay called the problem [Subtrans SLRU\n    overflow](https://v2.postgres.ai/blog/20210831-postgresql-subtransactions-considered-harmful#problem-4-subtrans-slru-overflow).\n\n    In a busy database, it's possible for the size of the subtransaction log\n\n    to grow so large that the working set no longer fits into memory. This\n\n    results in a lot of cache misses, which in turn causes a high amount of\n\n    disk I/O and CPU as PostgreSQL furiously tries to load data from disk to\n\n    keep up with all the lookups.\n\n\n    As mentioned earlier, the subtransaction cache holds a mapping of the\n\n    subXID to the parent XID. When PostgreSQL needs to look up the subXID,\n\n    it calculates in which memory page this ID would live, and then does a\n\n    linear search to find in the memory page. If the page is not in the\n\n    cache, it evicts one page and loads the desired one into memory. The\n\n    diagram below shows the memory layout of the subtransaction SLRU.\n\n\n    ![Subtrans\n    SLRU](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/subtrans-slru.png)\n\n\n    By default, each SLRU page is an 8K buffer holding 4-byte parent\n\n    XIDs. This means 8192/4 = 2048 transaction IDs can be stored in each\n\n    page.\n\n\n    Note that there may be gaps in each page. PostgreSQL will cache XIDs as\n\n    needed, so a single XID can occupy an entire page.\n\n\n    There are 32 (`NUM_SUBTRANS_BUFFERS`) pages, which means up to 65K\n\n    transaction IDs can be stored in memory. Nikolay demonstrated that in a\n\n    busy system, it took about 18 seconds to fill up all 65K entries. Then\n\n    performance dropped off a cliff, making the database replicas unusable.\n\n\n    To our surprise, our experiments also demonstrated that a single\n\n    `SAVEPOINT` during a long-transaction [could initiate this problem if\n\n    many writes also occurred\n    simultaneously](https://gitlab.com/gitlab-org/gitlab/-/issues/338865#note_655312474).\n    That\n\n    is, it wasn't enough just to reduce the frequency of `SAVEPOINT`; we had\n\n    to eliminate them completely.\n\n\n    #### Why does a single `SAVEPOINT` cause problems?\n\n\n    To answer this question, we need to understand what happens when a\n\n    `SAVEPOINT` occurs in one query while a long-running transaction is\n\n    running.\n\n\n    We mentioned earlier that PostgreSQL needs to decide whether a given row\n\n    is visible to support a feature called [multi-version concurrency\n    control](https://www.postgresql.org/docs/current/mvcc.html), or MVCC for\n\n    short. It does this by storing hidden columns, `xmin` and `xmax`, in\n\n    each tuple.\n\n\n    `xmin` holds the XID of when the tuple was created, and `xmax` holds the\n\n    XID when it was marked as dead (0 if the row is still present). In\n\n    addition, at the beginning of a transaction, PostgreSQL records metadata\n\n    in a database snapshot. Among other items, this snapshot records the\n\n    oldest XID and the newest XID in its own `xmin` and `xmax` values.\n\n\n    This metadata helps [PostgreSQL determine whether a tuple is\n    visible](https://www.interdb.jp/pg/pgsql05.html).\n\n    For example, a committed XID that started before `xmin` is definitely\n\n    visible, while anything after `xmax` is invisible.\n\n\n    ### What does this have to do with long transactions?\n\n\n    Long transactions are bad in general because they can tie up\n\n    connections, but they can cause a subtly different problem on a\n\n    replica. On the replica, a single `SAVEPOINT` during a long transaction\n\n    causes a snapshot to suboverflow. Remember that dragged down performance\n\n    in the case where we had more than 64 subtransactions.\n\n\n    Fundamentally, the problem happens because a replica behaves differently\n\n    from a primary when creating snapshots and checking for tuple\n\n    visibility. The diagram below illustrates an example with some of the\n\n    data structures used in PostgreSQL:\n\n\n    ![Diagram of subtransaction handling in\n    replicas](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/pg-replica-subtransaction-diagram.png)\n\n\n    On the top of this diagram, we can see the XIDs increase at the\n\n    beginning of a subtransaction: the `INSERT` after the `BEGIN` gets 1,\n\n    and the subsequent `INSERT` in `SAVEPOINT` gets 2. Another client comes\n\n    along and performs a `INSERT` and `SELECT` at XID 3.\n\n\n    On the primary, PostgreSQL stores the transactions in progress in a\n\n    shared memory segment. The process array (`procarray`) stores XID 1 with\n\n    the first connection, and the database also writes that information to\n\n    the `pg_xact` directory. XID 2 gets stored in the `pg_subtrans`\n\n    directory, mapped to its parent, XID 1.\n\n\n    If a read happens on the primary, the snapshot generated contains `xmin`\n\n    as 1, and `xmax` as 3. `txip` holds a list of transactions in progress,\n\n    and `subxip` holds a list of subtransactions in progress.\n\n\n    However, neither the `procarray` nor the snapshot are shared directly\n\n    with the replica. The replica receives all the data it needs from the\n\n    write-ahead log (WAL).\n\n\n    Playing the WAL back one entry at time, the replica populates a shared data\n\n    structure called `KnownAssignedIds`. It contains all the transactions in\n\n    progress on the primary. Since this structure can only hold a limited number\n    of\n\n    IDs, a busy database with a lot of active subtransactions could easily fill\n\n    this buffer. PostgreSQL made a design choice to kick out all subXIDs from\n    this\n\n    list and store them in the `pg_subtrans` directory.\n\n\n    When a snapshot is generated on the replica, notice how `txip` is\n\n    blank. A PostgreSQL replica treats **all** XIDs as though they are\n\n    subtransactions and throws them into the `subxip` bucket. That works\n\n    because if a XID has a parent XID, then it's a subtransaction. Otherwise,\n    it's a normal transaction. [The code comments\n\n    explain the\n    rationale](https://gitlab.com/postgres/postgres/blob/9f540f840665936132dd30bd8e58e9a67e648f22/src/backend/storage/ipc/procarray.c#L1665-L1681).\n\n\n    However, this means the snapshot is missing subXIDs, and that could be\n\n    bad for MVCC. To deal with that, the [replica also updates\n    `lastOverflowedXID`](https://gitlab.com/postgres/postgres/blob/9f540f840665936132dd30bd8e58e9a67e648f22/src/backend/storage/ipc/procarray.c#L3176-L3182):\n\n\n    ```c\n\n     * When we throw away subXIDs from KnownAssignedXids, we need to keep track of\n     * that, similarly to tracking overflow of a PGPROC's subxids array.  We do\n     * that by remembering the lastOverflowedXID, ie the last thrown-away subXID.\n     * As long as that is within the range of interesting XIDs, we have to assume\n     * that subXIDs are missing from snapshots.  (Note that subXID overflow occurs\n     * on primary when 65th subXID arrives, whereas on standby it occurs when 64th\n     * subXID arrives - that is not an error.)\n\n    ```\n\n\n    What is this \"range of interesting XIDs\"? We can see this in [the code\n    below](https://gitlab.com/postgres/postgres/blob/4bf0bce161097869be5a56706b31388ba15e0113/src/backend/storage/ipc/procarray.c#L1702-L1703):\n\n\n    ```c\n\n    if (TransactionIdPrecedesOrEquals(xmin, procArray->lastOverflowedXid))\n        suboverflowed = true;\n\n    ```\n\n\n    If `lastOverflowedXid` is smaller than our snapshot's `xmin`, it means\n\n    that all subtransactions have completed, so we don't need to check for\n\n    subtransactions. However, in our example:\n\n\n    1. `xmin` is 1 because of the transaction.\n\n    2. `lastOverflowXid` is 2 because of the `SAVEPOINT`.\n\n\n    This means `suboverflowed` is set to `true` here, which tells PostgreSQL\n\n    that whenever a XID needs to be checked, check to see if it has a parent\n\n    XID. Remember that this causes PostgreSQL to:\n\n\n    1. Look up the subXID for the parent XID in the SLRU cache.\n\n    1. If this doesn't exist in the cache, fetch the data from `pg_trans`.\n\n\n    In a busy system, the requested XIDs could span an ever-growing range of\n\n    values, which could easily exhaust the 64K entries in the SLRU\n\n    cache. This range will continue to grow as long as the transaction runs;\n\n    the rate of increase depends on how many updates are happening on the\n\n    prmary. As soon as the transaction terminates, the `suboverflowed` state\n\n    gets set to `false`.\n\n\n    In other words, we've replicated the same conditions as we saw with 64\n\n    subtransactions, only with a single `SAVEPOINT` and a long transaction.\n\n\n    ### What can we do about getting rid of Nessie?\n\n\n    There are three options:\n\n\n    1. Eliminate `SAVEPOINT` calls completely.\n\n    1. Eliminate all long-running transactions.\n\n    1. Apply [Andrey Borodin's patches to PostgreSQL and increase the\n    subtransaction\n    cache](https://www.postgresql.org/message-id/flat/494C5E7F-E410-48FA-A93E-F7723D859561%40yandex-team.ru#18c79477bf7fc44a3ac3d1ce55e4c169).\n\n\n    We chose the first option because most uses of subtransaction could be\n\n    removed fairly easily. There were a [number of\n    approaches](https://gitlab.com/groups/gitlab-org/-/epics/6540) we took:\n\n\n    1. Perform updates outside of a subtransaction. Examples:\n    [1](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68471),\n    [2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68690)\n\n    1. Rewrite a query to use a `INSERT` or an `UPDATE` with an `ON CONFLICT`\n    clause to deal with duplicate constraint violations. Examples:\n    [1](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68433),\n    [2](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/69240),\n    [3](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68509)\n\n    1. Live with a non-atomic `find_or_create_by`. We used this approach\n    sparingly. Example:\n    [1](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/68649)\n\n\n    In addition, we added [an alert whenever the application used a a single\n    `SAVEPOINT`](https://gitlab.com/gitlab-com/runbooks/-/merge_requests/3881):\n\n\n    ![subtransaction\n    alert](https://about.gitlab.com/images/blogimages/postgresql-subtransactions/subtransactions-alert-example.png)\n\n\n    This had the side benefit of flagging a [minor\n    bug](https://gitlab.com/gitlab-org/gitlab/-/merge_requests/70889).\n\n\n    #### Why not eliminate all long-running transactions?\n\n\n    In our database, it wasn't practical to eliminate all long-running\n\n    transactions because we think many of them happened via [database\n\n    autovacuuming](https://www.postgresql.org/docs/current/runtime-config-autovacuum.html),\n\n    but [we're not able to reproduce this\n    yet](https://gitlab.com/postgres-ai/postgresql-consulting/tests-and-benchmarks/-/issues/21#note_669698320).\n\n    We are working on partitioning the tables and sharding the database, but\n    this is a much more time-consuming problem\n\n    than removing all subtransactions.\n\n\n    #### What about the PostgreSQL patches?\n\n\n    Although we tested Andrey's PostgreSQL patches, we did not feel comfortable\n\n    deviating from the official PostgreSQL releases. Plus, maintaining a\n\n    custom patched release over upgrades would add a significant maintenance\n\n    burden for our infrastructure team. Our self-managed customers would\n\n    also not benefit unless they used a patched database.\n\n\n    Andrey's patches do two main things:\n\n\n    1. Allow administrators to change the SLRU size to any value.\n\n    1. Adds an [associative cache](https://www.youtube.com/watch?v=A0vR-ks3hsQ).\n\n    to make it performant to use a large cache value.\n\n\n    Remember that the SLRU cache does a linear search for the desired\n\n    page. That works fine when there are only 32 pages to search, but if you\n\n    increase the cache size to 100 MB the search becomes much more\n\n    expensive. The associative cache makes the lookup fast by indexing pages\n\n    with a bitmask and looking up the entry with offsets from the remaining\n\n    bits. This mitigates the problem because a transaction would need to be\n\n    several magnitudes longer to cause a problem.\n\n\n    Nikolay demonstrated that the `SAVEPOINT` problem disappeared as soon as\n\n    we increased the SLRU size to 100 MB with those patches. With a 100 MB\n\n    cache, PostgreSQL can cache 26.2 million IDs (104857600/4), far more\n\n    than the measely 65K.\n\n\n    These [patches are currently awaiting\n    review](https://postgres.ai/blog/20210831-postgresql-subtransactions-considered-harmful#ideas-for-postgresql-development),\n\n    but in our opinion they should be given high priority for PostgreSQL 15.\n\n\n    ### Conclusion\n\n\n    Since removing all `SAVEPOINT` queries, we have not seen Nessie rear her\n\n    head again. If you are running PostgreSQL with read replicas, we\n\n    strongly recommend that you also remove *all* subtransactions until\n\n    further notice.\n\n\n    PostgreSQL is a fantastic database, and its well-commented code makes it\n\n    possible to understand its limitations under different configurations.\n\n\n    We would like to thank the GitLab community for bearing with us while we\n\n    iron out this production issue.\n\n\n    We are also grateful for the support from [Nikolay\n\n    Samokhvalov](https://gitlab.com/NikolayS) and [Catalin\n\n    Irimie](https://gitlab.com/cat), who contributed to understanding where our\n\n    Loch Ness Monster was hiding.\n\n\n    Cover image by [Khadi\n    Ganiev](https://www.istockphoto.com/portfolio/Ganiev?mediatype=photography)\n    on [iStock](https://istock.com), licensed under [standard\n    license](https://www.istockphoto.com/legal/license-agreement)\n  category: engineering\n  tags:\n    - performance\n    - contributors\n    - frontend\nconfig:\n  slug: why-we-spent-the-last-month-eliminating-postgresql-subtransactions\n  featured: false\n  template: BlogPost\n",{"title":5,"description":19,"ogTitle":5,"ogDescription":19,"noIndex":16,"ogImage":21,"ogUrl":34,"ogSiteName":35,"ogType":36,"canonicalUrls":34},"https://about.gitlab.com/blog/why-we-spent-the-last-month-eliminating-postgresql-subtransactions","https://about.gitlab.com","article","en-us/blog/why-we-spent-the-last-month-eliminating-postgresql-subtransactions",[24,25,26],[24,25,26],"YlChWV-cQQK2e0oNPuzfX50xwEH52Cjfm7rGOk2L5_Q",{"data":42},{"logo":43,"freeTrial":48,"sales":53,"login":58,"items":63,"search":372,"minimal":403,"duo":422,"switchNav":431,"pricingDeployment":442},{"config":44},{"href":45,"dataGaName":46,"dataGaLocation":47},"/","gitlab logo","header",{"text":49,"config":50},"Get free trial",{"href":51,"dataGaName":52,"dataGaLocation":47},"https://gitlab.com/-/trial_registrations/new?glm_source=about.gitlab.com&glm_content=default-saas-trial/","free trial",{"text":54,"config":55},"Talk to sales",{"href":56,"dataGaName":57,"dataGaLocation":47},"/sales/","sales",{"text":59,"config":60},"Sign in",{"href":61,"dataGaName":62,"dataGaLocation":47},"https://gitlab.com/users/sign_in/","sign in",[64,91,186,191,293,353],{"text":65,"config":66,"cards":68},"Platform",{"dataNavLevelOne":67},"platform",[69,75,83],{"title":65,"description":70,"link":71},"The intelligent orchestration platform for DevSecOps",{"text":72,"config":73},"Explore our Platform",{"href":74,"dataGaName":67,"dataGaLocation":47},"/platform/",{"title":76,"description":77,"link":78},"GitLab Duo Agent Platform","Agentic AI for the entire software lifecycle",{"text":79,"config":80},"Meet GitLab Duo",{"href":81,"dataGaName":82,"dataGaLocation":47},"/gitlab-duo-agent-platform/","gitlab duo agent platform",{"title":84,"description":85,"link":86},"Why GitLab","See the top reasons enterprises choose GitLab",{"text":87,"config":88},"Learn more",{"href":89,"dataGaName":90,"dataGaLocation":47},"/why-gitlab/","why gitlab",{"text":92,"left":30,"config":93,"link":95,"lists":99,"footer":168},"Product",{"dataNavLevelOne":94},"solutions",{"text":96,"config":97},"View all Solutions",{"href":98,"dataGaName":94,"dataGaLocation":47},"/solutions/",[100,124,147],{"title":101,"description":102,"link":103,"items":108},"Automation","CI/CD and automation to accelerate deployment",{"config":104},{"icon":105,"href":106,"dataGaName":107,"dataGaLocation":47},"AutomatedCodeAlt","/solutions/delivery-automation/","automated software delivery",[109,113,116,120],{"text":110,"config":111},"CI/CD",{"href":112,"dataGaLocation":47,"dataGaName":110},"/solutions/continuous-integration/",{"text":76,"config":114},{"href":81,"dataGaLocation":47,"dataGaName":115},"gitlab duo agent platform - product menu",{"text":117,"config":118},"Source Code Management",{"href":119,"dataGaLocation":47,"dataGaName":117},"/solutions/source-code-management/",{"text":121,"config":122},"Automated Software Delivery",{"href":106,"dataGaLocation":47,"dataGaName":123},"Automated software delivery",{"title":125,"description":126,"link":127,"items":132},"Security","Deliver code faster without compromising security",{"config":128},{"href":129,"dataGaName":130,"dataGaLocation":47,"icon":131},"/solutions/application-security-testing/","security and compliance","ShieldCheckLight",[133,137,142],{"text":134,"config":135},"Application Security Testing",{"href":129,"dataGaName":136,"dataGaLocation":47},"Application security testing",{"text":138,"config":139},"Software Supply Chain Security",{"href":140,"dataGaLocation":47,"dataGaName":141},"/solutions/supply-chain/","Software supply chain security",{"text":143,"config":144},"Software Compliance",{"href":145,"dataGaName":146,"dataGaLocation":47},"/solutions/software-compliance/","software compliance",{"title":148,"link":149,"items":154},"Measurement",{"config":150},{"icon":151,"href":152,"dataGaName":153,"dataGaLocation":47},"DigitalTransformation","/solutions/visibility-measurement/","visibility and measurement",[155,159,163],{"text":156,"config":157},"Visibility & Measurement",{"href":152,"dataGaLocation":47,"dataGaName":158},"Visibility and Measurement",{"text":160,"config":161},"Value Stream Management",{"href":162,"dataGaLocation":47,"dataGaName":160},"/solutions/value-stream-management/",{"text":164,"config":165},"Analytics & Insights",{"href":166,"dataGaLocation":47,"dataGaName":167},"/solutions/analytics-and-insights/","Analytics and insights",{"title":169,"items":170},"GitLab for",[171,176,181],{"text":172,"config":173},"Enterprise",{"href":174,"dataGaLocation":47,"dataGaName":175},"/enterprise/","enterprise",{"text":177,"config":178},"Small Business",{"href":179,"dataGaLocation":47,"dataGaName":180},"/small-business/","small business",{"text":182,"config":183},"Public Sector",{"href":184,"dataGaLocation":47,"dataGaName":185},"/solutions/public-sector/","public sector",{"text":187,"config":188},"Pricing",{"href":189,"dataGaName":190,"dataGaLocation":47,"dataNavLevelOne":190},"/pricing/","pricing",{"text":192,"config":193,"link":195,"lists":199,"feature":284},"Resources",{"dataNavLevelOne":194},"resources",{"text":196,"config":197},"View all resources",{"href":198,"dataGaName":194,"dataGaLocation":47},"/resources/",[200,233,256],{"title":201,"items":202},"Getting started",[203,208,213,218,223,228],{"text":204,"config":205},"Install",{"href":206,"dataGaName":207,"dataGaLocation":47},"/install/","install",{"text":209,"config":210},"Quick start guides",{"href":211,"dataGaName":212,"dataGaLocation":47},"/get-started/","quick setup checklists",{"text":214,"config":215},"Learn",{"href":216,"dataGaLocation":47,"dataGaName":217},"https://university.gitlab.com/","learn",{"text":219,"config":220},"Product documentation",{"href":221,"dataGaName":222,"dataGaLocation":47},"https://docs.gitlab.com/","product documentation",{"text":224,"config":225},"Best practice videos",{"href":226,"dataGaName":227,"dataGaLocation":47},"/getting-started-videos/","best practice videos",{"text":229,"config":230},"Integrations",{"href":231,"dataGaName":232,"dataGaLocation":47},"/integrations/","integrations",{"title":234,"items":235},"Discover",[236,241,246,251],{"text":237,"config":238},"Customer success stories",{"href":239,"dataGaName":240,"dataGaLocation":47},"/customers/","customer success stories",{"text":242,"config":243},"Blog",{"href":244,"dataGaName":245,"dataGaLocation":47},"/blog/","blog",{"text":247,"config":248},"The Source",{"href":249,"dataGaName":250,"dataGaLocation":47},"/the-source/","the source",{"text":252,"config":253},"Remote",{"href":254,"dataGaName":255,"dataGaLocation":47},"https://handbook.gitlab.com/handbook/company/culture/all-remote/","remote",{"title":257,"items":258},"Connect",[259,264,269,274,279],{"text":260,"config":261},"GitLab Services",{"href":262,"dataGaName":263,"dataGaLocation":47},"/services/","services",{"text":265,"config":266},"Community",{"href":267,"dataGaName":268,"dataGaLocation":47},"/community/","community",{"text":270,"config":271},"Forum",{"href":272,"dataGaName":273,"dataGaLocation":47},"https://forum.gitlab.com/","forum",{"text":275,"config":276},"Events",{"href":277,"dataGaName":278,"dataGaLocation":47},"/events/","events",{"text":280,"config":281},"Partners",{"href":282,"dataGaName":283,"dataGaLocation":47},"/partners/","partners",{"textColor":285,"title":286,"text":287,"link":288},"#000","What’s new in GitLab","Stay updated with our latest features and improvements.",{"text":289,"config":290},"Read the latest",{"href":291,"dataGaName":292,"dataGaLocation":47},"/releases/whats-new/","whats new",{"text":294,"config":295,"lists":297},"Company",{"dataNavLevelOne":296},"company",[298],{"items":299},[300,305,311,313,318,323,328,333,338,343,348],{"text":301,"config":302},"About",{"href":303,"dataGaName":304,"dataGaLocation":47},"/company/","about",{"text":306,"config":307,"footerGa":310},"Jobs",{"href":308,"dataGaName":309,"dataGaLocation":47},"/jobs/","jobs",{"dataGaName":309},{"text":275,"config":312},{"href":277,"dataGaName":278,"dataGaLocation":47},{"text":314,"config":315},"Leadership",{"href":316,"dataGaName":317,"dataGaLocation":47},"/company/team/e-group/","leadership",{"text":319,"config":320},"Team",{"href":321,"dataGaName":322,"dataGaLocation":47},"/company/team/","team",{"text":324,"config":325},"Handbook",{"href":326,"dataGaName":327,"dataGaLocation":47},"https://handbook.gitlab.com/","handbook",{"text":329,"config":330},"Investor relations",{"href":331,"dataGaName":332,"dataGaLocation":47},"https://ir.gitlab.com/","investor relations",{"text":334,"config":335},"Trust Center",{"href":336,"dataGaName":337,"dataGaLocation":47},"/security/","trust center",{"text":339,"config":340},"AI Transparency Center",{"href":341,"dataGaName":342,"dataGaLocation":47},"/ai-transparency-center/","ai transparency center",{"text":344,"config":345},"Newsletter",{"href":346,"dataGaName":347,"dataGaLocation":47},"/company/contact/#contact-forms","newsletter",{"text":349,"config":350},"Press",{"href":351,"dataGaName":352,"dataGaLocation":47},"/press/","press",{"text":354,"config":355,"lists":356},"Contact us",{"dataNavLevelOne":296},[357],{"items":358},[359,362,367],{"text":54,"config":360},{"href":56,"dataGaName":361,"dataGaLocation":47},"talk to sales",{"text":363,"config":364},"Support portal",{"href":365,"dataGaName":366,"dataGaLocation":47},"https://support.gitlab.com","support portal",{"text":368,"config":369},"Customer portal",{"href":370,"dataGaName":371,"dataGaLocation":47},"https://customers.gitlab.com/customers/sign_in/","customer portal",{"close":373,"login":374,"suggestions":381},"Close",{"text":375,"link":376},"To search repositories and projects, login to",{"text":377,"config":378},"gitlab.com",{"href":61,"dataGaName":379,"dataGaLocation":380},"search login","search",{"text":382,"default":383},"Suggestions",[384,386,390,392,396,400],{"text":76,"config":385},{"href":81,"dataGaName":76,"dataGaLocation":380},{"text":387,"config":388},"Code Suggestions (AI)",{"href":389,"dataGaName":387,"dataGaLocation":380},"/solutions/code-suggestions/",{"text":110,"config":391},{"href":112,"dataGaName":110,"dataGaLocation":380},{"text":393,"config":394},"GitLab on AWS",{"href":395,"dataGaName":393,"dataGaLocation":380},"/partners/technology-partners/aws/",{"text":397,"config":398},"GitLab on Google Cloud",{"href":399,"dataGaName":397,"dataGaLocation":380},"/partners/technology-partners/google-cloud-platform/",{"text":401,"config":402},"Why GitLab?",{"href":89,"dataGaName":401,"dataGaLocation":380},{"freeTrial":404,"mobileIcon":409,"desktopIcon":414,"secondaryButton":417},{"text":405,"config":406},"Start free trial",{"href":407,"dataGaName":52,"dataGaLocation":408},"https://gitlab.com/-/trials/new/","nav",{"altText":410,"config":411},"Gitlab Icon",{"src":412,"dataGaName":413,"dataGaLocation":408},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1758203874/jypbw1jx72aexsoohd7x.svg","gitlab icon",{"altText":410,"config":415},{"src":416,"dataGaName":413,"dataGaLocation":408},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1758203875/gs4c8p8opsgvflgkswz9.svg",{"text":418,"config":419},"Get Started",{"href":420,"dataGaName":421,"dataGaLocation":408},"https://gitlab.com/-/trial_registrations/new?glm_source=about.gitlab.com/get-started/","get started",{"freeTrial":423,"mobileIcon":427,"desktopIcon":429},{"text":424,"config":425},"Learn more about GitLab Duo",{"href":81,"dataGaName":426,"dataGaLocation":408},"gitlab duo",{"altText":410,"config":428},{"src":412,"dataGaName":413,"dataGaLocation":408},{"altText":410,"config":430},{"src":416,"dataGaName":413,"dataGaLocation":408},{"button":432,"mobileIcon":437,"desktopIcon":439},{"text":433,"config":434},"/switch",{"href":435,"dataGaName":436,"dataGaLocation":408},"#contact","switch",{"altText":410,"config":438},{"src":412,"dataGaName":413,"dataGaLocation":408},{"altText":410,"config":440},{"src":441,"dataGaName":413,"dataGaLocation":408},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1773335277/ohhpiuoxoldryzrnhfrh.png",{"freeTrial":443,"mobileIcon":448,"desktopIcon":450},{"text":444,"config":445},"Back to pricing",{"href":189,"dataGaName":446,"dataGaLocation":408,"icon":447},"back to pricing","GoBack",{"altText":410,"config":449},{"src":412,"dataGaName":413,"dataGaLocation":408},{"altText":410,"config":451},{"src":416,"dataGaName":413,"dataGaLocation":408},{"title":453,"button":454,"config":459},"See how agentic AI transforms software delivery",{"text":455,"config":456},"Watch GitLab Transcend now",{"href":457,"dataGaName":458,"dataGaLocation":47},"/events/transcend/virtual/","transcend event",{"layout":460,"icon":461,"disabled":30},"release","AiStar",{"data":463},{"text":464,"source":465,"edit":471,"contribute":476,"config":481,"items":486,"minimal":693},"Git is a trademark of Software Freedom Conservancy and our use of 'GitLab' is under license",{"text":466,"config":467},"View page source",{"href":468,"dataGaName":469,"dataGaLocation":470},"https://gitlab.com/gitlab-com/marketing/digital-experience/about-gitlab-com/","page source","footer",{"text":472,"config":473},"Edit this page",{"href":474,"dataGaName":475,"dataGaLocation":470},"https://gitlab.com/gitlab-com/marketing/digital-experience/about-gitlab-com/-/blob/main/content/","web ide",{"text":477,"config":478},"Please contribute",{"href":479,"dataGaName":480,"dataGaLocation":470},"https://gitlab.com/gitlab-com/marketing/digital-experience/about-gitlab-com/-/blob/main/CONTRIBUTING.md/","please contribute",{"twitter":482,"facebook":483,"youtube":484,"linkedin":485},"https://twitter.com/gitlab","https://www.facebook.com/gitlab","https://www.youtube.com/channel/UCnMGQ8QHMAnVIsI3xJrihhg","https://www.linkedin.com/company/gitlab-com",[487,534,588,632,659],{"title":187,"links":488,"subMenu":503},[489,493,498],{"text":490,"config":491},"View plans",{"href":189,"dataGaName":492,"dataGaLocation":470},"view plans",{"text":494,"config":495},"Why Premium?",{"href":496,"dataGaName":497,"dataGaLocation":470},"/pricing/premium/","why premium",{"text":499,"config":500},"Why Ultimate?",{"href":501,"dataGaName":502,"dataGaLocation":470},"/pricing/ultimate/","why ultimate",[504],{"title":505,"links":506},"Contact Us",[507,510,512,514,519,524,529],{"text":508,"config":509},"Contact sales",{"href":56,"dataGaName":57,"dataGaLocation":470},{"text":363,"config":511},{"href":365,"dataGaName":366,"dataGaLocation":470},{"text":368,"config":513},{"href":370,"dataGaName":371,"dataGaLocation":470},{"text":515,"config":516},"Status",{"href":517,"dataGaName":518,"dataGaLocation":470},"https://status.gitlab.com/","status",{"text":520,"config":521},"Terms of use",{"href":522,"dataGaName":523,"dataGaLocation":470},"/terms/","terms of use",{"text":525,"config":526},"Privacy statement",{"href":527,"dataGaName":528,"dataGaLocation":470},"/privacy/","privacy statement",{"text":530,"config":531},"Cookie preferences",{"dataGaName":532,"dataGaLocation":470,"id":533,"isOneTrustButton":30},"cookie preferences","ot-sdk-btn",{"title":92,"links":535,"subMenu":544},[536,540],{"text":537,"config":538},"DevSecOps platform",{"href":74,"dataGaName":539,"dataGaLocation":470},"devsecops platform",{"text":541,"config":542},"AI-Assisted Development",{"href":81,"dataGaName":543,"dataGaLocation":470},"ai-assisted development",[545],{"title":546,"links":547},"Topics",[548,553,558,563,568,573,578,583],{"text":549,"config":550},"CICD",{"href":551,"dataGaName":552,"dataGaLocation":470},"/topics/ci-cd/","cicd",{"text":554,"config":555},"GitOps",{"href":556,"dataGaName":557,"dataGaLocation":470},"/topics/gitops/","gitops",{"text":559,"config":560},"DevOps",{"href":561,"dataGaName":562,"dataGaLocation":470},"/topics/devops/","devops",{"text":564,"config":565},"Version Control",{"href":566,"dataGaName":567,"dataGaLocation":470},"/topics/version-control/","version control",{"text":569,"config":570},"DevSecOps",{"href":571,"dataGaName":572,"dataGaLocation":470},"/topics/devsecops/","devsecops",{"text":574,"config":575},"Cloud Native",{"href":576,"dataGaName":577,"dataGaLocation":470},"/topics/cloud-native/","cloud native",{"text":579,"config":580},"AI for Coding",{"href":581,"dataGaName":582,"dataGaLocation":470},"/topics/devops/ai-for-coding/","ai for coding",{"text":584,"config":585},"Agentic AI",{"href":586,"dataGaName":587,"dataGaLocation":470},"/topics/agentic-ai/","agentic ai",{"title":589,"links":590},"Solutions",[591,593,595,600,604,607,611,614,616,619,622,627],{"text":134,"config":592},{"href":129,"dataGaName":134,"dataGaLocation":470},{"text":123,"config":594},{"href":106,"dataGaName":107,"dataGaLocation":470},{"text":596,"config":597},"Agile development",{"href":598,"dataGaName":599,"dataGaLocation":470},"/solutions/agile-delivery/","agile delivery",{"text":601,"config":602},"SCM",{"href":119,"dataGaName":603,"dataGaLocation":470},"source code management",{"text":549,"config":605},{"href":112,"dataGaName":606,"dataGaLocation":470},"continuous integration & delivery",{"text":608,"config":609},"Value stream management",{"href":162,"dataGaName":610,"dataGaLocation":470},"value stream management",{"text":554,"config":612},{"href":613,"dataGaName":557,"dataGaLocation":470},"/solutions/gitops/",{"text":172,"config":615},{"href":174,"dataGaName":175,"dataGaLocation":470},{"text":617,"config":618},"Small business",{"href":179,"dataGaName":180,"dataGaLocation":470},{"text":620,"config":621},"Public sector",{"href":184,"dataGaName":185,"dataGaLocation":470},{"text":623,"config":624},"Education",{"href":625,"dataGaName":626,"dataGaLocation":470},"/solutions/education/","education",{"text":628,"config":629},"Financial services",{"href":630,"dataGaName":631,"dataGaLocation":470},"/solutions/finance/","financial services",{"title":192,"links":633},[634,636,638,640,643,645,647,649,651,653,655,657],{"text":204,"config":635},{"href":206,"dataGaName":207,"dataGaLocation":470},{"text":209,"config":637},{"href":211,"dataGaName":212,"dataGaLocation":470},{"text":214,"config":639},{"href":216,"dataGaName":217,"dataGaLocation":470},{"text":219,"config":641},{"href":221,"dataGaName":642,"dataGaLocation":470},"docs",{"text":242,"config":644},{"href":244,"dataGaName":245,"dataGaLocation":470},{"text":237,"config":646},{"href":239,"dataGaName":240,"dataGaLocation":470},{"text":252,"config":648},{"href":254,"dataGaName":255,"dataGaLocation":470},{"text":260,"config":650},{"href":262,"dataGaName":263,"dataGaLocation":470},{"text":265,"config":652},{"href":267,"dataGaName":268,"dataGaLocation":470},{"text":270,"config":654},{"href":272,"dataGaName":273,"dataGaLocation":470},{"text":275,"config":656},{"href":277,"dataGaName":278,"dataGaLocation":470},{"text":280,"config":658},{"href":282,"dataGaName":283,"dataGaLocation":470},{"title":294,"links":660},[661,663,665,667,669,671,673,677,682,684,686,688],{"text":301,"config":662},{"href":303,"dataGaName":296,"dataGaLocation":470},{"text":306,"config":664},{"href":308,"dataGaName":309,"dataGaLocation":470},{"text":314,"config":666},{"href":316,"dataGaName":317,"dataGaLocation":470},{"text":319,"config":668},{"href":321,"dataGaName":322,"dataGaLocation":470},{"text":324,"config":670},{"href":326,"dataGaName":327,"dataGaLocation":470},{"text":329,"config":672},{"href":331,"dataGaName":332,"dataGaLocation":470},{"text":674,"config":675},"Sustainability",{"href":676,"dataGaName":674,"dataGaLocation":470},"/sustainability/",{"text":678,"config":679},"Diversity, inclusion and belonging (DIB)",{"href":680,"dataGaName":681,"dataGaLocation":470},"/diversity-inclusion-belonging/","Diversity, inclusion and belonging",{"text":334,"config":683},{"href":336,"dataGaName":337,"dataGaLocation":470},{"text":344,"config":685},{"href":346,"dataGaName":347,"dataGaLocation":470},{"text":349,"config":687},{"href":351,"dataGaName":352,"dataGaLocation":470},{"text":689,"config":690},"Modern Slavery Transparency Statement",{"href":691,"dataGaName":692,"dataGaLocation":470},"https://handbook.gitlab.com/handbook/legal/modern-slavery-act-transparency-statement/","modern slavery transparency statement",{"items":694},[695,698,701],{"text":696,"config":697},"Terms",{"href":522,"dataGaName":523,"dataGaLocation":470},{"text":699,"config":700},"Cookies",{"dataGaName":532,"dataGaLocation":470,"id":533,"isOneTrustButton":30},{"text":702,"config":703},"Privacy",{"href":527,"dataGaName":528,"dataGaLocation":470},[705,718],{"id":706,"title":10,"body":28,"config":707,"content":709,"description":28,"extension":27,"meta":713,"navigation":30,"path":714,"seo":715,"stem":716,"__hash__":717},"blogAuthors/en-us/blog/authors/grzegorz-bizon.yml",{"template":708},"BlogAuthor",{"name":10,"config":710},{"headshot":711,"ctfId":712},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1749659488/Blog/Author%20Headshots/gitlab-logo-extra-whitespace.png","Grzegorz-Bizon",{},"/en-us/blog/authors/grzegorz-bizon",{},"en-us/blog/authors/grzegorz-bizon","Z1aKSWxubaVpieVMM-H8afTapWLnKt0xl0AyT32DmJE",{"id":719,"title":11,"body":28,"config":720,"content":721,"description":28,"extension":27,"meta":725,"navigation":30,"path":726,"seo":727,"stem":728,"__hash__":729},"blogAuthors/en-us/blog/authors/stan-hu.yml",{"template":708},{"name":11,"config":722},{"headshot":723,"ctfId":724},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1749659504/Blog/Author%20Headshots/stanhu-headshot.jpg","stanhu",{},"/en-us/blog/authors/stan-hu",{},"en-us/blog/authors/stan-hu","KmQVCb_7YcWghHApaS2EI3J2bQ0dRustgOz4wYyOnVk",[731,745,759],{"content":732,"config":743},{"title":733,"description":734,"authors":735,"heroImage":737,"date":738,"body":739,"category":13,"tags":740},"How to build CI/CD observability at scale","This practical guide to GitLab pipeline analytics helps self-managed users gain operational insights using Prometheus and Grafana.",[736],"Paul Meresanu","https://res.cloudinary.com/about-gitlab-com/image/upload/v1774465167/n5hlvrsrheadeccyr1oz.png","2026-04-28","CI/CD optimization starts with visibility. Building a successful DevOps platform at enterprise scale **should include** understanding pipeline performance, job execution patterns, and quantifiable operational insights — especially for organizations running GitLab self-managed instances.\n\nTo help GitLab customers maximize their platform investments, we developed the GitLab CI/CD Observability solution as part of our Platform Excellence program, which transforms raw pipeline metrics into actionable operational insights.\n\nA leading financial services organization partnered with GitLab's customer success architect to gain visibility into their GitLab self-managed deployment. Together, we implemented a containerized observability solution combining the open-source gitlab-ci-pipelines-exporter with enterprise-grade Prometheus and Grafana infrastructure.\n\nIn this article, you'll learn the challenges they faced managing pipelines at scale and how GitLab CI/CD Observability addressed them with a practical, end-to-end implementation.\n\n## The challenge: Measuring CI/CD performance\nBefore implementing any observability solution, define your measurement landscape:\n*   **What metrics matter?** Pipeline duration, job success rates, queue times, runner utilization\n*   **Who needs visibility?** Developers, DevOps engineers, platform teams, leadership\n*   **What decisions will this drive?** Infrastructure investment, bottleneck remediation, capacity planning\n\n## Solution architecture: A full set of dashboards for observability\nOnce deployed, the observability stack provides a set of Grafana dashboards that give real-time and historical visibility into your CI/CD platform. A typical deployment includes:\n*   **Pipeline Overview Dashboard:** A top-level view showing total pipeline runs, success/failure rates over time (as stacked bar or time-series charts), and average pipeline duration trends. Panels use color-coded status indicators (green for success, red for failure, amber for cancelled) so platform teams can spot degradation at a glance.\n*   **Job Performance Dashboard:** Drill-down panels showing individual job duration distributions (histogram), the top 10 slowest jobs by average duration, and job failure heatmaps by project and stage. This is where teams identify specific bottleneck jobs worth optimizing.\n*   **Runner & Infrastructure Dashboard:** Combines Node Exporter host metrics (CPU, memory, disk) with pipeline queue-time data to correlate infrastructure saturation with pipeline wait times. Useful for capacity planning decisions such as scaling runner pools or upgrading instance sizes.\n*   **Deployment Frequency Dashboard:** Tracks deployment count and deployment duration over time per environment, aligned with DORA metrics. Helps engineering leadership assess delivery throughput and environment drift (commits behind main).\n\nEach dashboard is provisioned automatically via Grafana's file-based provisioning, so it deploys consistently across environments. The dashboards can be further customized with Grafana variables to filter by project, ref/branch, or time range.\n\n![Solution architecture](https://res.cloudinary.com/about-gitlab-com/image/upload/v1777382608/Blog/Imported/blog-building-ci-cd-observability-stack-for-gitlab-self-managed/image1.png)\n\nThe solution requires two exporters:\n*   **Pipeline Exporter:** Collects CI/CD metrics via GitLab API (pipeline duration, job status, deployments)\n*   **Node Exporter:** Collects host-level metrics (CPU, memory, disk) for infrastructure correlation\n\n**Prerequisites:**\n*   GitLab Self-Managed Version 18.1+\n*   **Container orchestration platform:** A Kubernetes cluster (recommended for enterprise deployments) or a container runtime such as Docker/Podman for smaller scale or proof-of-concept environments. The primary deployment guide below targets Kubernetes; a Docker Compose alternative is provided in the appendix for local testing and evaluation\n*   GitLab Personal Access Token (**read_api** scope)\n\n## Kubernetes deployment (recommended)\nFor enterprise environments, deploy each component as a separate Deployment within a dedicated namespace. This approach integrates with existing cluster infrastructure, secrets management, and network policies.\n\n### 1. Create namespace and secret\n```bash\nkubectl create namespace gitlab-observability\n\n# Create the GitLab token secret (see Secrets Management section below\n# for enterprise-grade approaches using external secret operators)\nkubectl create secret generic gitlab-token \\\n  --from-literal=token=glpat-xxxxxxxxxxxx \\\n  -n gitlab-observability\n```\n\n\n### 2. Deploy the Pipeline Exporter\n```yaml\n# exporter-deployment.yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: gitlab-ci-pipelines-exporter\n  namespace: gitlab-observability\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: gitlab-ci-pipelines-exporter\n  template:\n    metadata:\n      labels:\n        app: gitlab-ci-pipelines-exporter\n    spec:\n      containers:\n        - name: exporter\n          image: mvisonneau/gitlab-ci-pipelines-exporter:latest\n          ports:\n            - containerPort: 8080\n          env:\n            - name: GCPE_GITLAB_TOKEN\n              valueFrom:\n                secretKeyRef:\n                  name: gitlab-token\n                  key: token\n            - name: GCPE_CONFIG\n              value: /etc/gcpe/config.yml\n          volumeMounts:\n            - name: config\n              mountPath: /etc/gcpe\n      volumes:\n        - name: config\n          configMap:\n            name: gcpe-config\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: gitlab-ci-pipelines-exporter\n  namespace: gitlab-observability\nspec:\n  selector:\n    app: gitlab-ci-pipelines-exporter\n  ports:\n    - port: 8080\n      targetPort: 8080\n```\n\n### 3. Deploy Node Exporter (DaemonSet)\n```yaml\n# node-exporter-daemonset.yaml\napiVersion: apps/v1\nkind: DaemonSet\nmetadata:\n  name: node-exporter\n  namespace: gitlab-observability\nspec:\n  selector:\n    matchLabels:\n      app: node-exporter\n  template:\n    metadata:\n      labels:\n        app: node-exporter\n    spec:\n      containers:\n        - name: node-exporter\n          image: prom/node-exporter:latest\n          ports:\n            - containerPort: 9100\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: node-exporter\n  namespace: gitlab-observability\nspec:\n  selector:\n    app: node-exporter\n  ports:\n    - port: 9100\n      targetPort: 9100\n```\n\n### 4. Deploy Prometheus\n```yaml\n# prometheus-deployment.yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: prometheus\n  namespace: gitlab-observability\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: prometheus\n  template:\n    metadata:\n      labels:\n        app: prometheus\n    spec:\n      containers:\n        - name: prometheus\n          image: prom/prometheus:latest\n          ports:\n            - containerPort: 9090\n          volumeMounts:\n            - name: config\n              mountPath: /etc/prometheus\n      volumes:\n        - name: config\n          configMap:\n            name: prometheus-config\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: prometheus\n  namespace: gitlab-observability\nspec:\n  selector:\n    app: prometheus\n  ports:\n    - port: 9090\n      targetPort: 9090\n```\n\n### 5. Deploy Grafana\nThe Grafana deployment below starts with authentication disabled (`GF_AUTH_ANONYMOUS_ENABLED: true`) for initial setup convenience.\n\n**This setting allows anyone with network access to view all dashboards without logging in.** For production deployments, remove this variable or set it to false and configure a proper authentication provider (LDAP, SAML/SSO, or OAuth) to restrict access to authorized users.\n```yaml\n# grafana-deployment.yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: grafana\n  namespace: gitlab-observability\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: grafana\n  template:\n    metadata:\n      labels:\n        app: grafana\n    spec:\n      containers:\n        - name: grafana\n          image: grafana/grafana:10.0.0\n          ports:\n            - containerPort: 3000\n          env:\n            # REMOVE or set to 'false' for production.\n            # When 'true', any user with network access can\n            # view dashboards without authentication.\n            - name: GF_AUTH_ANONYMOUS_ENABLED\n              value: 'true'\n          volumeMounts:\n            - name: dashboards-provider\n              mountPath: /etc/grafana/provisioning/dashboards\n            - name: datasources\n              mountPath: /etc/grafana/provisioning/datasources\n            - name: dashboards\n              mountPath: /var/lib/grafana/dashboards\n      volumes:\n        - name: dashboards-provider\n          configMap:\n            name: grafana-dashboards-provider\n        - name: datasources\n          configMap:\n            name: grafana-datasources\n        - name: dashboards\n          configMap:\n            name: grafana-dashboards\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: grafana\n  namespace: gitlab-observability\nspec:\n  selector:\n    app: grafana\n  ports:\n    - port: 3000\n      targetPort: 3000\n```\n\n### 6. Set network policy\nRestrict inter-pod traffic to only the required communication paths:\n```yaml\n# network-policy.yaml\napiVersion: networking.k8s.io/v1\nkind: NetworkPolicy\nmetadata:\n  name: observability-policy\n  namespace: gitlab-observability\nspec:\n  podSelector: {}\n  policyTypes:\n    - Ingress\n  ingress:\n    # Prometheus scrapes exporter and node-exporter\n    - from:\n        - podSelector:\n            matchLabels:\n              app: prometheus\n      ports:\n        - port: 8080\n        - port: 9100\n    # Grafana queries Prometheus\n    - from:\n        - podSelector:\n            matchLabels:\n              app: grafana\n      ports:\n        - port: 9090\n```\n\n### 7. Validate\n```bash\nkubectl get pods -n gitlab-observability\nkubectl port-forward svc/grafana 3000:3000 -n gitlab-observability\ncurl http://localhost:3000/api/health\n```\n\n## Configuration reference\n### Exporter configuration\n```yaml\n# gitlab-ci-pipelines-exporter.yml (ConfigMap: gcpe-config)\nlog:\n  level: info\ngitlab:\n  url: https://gitlab.your-domain.com\n  maximum_requests_per_second: 10\nproject_defaults:\n  pull:\n    pipeline:\n      jobs:\n        enabled: true\nwildcards:\n  - owner:\n      name: your-group-name\n      kind: group\n    archived: false\n```\n\n### Prometheus configuration\n```yaml\n# prometheus.yml (ConfigMap: prometheus-config)\nglobal:\n  scrape_interval: 15s\nscrape_configs:\n  - job_name: 'gitlab-ci-pipelines-exporter'\n    static_configs:\n      - targets: ['gitlab-ci-pipelines-exporter:8080']\n  - job_name: 'node-exporter'\n    static_configs:\n      - targets: ['node-exporter:9100']\n```\n\n### Grafana data sources\n```yaml\n# datasources.yml (ConfigMap: grafana-datasources)\napiVersion: 1\ndatasources:\n  - name: Prometheus\n    type: prometheus\n    access: proxy\n    url: http://prometheus:9090\n    isDefault: true\n# dashboards.yml (ConfigMap: grafana-dashboards-provider)\napiVersion: 1\nproviders:\n  - name: 'default'\n    folder: 'GitLab CI/CD'\n    type: file\n    options:\n      path: /var/lib/grafana/dashboards\n```\n\n## Key metrics\n### Pipeline Exporter metrics\n| Metric | Description |\n| :---- | :---- |\n| `gitlab_ci_pipeline_duration_seconds` | Pipeline execution time |\n| `gitlab_ci_pipeline_status` | Pipeline success/failure by project |\n| `gitlab_ci_pipeline_job_duration_seconds` | Individual job execution time |\n| `gitlab_ci_pipeline_job_status` | Job success/failure status |\n| `gitlab_ci_pipeline_job_artifact_size_bytes` | Artifact storage consumption |\n| `gitlab_ci_pipeline_coverage` | Code coverage percentage |\n| `gitlab_ci_environment_deployment_count` | Deployment frequency |\n| `gitlab_ci_environment_deployment_duration_seconds` | Deployment execution time |\n| `gitlab_ci_environment_behind_commits_count` | Environment drift from main |\n\n### Node Exporter metrics\n| Metric | Description |\n| :---- | :---- |\n| `node_cpu_seconds_total` | CPU utilization |\n| `node_memory_MemAvailable_bytes` | Available memory |\n| `node_filesystem_avail_bytes` | Disk space available |\n| `node_load1` | 1-minute load average |\n\n## Troubleshooting\n### Air-gapped Grafana plugin installation\nFor offline environments, install plugins manually. Example for Kubernetes:\n```bash\n# Copy plugin zip into the Grafana pod\nkubectl cp grafana-polystat-panel-2.1.16.zip \\\n  gitlab-observability/grafana-\u003Cpod-id>:/tmp/\n# Extract plugin\nkubectl exec -it -n gitlab-observability deploy/grafana -- \\\n  sh -c \"unzip /tmp/grafana-polystat-panel-2.1.16.zip -d /var/lib/grafana/plugins/\"\n# Restart Grafana pod\nkubectl rollout restart deployment/grafana -n gitlab-observability\n# Verify installation\nkubectl exec -it -n gitlab-observability deploy/grafana -- \\\n  ls -al /var/lib/grafana/plugins/\n```\n\n## Enterprise considerations\nFor regulated industries, ensure:\n*   **Token security:** Store GitLab Personal Access Tokens in a dedicated secrets manager rather than hardcoded in ConfigMaps. Enforce token rotation policies and limit scope to **read\\_api** only.\n*   **Network segmentation:** Deploy behind a reverse proxy with TLS termination. In Kubernetes, use an Ingress controller with automated certificate provisioning.\n*   **Authentication:** Configure Grafana with your organization's identity provider (SAML, LDAP, or OAuth/OIDC) to enforce role-based access control on dashboards.\n\n## Why GitLab?\nGitLab's API-first design enables custom observability solutions that complement native capabilities like Value Stream Analytics and DORA metrics. The open architecture allows organizations to integrate proven open-source tooling — like the gitlab-ci-pipelines-exporter — directly with their existing enterprise infrastructure, without disrupting established workflows.\n\nAs your observability maturity grows, GitLab's built-in Observability capabilities provide a natural next step — offering deeper, integrated visibility without additional tooling. Learn more about what's available natively in the platform for [GitLab Observability](https://docs.gitlab.com/operations/observability/observability/).\n",[110,741,742],"product","tutorial",{"featured":16,"template":17,"slug":744},"how-to-build-ci-cd-observability-at-scale",{"content":746,"config":757},{"body":747,"title":748,"description":749,"authors":750,"heroImage":752,"date":753,"category":13,"tags":754},"Most CI/CD tools can run a build and ship a deployment. Where they diverge is what happens when your delivery needs get real: a monorepo with a dozen services, microservices spread across multiple repositories, deployments to dozens of environments, or a platform team trying to enforce standards without becoming a bottleneck.\n  \nGitLab's pipeline execution model was designed for that complexity. Parent-child pipelines, DAG execution, dynamic pipeline generation, multi-project triggers, merge request pipelines with merged results, and CI/CD Components each solve a distinct class of problems. Because they compose, understanding the full model unlocks something more than a faster pipeline. In this article, you'll learn about the five patterns where that model stands out, each mapped to a real engineering scenario with the configuration to match.\n  \nThe configs below are illustrative. The scripts use echo commands to keep the signal-to-noise ratio low. Swap them out for your actual build, test, and deploy steps and they are ready to use.\n\n\n## 1. Monorepos: Parent-child pipelines + DAG execution\n\n\nThe problem: Your monorepo has a frontend, a backend, and a docs site. Every commit triggers a full rebuild of everything, even when only a README changed.\n\n\nGitLab solves this with two complementary features: [parent-child pipelines](https://docs.gitlab.com/ci/pipelines/downstream_pipelines/#parent-child-pipelines) (which let a top-level pipeline spawn isolated sub-pipelines) and [DAG execution via `needs`](https://docs.gitlab.com/ci/yaml/#needs) (which breaks rigid stage-by-stage ordering and lets jobs start the moment their dependencies finish).\n\n\nA parent pipeline detects what changed and triggers only the relevant child pipelines:\n\n```yaml\n# .gitlab-ci.yml\nstages:\n  - trigger\n\ntrigger-services:\n  stage: trigger\n  trigger:\n    include:\n      - local: '.gitlab/ci/api-service.yml'\n      - local: '.gitlab/ci/web-service.yml'\n      - local: '.gitlab/ci/worker-service.yml'\n    strategy: depend\n```\n\n\nEach child pipeline is a fully independent pipeline with its own stages, jobs, and artifacts. The parent waits for all of them via [strategy: depend](https://docs.gitlab.com/ci/pipelines/downstream_pipelines/#wait-for-downstream-pipeline-to-complete) so you get a single green/red signal at the top level, with full drill-down into each service's pipeline. This organizational separation is the bigger win for large teams: each service owns its pipeline config, changes in one cannot break another, and the complexity stays manageable as the repo grows.\n\n\nOne thing worth knowing: when you pass [multiple files to a single `trigger: include:`](https://docs.gitlab.com/ci/pipelines/downstream_pipelines/#combine-multiple-child-pipeline-configuration-files), GitLab merges them into a single child pipeline configuration. This means jobs defined across those files share the same pipeline context and can reference each other with `needs:`, which is what makes the DAG optimization possible. If you split them into separate trigger jobs instead, each would be its own isolated pipeline and cross-file `needs:` references would not work.\n\n\nCombine this with `needs:` inside each child pipeline and you get DAG execution. Your integration tests can start the moment the build finishes, without waiting for other jobs in the same stage.\n\n```yaml\n# .gitlab/ci/api-service.yml\nstages:\n  - build\n  - test\n\nbuild-api:\n  stage: build\n  script:\n    - echo \"Building API service\"\n\ntest-api:\n  stage: test\n  needs: [build-api]\n  script:\n    - echo \"Running API tests\"\n```\n\n\nWhy it matters: Teams with large monorepos typically report significant reductions in pipeline runtime after switching to DAG execution, since jobs no longer wait on unrelated work in the same stage. Parent-child pipelines add the organizational layer that keeps the configuration maintainable as the repo and team grow.\n\n![Local downstream pipelines](https://res.cloudinary.com/about-gitlab-com/image/upload/v1775738759/Blog/Imported/hackathon-fake-blog-post-s/image3_vwj3rz.png \"Local downstream pipelines\")\n\n## 2. Microservices: Cross-repo, multi-project pipelines\n\n\nThe problem: Your frontend lives in one repo, your backend in another. When the frontend team ships a change, they have no visibility into whether it broke the backend integration and vice versa.\n\n\nGitLab's [multi-project pipelines](https://docs.gitlab.com/ci/pipelines/downstream_pipelines/#multi-project-pipelines) let one project trigger a pipeline in a completely separate project and wait for the result. The triggering project gets a linked downstream pipeline right in its own pipeline view.\n\n\nThe frontend pipeline builds an API contract artifact and publishes it, then triggers the backend pipeline. The backend fetches that artifact directly using the [Jobs API](https://docs.gitlab.com/api/jobs/#download-a-single-artifact-file-from-specific-tag-or-branch) and validates it before allowing anything to proceed. If a breaking change is detected, the backend pipeline fails and the frontend pipeline fails with it.\n\n```yaml\n# frontend repo: .gitlab-ci.yml\nstages:\n  - build\n  - test\n  - trigger-backend\n\nbuild-frontend:\n  stage: build\n  script:\n    - echo \"Building frontend and generating API contract...\"\n    - mkdir -p dist\n    - |\n      echo '{\n        \"api_version\": \"v2\",\n        \"breaking_changes\": false\n      }' > dist/api-contract.json\n    - cat dist/api-contract.json\n  artifacts:\n    paths:\n      - dist/api-contract.json\n    expire_in: 1 hour\n\ntest-frontend:\n  stage: test\n  script:\n    - echo \"All frontend tests passed!\"\n\ntrigger-backend-pipeline:\n  stage: trigger-backend\n  trigger:\n    project: my-org/backend-service\n    branch: main\n    strategy: depend\n  rules:\n    - if: $CI_COMMIT_BRANCH == \"main\"\n```\n\n```yaml\n# backend repo: .gitlab-ci.yml\nstages:\n  - build\n  - test\n\nbuild-backend:\n  stage: build\n  script:\n    - echo \"All backend tests passed!\"\n\nintegration-test:\n  stage: test\n  rules:\n    - if: $CI_PIPELINE_SOURCE == \"pipeline\"\n  script:\n    - echo \"Fetching API contract from frontend...\"\n    - |\n      curl --silent --fail \\\n        --header \"JOB-TOKEN: $CI_JOB_TOKEN\" \\\n        --output api-contract.json \\\n        \"${CI_API_V4_URL}/projects/${FRONTEND_PROJECT_ID}/jobs/artifacts/main/raw/dist/api-contract.json?job=build-frontend\"\n    - cat api-contract.json\n    - |\n      if grep -q '\"breaking_changes\": true' api-contract.json; then\n        echo \"FAIL: Breaking API changes detected - backend integration blocked!\"\n        exit 1\n      fi\n      echo \"PASS: API contract is compatible!\"\n```\n\n\nA few things worth noting in this config. The `integration-test` job uses `$CI_PIPELINE_SOURCE == \"pipeline\"` to ensure it only runs when triggered by an upstream pipeline, not on a standalone push to the backend repo. The frontend project ID is referenced via `$FRONTEND_PROJECT_ID`, which should be set as a [CI/CD variable](https://docs.gitlab.com/ci/variables/) in the backend project settings to avoid hardcoding it.\n\n\nWhy it matters: Cross-service breakage that previously surfaced in production gets caught in the pipeline instead. The dependency between services stops being invisible and becomes something teams can see, track, and act on.\n\n\n![Cross-project pipelines](https://res.cloudinary.com/about-gitlab-com/image/upload/v1775738762/Blog/Imported/hackathon-fake-blog-post-s/image4_h6mfsb.png \"Cross-project pipelines\")\n\n\n## 3. Multi-tenant / matrix deployments: Dynamic child pipelines\n\n\nThe problem: You deploy the same application to 15 customer environments, or three cloud regions, or dev/staging/prod. Updating a deploy stage across all of them one by one is the kind of work that leads to configuration drift. Writing a separate pipeline for each environment is unmaintainable from day one.\n\n\nGitLab's [dynamic child pipelines](https://docs.gitlab.com/ci/pipelines/downstream_pipelines/#dynamic-child-pipelines) let you generate a pipeline at runtime. A job runs a script that produces a YAML file, and that YAML becomes the pipeline for the next stage. The pipeline structure itself becomes data.\n\n\n```yaml\n# .gitlab-ci.yml\nstages:\n  - generate\n  - trigger-environments\n\ngenerate-config:\n  stage: generate\n  script:\n    - |\n      # ENVIRONMENTS can be passed as a CI variable or read from a config file.\n      # Default to dev, staging, prod if not set.\n      ENVIRONMENTS=${ENVIRONMENTS:-\"dev staging prod\"}\n      for ENV in $ENVIRONMENTS; do\n        cat > ${ENV}-pipeline.yml \u003C\u003C EOF\n      stages:\n        - deploy\n        - verify\n      deploy-${ENV}:\n        stage: deploy\n        script:\n          - echo \"Deploying to ${ENV} environment\"\n      verify-${ENV}:\n        stage: verify\n        script:\n          - echo \"Running smoke tests on ${ENV}\"\n      EOF\n      done\n  artifacts:\n    paths:\n      - \"*.yml\"\n    exclude:\n      - \".gitlab-ci.yml\"\n\n.trigger-template:\n  stage: trigger-environments\n  trigger:\n    strategy: depend\n\ntrigger-dev:\n  extends: .trigger-template\n  trigger:\n    include:\n      - artifact: dev-pipeline.yml\n        job: generate-config\n\ntrigger-staging:\n  extends: .trigger-template\n  needs: [trigger-dev]\n  trigger:\n    include:\n      - artifact: staging-pipeline.yml\n        job: generate-config\n\ntrigger-prod:\n  extends: .trigger-template\n  needs: [trigger-staging]\n  trigger:\n    include:\n      - artifact: prod-pipeline.yml\n        job: generate-config\n  when: manual\n```\n\n\nThe generation script loops over an `ENVIRONMENTS` variable rather than hardcoding each environment separately. Pass in a different list via a CI variable or read it from a config file and the pipeline adapts without touching the YAML. The trigger jobs use [extends:](https://docs.gitlab.com/ci/yaml/#extends) to inherit shared configuration from `.trigger-template`, so `strategy: depend` is defined once rather than repeated on every trigger job. Add a new environment by updating the variable, not by duplicating pipeline config. Add [when: manual](https://docs.gitlab.com/ci/yaml/#when) to the production trigger and you get a promotion gate baked right into the pipeline graph.\n\n\nWhy it matters: SaaS companies and platform teams use this pattern to manage dozens of environments without duplicating pipeline logic. The pipeline structure itself stays lean as the deployment matrix grows.\n\n\n![Dynamic pipeline](https://res.cloudinary.com/about-gitlab-com/image/upload/v1775738765/Blog/Imported/hackathon-fake-blog-post-s/image7_wr0kx2.png \"Dynamic pipeline\")\n\n\n## 4. MR-first delivery: Merge request pipelines, merged results, and workflow routing\n\n\nThe problem: Your pipeline runs on every push to every branch. Expensive tests run on feature branches that will never merge. Meanwhile, you have no guarantee that what you tested is actually what will land on `main` after a merge.\n\n\nGitLab has three interlocking features that solve this together:\n\n\n*   [Merge request pipelines](https://docs.gitlab.com/ci/pipelines/merge_request_pipelines/) run only when a merge request exists, not on every branch push. This alone eliminates a significant amount of wasted compute.\n\n*   [Merged results pipelines](https://docs.gitlab.com/ci/pipelines/merged_results_pipelines/) go further. GitLab creates a temporary merge commit (your branch plus the current target branch) and runs the pipeline against that. You are testing what will actually exist after the merge, not just your branch in isolation.\n\n*   [Workflow rules](https://docs.gitlab.com/ci/yaml/workflow/) let you define exactly which pipeline type runs under which conditions and suppress everything else. The `$CI_OPEN_MERGE_REQUESTS` guard below prevents duplicate pipelines firing for both a branch and its open MR simultaneously.\n\n\nWith those three working together, here is what a tiered pipeline looks like:\n\n```yaml\n# .gitlab-ci.yml\nworkflow:\n  rules:\n    - if: $CI_PIPELINE_SOURCE == \"merge_request_event\"\n    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS\n      when: never\n    - if: $CI_COMMIT_BRANCH\n    - if: $CI_PIPELINE_SOURCE == \"schedule\"\n\nstages:\n  - fast-checks\n  - expensive-tests\n  - deploy\n\nlint-code:\n  stage: fast-checks\n  script:\n    - echo \"Running linter\"\n  rules:\n    - if: $CI_PIPELINE_SOURCE == \"push\"\n    - if: $CI_PIPELINE_SOURCE == \"merge_request_event\"\n    - if: $CI_COMMIT_BRANCH == \"main\"\n\nunit-tests:\n  stage: fast-checks\n  script:\n    - echo \"Running unit tests\"\n  rules:\n    - if: $CI_PIPELINE_SOURCE == \"push\"\n    - if: $CI_PIPELINE_SOURCE == \"merge_request_event\"\n    - if: $CI_COMMIT_BRANCH == \"main\"\n\nintegration-tests:\n  stage: expensive-tests\n  script:\n    - echo \"Running integration tests (15 min)\"\n  rules:\n    - if: $CI_PIPELINE_SOURCE == \"merge_request_event\"\n    - if: $CI_COMMIT_BRANCH == \"main\"\n\ne2e-tests:\n  stage: expensive-tests\n  script:\n    - echo \"Running E2E tests (30 min)\"\n  rules:\n    - if: $CI_PIPELINE_SOURCE == \"merge_request_event\"\n    - if: $CI_COMMIT_BRANCH == \"main\"\n\nnightly-comprehensive-scan:\n  stage: expensive-tests\n  script:\n    - echo \"Running full nightly suite (2 hours)\"\n  rules:\n    - if: $CI_PIPELINE_SOURCE == \"schedule\"\n\ndeploy-production:\n  stage: deploy\n  script:\n    - echo \"Deploying to production\"\n  rules:\n    - if: $CI_COMMIT_BRANCH == \"main\"\n      when: manual\n```\n\nWith this setup, the pipeline behaves differently depending on context. A push to a feature branch with no open MR runs lint and unit tests only. Once an MR is opened, the workflow rules switch from a branch pipeline to an MR pipeline, and the full integration and E2E suite runs against the merged result. Merging to `main` queues a manual production deployment. A nightly schedule runs the comprehensive scan once, not on every commit.\n\n\nWhy it matters: Teams routinely cut CI costs significantly with this pattern, not by running fewer tests, but by running the right tests at the right time. Merged results pipelines catch the class of bugs that only appear after a merge, before they ever reach `main`.\n\n\n![Conditional pipelines (within a branch with no MR)](https://res.cloudinary.com/about-gitlab-com/image/upload/v1775738768/Blog/Imported/hackathon-fake-blog-post-s/image6_dnfcny.png \"Conditional pipelines (within a branch with no MR)\")\n\n\n\n![Conditional pipelines (within an MR)](https://res.cloudinary.com/about-gitlab-com/image/upload/v1775738772/Blog/Imported/hackathon-fake-blog-post-s/image1_wyiafu.png \"Conditional pipelines (within an MR)\")\n\n\n\n![Conditional pipelines (on the main branch)](https://res.cloudinary.com/about-gitlab-com/image/upload/v1775738774/Blog/Imported/hackathon-fake-blog-post-s/image5_r6lkfd.png \"Conditional pipelines (on the main branch)\")\n\n## 5. Governed pipelines: CI/CD Components\n\n\nThe problem: Your platform team has defined the right way to build, test, and deploy. But every team has their own `.gitlab-ci.yml` with subtle variations. Security scanning gets skipped. Deployment standards drift. Audits are painful.\n\n\nGitLab [CI/CD Components](https://docs.gitlab.com/ci/components/) let platform teams publish versioned, reusable pipeline building blocks. Application teams consume them with a single `include:` line and optional inputs — no copy-paste, no drift. Components are discoverable through the [CI/CD Catalog](https://docs.gitlab.com/ci/components/#cicd-catalog), which means teams can find and adopt approved building blocks without needing to go through the platform team directly.\n\n\nHere is a component definition from a shared library:\n\n```yaml\n# templates/deploy.yml\nspec:\n  inputs:\n    stage:\n      default: deploy\n    environment:\n      default: production\n---\ndeploy-job:\n  stage: $[[ inputs.stage ]]\n  script:\n    - echo \"Deploying $APP_NAME to $[[ inputs.environment ]]\"\n    - echo \"Deploy URL: $DEPLOY_URL\"\n  environment:\n    name: $[[ inputs.environment ]]\n```\nAnd here is how an application team consumes it:\n\n```yaml\n# Application repo: .gitlab-ci.yml\nvariables:\n  APP_NAME: \"my-awesome-app\"\n  DEPLOY_URL: \"https://api.example.com\"\n\ninclude:\n  - component: gitlab.com/my-org/component-library/build@v1.0.6\n  - component: gitlab.com/my-org/component-library/test@v1.0.6\n  - component: gitlab.com/my-org/component-library/deploy@v1.0.6\n    inputs:\n      environment: staging\n\nstages:\n  - build\n  - test\n  - deploy\n```\n\nThree lines of `include:` replace hundreds of lines of duplicated YAML. The platform team can push a security fix to `v1.0.7` and teams opt in on their own schedule — or the platform team can pin everyone to a minimum version. Either way, one change propagates everywhere instead of needing to be applied repo by repo.\n\n\nPair this with [resource groups](https://docs.gitlab.com/ci/resource_groups/) to prevent concurrent deployments to the same environment, and [protected environments](https://docs.gitlab.com/ci/environments/protected_environments/) to enforce approval gates - and you have a governed delivery platform where compliance is the default, not the exception.\n\n\nWhy it matters: This is the pattern that makes GitLab CI/CD scale across hundreds of teams. Platform engineering teams enforce compliance without becoming a bottleneck. Application teams get a fast path to a working pipeline without reinventing the wheel.\n\n\n![Component pipeline (imported jobs)](https://res.cloudinary.com/about-gitlab-com/image/upload/v1775738776/Blog/Imported/hackathon-fake-blog-post-s/image2_pizuxd.png \"Component pipeline (imported jobs)\")\n\n## Putting it all together\n\nNone of these features exist in isolation. The reason GitLab's pipeline model is worth understanding deeply is that these primitives compose:\n\n*   A monorepo uses parent-child pipelines, and each child uses DAG execution\n\n*   A microservices platform uses multi-project pipelines, and each project uses MR pipelines with merged results\n\n*   A governed platform uses CI/CD components to standardize the patterns above across every team\n\n\nMost teams discover one of these features when they hit a specific pain point. The ones who invest in understanding the full model end up with a delivery system that actually reflects how their engineering organization works, not a pipeline that fights it.\n\n## Other patterns worth exploring\n\n\nThe five patterns above cover the most common structural pain points, but GitLab's pipeline model goes further. A few others worth looking into as your needs grow:\n\n\n*   [Review apps with dynamic environments](https://docs.gitlab.com/ci/environments/) let you spin up a live preview for every feature branch and tear it down automatically when the MR closes. Useful for teams doing frontend work or API changes that need stakeholder sign-off before merging.\n\n*   [Caching and artifact strategies](https://docs.gitlab.com/ci/caching/) are often the fastest way to cut pipeline runtime after the structural work is done. Structuring `cache:` keys around dependency lockfiles and being deliberate about what gets passed between jobs with [artifacts:](https://docs.gitlab.com/ci/yaml/#artifacts) can make a significant difference without changing your pipeline shape at all.\n\n*   [Scheduled and API-triggered pipelines](https://docs.gitlab.com/ci/pipelines/schedules/) are worth knowing about because not everything should run on a code push. Nightly security scans, compliance reports, and release automation are better modeled as scheduled or [API-triggered](https://docs.gitlab.com/ci/triggers/) pipelines with `$CI_PIPELINE_SOURCE` routing the right jobs for each context.\n\n## How to get started\n\nModern software delivery is complex. Teams are managing monorepos with dozens of services, coordinating across multiple repositories, deploying to many environments at once, and trying to keep standards consistent as organizations grow. GitLab's pipeline model was built with all of that in mind.\n\nWhat makes it worth investing time in is how well the pieces fit together. Parent-child pipelines bring structure to large codebases. Multi-project pipelines make cross-team dependencies visible and testable. Dynamic pipelines turn environment management into something that scales gracefully. MR-first delivery with merged results ensures confidence at every step of the review process. And CI/CD Components give platform teams a way to share best practices across an entire organization without becoming a bottleneck.\n\nEach of these features is powerful on its own, and even more so when combined. GitLab gives you the building blocks to design a delivery system that fits how your team actually works, and grows with you as your needs evolve.\n\n> [Start a free trial of GitLab Ultimate](https://about.gitlab.com/free-trial/) to use pipeline logic today.\n\n## Read more\n\n*   [Variable and artifact sharing in GitLab parent-child pipelines](https://about.gitlab.com/blog/variable-and-artifact-sharing-in-gitlab-parent-child-pipelines/)\n*   [CI/CD inputs: Secure and preferred method to pass parameters to a pipeline](https://about.gitlab.com/blog/ci-cd-inputs-secure-and-preferred-method-to-pass-parameters-to-a-pipeline/)\n*   [Tutorial: How to set up your first GitLab CI/CD component](https://about.gitlab.com/blog/tutorial-how-to-set-up-your-first-gitlab-ci-cd-component/)\n*   [How to include file references in your CI/CD components](https://about.gitlab.com/blog/how-to-include-file-references-in-your-ci-cd-components/)\n*   [FAQ: GitLab CI/CD Catalog](https://about.gitlab.com/blog/faq-gitlab-ci-cd-catalog/)\n*   [Building a GitLab CI/CD pipeline for a monorepo the easy way](https://about.gitlab.com/blog/building-a-gitlab-ci-cd-pipeline-for-a-monorepo-the-easy-way/)\n*   [A CI/CD component builder's journey](https://about.gitlab.com/blog/a-ci-component-builders-journey/)\n*   [CI/CD Catalog goes GA: No more building pipelines from scratch](https://about.gitlab.com/blog/ci-cd-catalog-goes-ga-no-more-building-pipelines-from-scratch/)","5 ways GitLab pipeline logic solves real engineering problems","Learn how to scale CI/CD with composable patterns for monorepos, microservices, environments, and governance.",[751],"Omid Khan","https://res.cloudinary.com/about-gitlab-com/image/upload/v1772721753/frfsm1qfscwrmsyzj1qn.png","2026-04-09",[110,755,742,756],"DevOps platform","features",{"featured":30,"template":17,"slug":758},"5-ways-gitlab-pipeline-logic-solves-real-engineering-problems",{"content":760,"config":769},{"title":761,"description":762,"authors":763,"heroImage":765,"date":766,"body":767,"category":13,"tags":768},"How to use GitLab Container Virtual Registry with Docker Hardened Images","Learn how to simplify container image management with this step-by-step guide.",[764],"Tim Rizzi","https://res.cloudinary.com/about-gitlab-com/image/upload/v1772111172/mwhgbjawn62kymfwrhle.png","2026-03-12","If you're a platform engineer, you've probably had this conversation:\n  \n*\"Security says we need to use hardened base images.\"*\n\n*\"Great, where do I configure credentials for yet another registry?\"*\n\n*\"Also, how do we make sure everyone actually uses them?\"*\n\nOr this one:\n\n*\"Why are our builds so slow?\"*\n\n*\"We're pulling the same 500MB image from Docker Hub in every single job.\"*\n\n*\"Can't we just cache these somewhere?\"*\n\nI've been working on [Container Virtual Registry](https://docs.gitlab.com/user/packages/virtual_registry/container/) at GitLab specifically to solve these problems. It's a pull-through cache that sits in front of your upstream registries — Docker Hub, dhi.io (Docker Hardened Images), MCR, and Quay — and gives your teams a single endpoint to pull from. Images get cached on the first pull. Subsequent pulls come from the cache. Your developers don't need to know or care which upstream a particular image came from.\n\nThis article shows you how to set up Container Virtual Registry, specifically with Docker Hardened Images in mind, since that's a combination that makes a lot of sense for teams concerned about security and not making their developers' lives harder.\n\n## What problem are we actually solving?\n\nThe Platform teams I usually talk to manage container images across three to five registries:\n\n* **Docker Hub** for most base images\n* **dhi.io** for Docker Hardened Images (security-conscious workloads)\n* **MCR** for .NET and Azure tooling\n* **Quay.io** for Red Hat ecosystem stuff\n* **Internal registries** for proprietary images\n\nEach one has its own:\n\n* Authentication mechanism\n* Network latency characteristics\n* Way of organizing image paths\n\nYour CI/CD configs end up littered with registry-specific logic. Credential management becomes a project unto itself. And every pipeline job pulls the same base images over the network, even though they haven't changed in weeks.\n\nContainer Virtual Registry consolidates this. One registry URL. One authentication flow (GitLab's). Cached images are served from GitLab's infrastructure rather than traversing the internet each time.\n\n## How it works\n\nThe model is straightforward:\n\n```text\nYour pipeline pulls:\n  gitlab.com/virtual_registries/container/1000016/python:3.13\n\nVirtual registry checks:\n  1. Do I have this cached? → Return it\n  2. No? → Fetch from upstream, cache it, return it\n\n```\n\nYou configure upstreams in priority order. When a pull request comes in, the virtual registry checks each upstream until it finds the image. The result gets cached for a configurable period (default 24 hours).\n\n```text\n┌─────────────────────────────────────────────────────────┐\n│                    CI/CD Pipeline                       │\n│                          │                              │\n│                          ▼                              │\n│   gitlab.com/virtual_registries/container/\u003Cid>/image   │\n└─────────────────────────────────────────────────────────┘\n                           │\n                           ▼\n┌─────────────────────────────────────────────────────────┐\n│            Container Virtual Registry                   │\n│                                                         │\n│  Upstream 1: Docker Hub ────────────────┐               │\n│  Upstream 2: dhi.io (Hardened) ────────┐│               │\n│  Upstream 3: MCR ─────────────────────┐││               │\n│  Upstream 4: Quay.io ────────────────┐│││               │\n│                                      ││││               │\n│                    ┌─────────────────┴┴┴┴──┐            │\n│                    │        Cache          │            │\n│                    │  (manifests + layers) │            │\n│                    └───────────────────────┘            │\n└─────────────────────────────────────────────────────────┘\n```\n\n## Why this matters for Docker Hardened Images\n\n[Docker Hardened Images](https://docs.docker.com/dhi/) are great because of the minimal attack surface, near-zero CVEs, proper software bills of materials (SBOMs), and SLSA provenance. If you're evaluating base images for security-sensitive workloads, they should be on your list.\n\nBut adopting them creates the same operational friction as any new registry:\n\n* **Credential distribution**: You need to get Docker credentials to every system that pulls images from dhi.io.\n* **CI/CD changes**: Every pipeline needs to be updated to authenticate with dhi.io.\n* **Developer friction**: People need to remember to use the hardened variants.\n* **Visibility gap**: It's difficult to tell if teams are actually using hardened images vs. regular ones.\n\nVirtual registry addresses each of these:\n\n**Single credential**: Teams authenticate to GitLab. The virtual registry handles upstream authentication. You configure Docker credentials once, at the registry level, and they apply to all pulls.\n\n**No CI/CD changes per-team**: Point pipelines at your virtual registry. Done. The upstream configuration is centralized.\n\n**Gradual adoption**: Since images get cached with their full path, you can see in the cache what's being pulled. If someone's pulling `library/python:3.11` instead of the hardened variant, you'll know.\n\n**Audit trail**: The cache shows you exactly which images are in active use. Useful for compliance, useful for understanding what your fleet actually depends on.\n\n## Setting it up\n\nHere's a real setup using the Python client from this demo project.\n\n### Create the virtual registry\n\n```python\nfrom virtual_registry_client import VirtualRegistryClient\n\nclient = VirtualRegistryClient()\n\nregistry = client.create_virtual_registry(\n    group_id=\"785414\",  # Your top-level group ID\n    name=\"platform-images\",\n    description=\"Cached container images for platform teams\"\n)\n\nprint(f\"Registry ID: {registry['id']}\")\n# You'll need this ID for the pull URL\n```\n\n### Add Docker Hub as an upstream\n\nFor official images like Alpine, Python, etc.:\n\n```python\ndocker_upstream = client.create_upstream(\n    registry_id=registry['id'],\n    url=\"https://registry-1.docker.io\",\n    name=\"Docker Hub\",\n    cache_validity_hours=24\n)\n```\n\n### Add Docker Hardened Images (dhi.io)\n\nDocker Hardened Images are hosted on `dhi.io`, a separate registry that requires authentication:\n\n```python\ndhi_upstream = client.create_upstream(\n    registry_id=registry['id'],\n    url=\"https://dhi.io\",\n    name=\"Docker Hardened Images\",\n    username=\"your-docker-username\",\n    password=\"your-docker-access-token\",\n    cache_validity_hours=24\n)\n```\n\n### Add other upstreams\n\n```python\n# MCR for .NET teams\nclient.create_upstream(\n    registry_id=registry['id'],\n    url=\"https://mcr.microsoft.com\",\n    name=\"Microsoft Container Registry\",\n    cache_validity_hours=48\n)\n\n# Quay for Red Hat stuff\nclient.create_upstream(\n    registry_id=registry['id'],\n    url=\"https://quay.io\",\n    name=\"Quay.io\",\n    cache_validity_hours=24\n)\n```\n\n### Update your CI/CD\n\nHere's a `.gitlab-ci.yml` that pulls through the virtual registry:\n\n```yaml\nvariables:\n  VIRTUAL_REGISTRY_ID: \u003Cyour_virtual_registry_ID>\n\n  \nbuild:\n  image: docker:24\n  services:\n    - docker:24-dind\n  before_script:\n    # Authenticate to GitLab (which handles upstream auth for you)\n    - echo \"${CI_JOB_TOKEN}\" | docker login -u gitlab-ci-token --password-stdin gitlab.com\n  script:\n    # All of these go through your single virtual registry\n    \n    # Official Docker Hub images (use library/ prefix)\n    - docker pull gitlab.com/virtual_registries/container/${VIRTUAL_REGISTRY_ID}/library/alpine:latest\n    \n    # Docker Hardened Images from dhi.io (no prefix needed)\n    - docker pull gitlab.com/virtual_registries/container/${VIRTUAL_REGISTRY_ID}/python:3.13\n    \n    # .NET from MCR\n    - docker pull gitlab.com/virtual_registries/container/${VIRTUAL_REGISTRY_ID}/dotnet/sdk:8.0\n```\n\n### Image path formats\n\nDifferent registries use different path conventions:\n\n| Registry | Pull URL Example |\n|----------|------------------|\n| Docker Hub (official) | `.../library/python:3.11-slim` |\n| Docker Hardened Images (dhi.io) | `.../python:3.13` |\n| MCR | `.../dotnet/sdk:8.0` |\n| Quay.io | `.../prometheus/prometheus:latest` |\n\n### Verify it's working\n\nAfter some pulls, check your cache:\n\n```python\nupstreams = client.list_registry_upstreams(registry['id'])\nfor upstream in upstreams:\n    entries = client.list_cache_entries(upstream['id'])\n    print(f\"{upstream['name']}: {len(entries)} cached entries\")\n\n```\n\n## What the numbers look like\n\nI ran tests pulling images through the virtual registry:\n\n| Metric | Without Cache | With Warm Cache |\n|--------|---------------|-----------------|\n| Pull time (Alpine) | 10.3s | 4.2s |\n| Pull time (Python 3.13 DHI) | 11.6s | ~4s |\n| Network roundtrips to upstream | Every pull | Cache misses only |\n\n\n\n\nThe first pull is the same speed (it has to fetch from upstream). Every pull after that, for the cache validity period, comes straight from GitLab's storage. No network hop to Docker Hub, dhi.io, MCR, or wherever the image lives.\n\nFor a team running hundreds of pipeline jobs per day, that's hours of cumulative build time saved.\n\n## Practical considerations\nHere are some considerations to keep in mind:\n\n### Cache validity\n\n24 hours is the default. For security-sensitive images where you want patches quickly, consider 12 hours or less:\n\n```python\nclient.create_upstream(\n    registry_id=registry['id'],\n    url=\"https://dhi.io\",\n    name=\"Docker Hardened Images\",\n    username=\"your-username\",\n    password=\"your-token\",\n    cache_validity_hours=12\n)\n```\n\nFor stable, infrequently-updated images (like specific version tags), longer validity is fine.\n\n### Upstream priority\n\nUpstreams are checked in order. If you have images with the same name on different registries, the first matching upstream wins.\n\n### Limits\n\n* Maximum of 20 virtual registries per group\n* Maximum of 20 upstreams per virtual registry\n\n## Configuration via UI\n\nYou can also configure virtual registries and upstreams directly from the GitLab UI—no API calls required. Navigate to your group's **Settings > Packages and registries > Virtual Registry** to:\n\n* Create and manage virtual registries\n* Add, edit, and reorder upstream registries\n* View and manage the cache\n* Monitor which images are being pulled\n\n## What's next\n\nWe're actively developing:\n\n* **Allow/deny lists**: Use regex to control which images can be pulled from specific upstreams.\n\nThis is beta software. It works, people are using it in production, but we're still iterating based on feedback.\n\n## Share your feedback\n\nIf you're a platform engineer dealing with container registry sprawl, I'd like to understand your setup:\n\n* How many upstream registries are you managing?\n* What's your biggest pain point with the current state?\n* Would something like this help, and if not, what's missing?\n\nPlease share your experiences in the [Container Virtual Registry feedback issue](https://gitlab.com/gitlab-org/gitlab/-/work_items/589630).\n## Related resources\n- [New GitLab metrics and registry features help reduce CI/CD bottlenecks](https://about.gitlab.com/blog/new-gitlab-metrics-and-registry-features-help-reduce-ci-cd-bottlenecks/#container-virtual-registry)\n- [Container Virtual Registry documentation](https://docs.gitlab.com/user/packages/virtual_registry/container/)\n- [Container Virtual Registry API](https://docs.gitlab.com/api/container_virtual_registries/)",[742,741,756],{"featured":16,"template":17,"slug":770},"using-gitlab-container-virtual-registry-with-docker-hardened-images",{"promotions":772},[773,787,798,810],{"id":774,"categories":775,"header":777,"text":778,"button":779,"image":784},"ai-modernization",[776],"ai-ml","Is AI achieving its promise at scale?","Quiz will take 5 minutes or less",{"text":780,"config":781},"Get your AI maturity score",{"href":782,"dataGaName":783,"dataGaLocation":245},"/assessments/ai-modernization-assessment/","modernization assessment",{"config":785},{"src":786},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1772138786/qix0m7kwnd8x2fh1zq49.png",{"id":788,"categories":789,"header":790,"text":778,"button":791,"image":795},"devops-modernization",[741,572],"Are you just managing tools or shipping innovation?",{"text":792,"config":793},"Get your DevOps maturity score",{"href":794,"dataGaName":783,"dataGaLocation":245},"/assessments/devops-modernization-assessment/",{"config":796},{"src":797},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1772138785/eg818fmakweyuznttgid.png",{"id":799,"categories":800,"header":802,"text":778,"button":803,"image":807},"security-modernization",[801],"security","Are you trading speed for security?",{"text":804,"config":805},"Get your security maturity score",{"href":806,"dataGaName":783,"dataGaLocation":245},"/assessments/security-modernization-assessment/",{"config":808},{"src":809},"https://res.cloudinary.com/about-gitlab-com/image/upload/v1772138786/p4pbqd9nnjejg5ds6mdk.png",{"id":811,"paths":812,"header":815,"text":816,"button":817,"image":822},"github-azure-migration",[813,814],"migration-from-azure-devops-to-gitlab","integrating-azure-devops-scm-and-gitlab","Is your team ready for GitHub's Azure move?","GitHub is already rebuilding around Azure. Find out what it means for you.",{"text":818,"config":819},"See how GitLab compares to GitHub",{"href":820,"dataGaName":821,"dataGaLocation":245},"/compare/gitlab-vs-github/github-azure-migration/","github azure migration",{"config":823},{"src":797},{"header":825,"blurb":826,"button":827,"secondaryButton":832},"Start building faster today","See what your team can do with the intelligent orchestration platform for DevSecOps.\n",{"text":828,"config":829},"Get your free trial",{"href":830,"dataGaName":52,"dataGaLocation":831},"https://gitlab.com/-/trial_registrations/new?glm_content=default-saas-trial&glm_source=about.gitlab.com/","feature",{"text":508,"config":833},{"href":56,"dataGaName":57,"dataGaLocation":831},1777493629325]