Skip to content

Security policy sync fan-out saturating the database

This runbook covers incidents where security policy synchronization jobs flood Sidekiq and saturate the primary database. The workers involved belong to the security_policy_management feature category, owned by the Security Policies group (#g_srm_security_policies on Slack).

It applies to GitLab.com, GitLab Dedicated and self-managed instances. It builds on the generic Sidekiq runbooks and does not repeat them:

Act when web requests are affected. Commands and details are in Mitigation.

  1. Inspect the buffers to confirm the fan-out.
  2. Defer SyncProjectPolicyWorker and UnenforceablePolicyRulesNotificationWorker with their run_sidekiq_jobs_* flags. This works on every version.
  3. Lower the concurrency limit, then resume the deferred workers in steps.
  4. Clean up the flags and overrides, then restore enforcement.

How the fan-out works, the fixes by version and past incidents are in the sections at the end.

  • Primary database CPU near 100%, high active connections, or PgBouncer pool saturation.
  • Webservice latency rises, pods restart, and users see 502 errors.
  • Large and growing concurrency-limit buffers for the workers above.
  • Merge requests stay in the Checking state, because each sweep resets policy violations to running until the follow-up jobs finish.
  • Sidekiq failures with Rule idx has already been taken.

Concurrency-limit buffer and running jobs, per worker:

sum by (worker) (sidekiq_concurrency_limit_queue_jobs{feature_category="security_policy_management"})
sum by (worker) (sidekiq_concurrency_limit_current_concurrent_jobs{feature_category="security_policy_management"})

Database time spent by the feature category. Compare it with the number of primary vCPUs:

sum by (worker) (rate(sidekiq_jobs_db_seconds_sum{feature_category="security_policy_management"}[5m]))

Job completions and failures:

sum by (worker) (rate(sidekiq_jobs_completion_count{feature_category="security_policy_management"}[5m]))
sum by (worker) (rate(sidekiq_jobs_failed_total{feature_category="security_policy_management"}[5m]))

Jobs deferred by a run_sidekiq_jobs_* flag. A non-zero value hours after an incident means enforcement is still paused:

sum by (worker) (rate(sidekiq_jobs_skipped_total{feature_category="security_policy_management", action="deferred", reason="feature_flag"}[5m]))

Add the environment selector for GitLab.com. On GitLab.com, the Worker Concurrency Detail dashboard shows the buffer and running jobs.

The existing HighSecurityPolicyWorkerDatabaseDuration alert fires on the average database time per job, in gprd only. A storm of many short jobs does not trip it, so do not wait for it.

In the Sidekiq logs, filter on json.meta.feature_category: security_policy_management and:

  • Count by json.class to see which workers dominate. SyncProjectPolicyWorker far ahead of everything else means a fan-out.
  • Sum json.db_duration_s by json.class to see which worker uses the database.
  • For json.job_status: fail, look at json.error_message. Rule idx has already been taken means each failure adds a resync job.
  • Look at the earliest Security::SyncPolicyWorker, Security::PersistSecurityPoliciesWorker and Security::SyncScanPoliciesWorker jobs, and their json.meta.project, json.meta.user and json.meta.caller_id, to find the policy project and the trigger.
  1. Is it a policy fan-out? Yes, if most Sidekiq database time and most buffered jobs belong to security_policy_management, with SyncProjectPolicyWorker or the per-merge-request workers at the top.
  2. What started it? Match the earliest jobs to the trigger table. Record the policy project, the trigger and the time.
  3. Is the trigger still active? New SyncPolicyWorker or PersistSecurityPoliciesWorker jobs mean more writes are arriving. Ask the owners of the policy project to stop merging, approving with auto-merge, or editing policies until the backlog drains. Blocking the user does not stop a cascade that is already running.
  4. Which version is the instance on? The available controls depend on it. See Mitigation.
  5. Bring in the Security Policies group in #g_srm_security_policies, as described in Find the owning team.

Act when web requests are affected. If only background jobs are delayed and the database is healthy, letting the backlog drain is acceptable.

The commands below use the Rails console. On GitLab.com, the ChatOps equivalents work too. They share the CL and W constants defined in step 1. Run those definitions again in every new console session.

CL = Gitlab::SidekiqMiddleware::ConcurrencyLimit::ConcurrencyLimitService
W = %w[
Security::SyncPolicyWorker
Security::SyncProjectPolicyWorker
Security::SyncProjectPoliciesWorker
Security::SyncMergeRequestsWorker
Security::UnenforceablePolicyRulesNotificationWorker
]
W.each { |w| puts "#{w}: buffered=#{CL.queue_size(w)} running=#{CL.concurrent_worker_count(w)} limit=#{CL.current_limit(w)}" }

2. Relieve the database now: defer the workers

Section titled “2. Relieve the database now: defer the workers”

This works on every version and takes effect within about a minute. Deferred jobs are rescheduled 5 minutes later. Nothing is lost, and jobs that are already running finish.

Feature.disable(:"run_sidekiq_jobs_Security::SyncProjectPolicyWorker")
Feature.disable(:"run_sidekiq_jobs_Security::UnenforceablePolicyRulesNotificationWorker")
# Optional: stops new fan-out if someone changes a policy again.
Feature.disable(:"run_sidekiq_jobs_Security::SyncPolicyWorker")

Before you move on, post in the incident channel which flags you set and when you will review them. Keep that review time on the incident timeline. While a policy worker is deferred, policy changes do not reach projects and merge request approval rules are not updated. Nothing alerts on this, and it has stayed unnoticed for days in a past incident.

For workers with a concurrency limit, buffered jobs only see the flag when they are released. The buffer therefore drains into the Sidekiq scheduled set, which keeps the jobs in Redis. Check Redis memory with the decision gate.

3. Lower the concurrency limit, then resume

Section titled “3. Lower the concurrency limit, then resume”

A lower limit keeps the jobs in the concurrency-limit buffer and lets them run at a rate the database can sustain. It is the preferred way to resume, because enforcement keeps progressing. Start at about 10 to 20 concurrent jobs per worker on a small instance, and raise the limit while you watch database CPU.

Use the override API through ChatOps on GitLab.com, or the admin API elsewhere. Overrides last from 1 second to 1 day (default 30 minutes), take precedence over adaptive throttling, and are rejected while a worker is paused.

Terminal window
curl --request PUT \
--header "PRIVATE-TOKEN: <admin_token>" \
--header "Content-Type: application/json" \
--data '{"limit":20,"ttl":7200}' \
--url "https://gitlab.example.com/api/v4/admin/sidekiq/concurrency_limits/Security::SyncProjectPolicyWorker"

The Rails console equivalent:

CL.set_override_limit!("Security::SyncProjectPolicyWorker", limit: 20, ttl: 2.hours.to_i)
CL.override_status("Security::SyncProjectPolicyWorker") # => { limit: 20, ttl: ... }
CL.clear_override_limit!("Security::SyncProjectPolicyWorker") # when done

These versions have no override. Set the stored limit from the Rails console:

CL.set_current_limit!("Security::SyncProjectPolicyWorker", limit: 20)
CL.current_limit("Security::SyncProjectPolicyWorker") # check that it stuck

The value expires after 30 minutes and then falls back to the class default (300 or 200). Adaptive throttling also writes this value, and its recovery can raise it again. Re-run the command every 20 to 25 minutes, and check it with current_limit, until the buffer is empty.

gitlab!277261, not merged yet, adds the GITLAB_SIDEKIQ_CONCURRENCY_LIMIT_MULTIPLIER environment variable, which scales every explicit concurrency limit, for example 0.1 to turn 300 into 30. It is proposed for backport, and it would let smaller instances fit the limits permanently, without a console or an expiring override. Sidekiq reads it at startup, so changing it needs a restart. gitlab!276877 proposes the same multiplier as an application setting that applies without a restart.

After the limit is lowered, let deferred jobs run again in steps. Raise the percentage about every 10 minutes while database CPU stays healthy:

Feature.enable_percentage_of_actors(:"run_sidekiq_jobs_Security::SyncProjectPolicyWorker", 10) # then 25, 50

Each job execution is a separate actor, so the percentage is the share of picked-up jobs that run. The rest are deferred for another 5 minutes. Remove the flag when you reach 100%. See Cleanup.

  • Do not drop SyncPolicyWorker, SyncProjectPolicyWorker or SyncProjectPoliciesWorker. Dropped syncs leave approval rules out of date for the affected projects. Fixing that needs a resync, which starts another fan-out. Dropping UnenforceablePolicyRulesNotificationWorker is acceptable when Redis memory is at risk, with approval as described in the decision gate: it is enqueued again when a merge request is refreshed or a pipeline is created.
  • Do not leave a worker deferred without an end time. A deferred policy worker is a silent enforcement gap.
  • Do not scale up Sidekiq. It adds load to the database, which is the bottleneck.
  • Do not resync the whole policy configuration from the UI during the incident. It is another full fan-out.
  • Do not bypass the concurrency limit with disable_sidekiq_concurrency_limit_middleware_* while the database is saturated. The latch procedure in the concurrency-limit runbook assumes the database has recovered.
  1. When the buffers are empty, remove every flag and override you set. This often happens in a new console session, so first run the CL and W definitions from step 1.

    W.each { |w| Feature.remove(:"run_sidekiq_jobs_#{w}") }
    W.each { |w| puts "#{w}: run=#{Feature.enabled?(:"run_sidekiq_jobs_#{w}", type: :worker, default_enabled_if_undefined: true)} drop=#{Feature.enabled?(:"drop_sidekiq_jobs_#{w}", type: :worker, default_enabled_if_undefined: false)}" }

    On GitLab.com, also check /chatops gitlab run feature list --match run_sidekiq_jobs. On 19.6 and later, clear any override with clear_override_limit! or the API DELETE.

  2. Confirm that sidekiq_jobs_skipped_total for the feature category has dropped to zero.

Once the queues are empty, check that policies are enforced again. Work with the Security Policies group, and keep every step limited to the affected projects. Do not resync the whole configuration.

  1. Find projects whose sync failed. In the Sidekiq logs, collect json.args (the first argument is the project ID) for Security::SyncProjectPolicyWorker jobs with json.job_status: fail, and for jobs dropped while a drop flag was on. A resync job that fails again is discarded after it removed the policy’s approval rules from the project, so these projects may have no policy rules at all.

  2. Resync those projects one at a time, paced, from the Rails console:

    project = Project.find(project_id)
    project.all_security_orchestration_policy_configurations.each do |configuration|
    Security::SyncProjectPoliciesWorker.perform_async(project.id, configuration.id, { 'force_resync' => true })
    end

    This is what the Resync policies action does for a single project. It enqueues one SyncProjectPolicyWorker job per policy, each of which sweeps the project’s open merge requests.

  3. Check merge requests stuck in Checking. A merge request stays blocked while it has policy violations in the running state:

    Security::ScanResultPolicyViolation.running.where(project_id: project_id).where('updated_at < ?', 1.hour.ago).count

    On 19.6 and later, Security::ScanResultPolicies::SweepStaleRunningViolationsWorker re-evaluates violations that have been running for more than an hour. On earlier versions, re-evaluate the merge request with merge_request.schedule_policy_synchronization, or ask the author to use the mergeRequestResyncSecurityPolicies GraphQL mutation (rate-limited to once a minute per merge request).

  4. Spot-check approval rules on a few open merge requests in the affected projects. The merge request widget should list the policy approval rules, and their required approvals should match the policy.

  • All run_sidekiq_jobs_* and drop_sidekiq_jobs_* flags for the feature category are removed, and the removal time is on the incident timeline.
  • Concurrency-limit overrides are cleared, or expired by design.
  • Projects with failed or dropped syncs were resynced, and their merge requests re-evaluated.
  • The trigger (policy project, type of write, time) is recorded in the incident.
  • The instance version is recorded, and the Security Policies group has confirmed which fixes below apply to it.
  • If the instance runs a version without the fixes, an upgrade or a backport request is tracked.

One change to a security policy project can enqueue work for every project the policy applies to, and then for every open merge request in those projects:

  1. A merge or push to the policy project runs Security::PersistSecurityPoliciesWorker, which publishes one event per created or changed policy.
  2. Security::SyncPolicyWorker runs once per changed policy and enqueues one Security::SyncProjectPolicyWorker job per project in scope.
  3. For approval policies, each SyncProjectPolicyWorker job rewrites the approval rules of every open merge request in the project. Each merge request gets one database transaction per approval rule, and 3 to 5 follow-up jobs, such as Security::UnenforceablePolicyRulesNotificationWorker and Security::ScanResultPolicies::SyncPreexistingStatesApprovalRulesWorker.
  4. If a sync fails with a validation error, such as Validation failed: Rule idx has already been taken, the worker enqueues a resync job for the same project and policy. Each failure adds more work.

So one write costs roughly changed policies x projects sync jobs and changed policies x open merge requests sweeps. In one incident, a single merge in a policy project led to about 115,000 SyncProjectPolicyWorker jobs, more than a million job starts, and about 90,000 buffered UnenforceablePolicyRulesNotificationWorker jobs. Database CPU stayed at 100% and web requests returned 502 errors.

Other triggers follow the same pattern:

TriggerFirst workers to look for
Merge or push to a policy project, including an auto-merge after an approvalSecurity::SyncScanPoliciesWorker, Security::PersistSecurityPoliciesWorker, then Security::SyncPolicyWorker
Policy resync from the UI or the resyncSecurityPolicies GraphQL mutation, security policy project assigned or unassignedSecurity::SyncScanPoliciesWorker with force_resync, Security::SyncPolicyConfigurationWorker, Security::SyncProjectPoliciesWorker
Group-level protected branch created or removedSecurity::SyncPolicyEventWorker, then one SyncProjectPolicyWorker per project and approval policy
Compliance framework or security attribute assigned to many projectsSecurity::SyncPolicyEventWorker
Project created in or transferred into a group with policiesSecurity::SyncProjectPoliciesWorker, one SyncProjectPolicyWorker per policy

Default concurrency limits are fixed per worker class and were sized for GitLab.com:

WorkerLimit
Security::SyncPolicyWorker300
Security::SyncProjectPolicyWorker300
Security::SyncProjectPoliciesWorker200
Security::SyncMergeRequestsWorker200
Security::UnenforceablePolicyRulesNotificationWorker200

On a smaller instance these limits can be higher than the number of Sidekiq threads, so they cap nothing. More Sidekiq replicas do not help: the primary database is the bottleneck, and more replicas add more load to it.

ChangeMerge requestVersion
Batch SyncProjectPolicyWorker enqueues with delaysgitlab!21629818.8
Fix SyncPolicyWorker timeoutsgitlab!23499419.0
Concurrency limit on SyncPolicyWorkergitlab!23674919.1
Realign policy indexes when approval policies are reordered (Rule idx has already been taken)gitlab!259557, backports gitlab!276048 (19.4) and gitlab!276049 (19.5) in review19.6
Skip approval rule cleanup for projects that were never linkedgitlab!26173419.6
Skip merge request sweeps for policies an event does not affectgitlab!26399519.6
Sync only listed projects for project-list scopesgitlab!26373819.6
Debounce the configuration sync after policy project changesgitlab!26401119.6
One configuration event for a policy resyncgitlab!26593419.6
Temporary concurrency limit overrides and admin APIgitlab!260640, gitlab!26064119.6
Skip zeroing approval rules that already require no approvalsgitlab!27299119.7
Instance-wide concurrency limit multipliergitlab!277261 (environment variable, backport proposed), gitlab!276877 (application setting)Not merged

Related bugs:

  • gitlab#599018: SyncPolicyWorker statement timeouts on instances with many policies, which retried in a loop.
  • gitlab#625029: approval policy rules can silently fail to resync after an interrupted policy sync.
  • gitlab#625042: policy sync fails on a duplicate approval rule group row.

Still open:

  • gitlab#642802: sync a created or transferred project in one job.
  • gitlab#607604: a policy scope change re-evaluates every project, not only the changed ones.

Most incidents of this kind have been on GitLab Dedicated, where one policy project can apply to tens of thousands of projects on a smaller database and Sidekiq fleet. Public GitLab.com examples:

  • production#20797: one group-level policy change flooded the catchall shard with SyncProjectPolicyWorker jobs.
  • production#22432: a policy update ran more than 10,000 concurrent SyncProjectPolicyWorker jobs, above the worker’s concurrency limit, and CI pipelines stayed pending.

Patterns seen across incidents:

  • The trigger is a single action in a policy project: a merge, an auto-merge after an approval, or a group policy edit.
  • Static concurrency limits did not protect the database, either because they were higher than the fleet or because re-enqueued and retried jobs bypassed them.
  • Retries amplify the load: statement timeouts and Rule idx has already been taken failures each add more jobs.
  • A worker left deferred after an incident stopped policies from applying for about 11 days before anyone noticed.