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:
- Disabling Sidekiq workers: deferring and dropping jobs with feature flags.
- Runaway Sidekiq backlog: backlogs that threaten
redis-sidekiq. - Sidekiq Concurrency Limit: the concurrency-limit buffer, the deferred-queue latch and the temporary override.
Quick mitigation
Section titled “Quick mitigation”Act when web requests are affected. Commands and details are in Mitigation.
- Inspect the buffers to confirm the fan-out.
- Defer
SyncProjectPolicyWorkerandUnenforceablePolicyRulesNotificationWorkerwith theirrun_sidekiq_jobs_*flags. This works on every version. - Lower the concurrency limit, then resume the deferred workers in steps.
- 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.
Symptoms
Section titled “Symptoms”- 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
runninguntil the follow-up jobs finish. - Sidekiq failures with
Rule idx has already been taken.
Detection
Section titled “Detection”Metrics
Section titled “Metrics”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.classto see which workers dominate.SyncProjectPolicyWorkerfar ahead of everything else means a fan-out. - Sum
json.db_duration_sbyjson.classto see which worker uses the database. - For
json.job_status: fail, look atjson.error_message.Rule idx has already been takenmeans each failure adds a resync job. - Look at the earliest
Security::SyncPolicyWorker,Security::PersistSecurityPoliciesWorkerandSecurity::SyncScanPoliciesWorkerjobs, and theirjson.meta.project,json.meta.userandjson.meta.caller_id, to find the policy project and the trigger.
Triage
Section titled “Triage”- Is it a policy fan-out? Yes, if most Sidekiq database time and most buffered jobs belong to
security_policy_management, withSyncProjectPolicyWorkeror the per-merge-request workers at the top. - What started it? Match the earliest jobs to the trigger table. Record the policy project, the trigger and the time.
- Is the trigger still active? New
SyncPolicyWorkerorPersistSecurityPoliciesWorkerjobs 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. - Which version is the instance on? The available controls depend on it. See Mitigation.
- Bring in the Security Policies group in
#g_srm_security_policies, as described in Find the owning team.
Mitigation
Section titled “Mitigation”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.
1. Inspect the buffers
Section titled “1. Inspect the buffers”CL = Gitlab::SidekiqMiddleware::ConcurrencyLimit::ConcurrencyLimitServiceW = %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.
GitLab 19.6 and later: temporary override
Section titled “GitLab 19.6 and later: temporary override”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.
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 doneGitLab 19.5 and earlier: console only
Section titled “GitLab 19.5 and earlier: console only”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 stuckThe 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.
Upcoming: instance-wide multiplier
Section titled “Upcoming: instance-wide multiplier”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.
Resuming deferred workers
Section titled “Resuming deferred workers”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, 50Each 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.
What not to do
Section titled “What not to do”- Do not drop
SyncPolicyWorker,SyncProjectPolicyWorkerorSyncProjectPoliciesWorker. Dropped syncs leave approval rules out of date for the affected projects. Fixing that needs a resync, which starts another fan-out. DroppingUnenforceablePolicyRulesNotificationWorkeris 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.
4. Cleanup
Section titled “4. Cleanup”-
When the buffers are empty, remove every flag and override you set. This often happens in a new console session, so first run the
CLandWdefinitions 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 withclear_override_limit!or the APIDELETE. -
Confirm that
sidekiq_jobs_skipped_totalfor the feature category has dropped to zero.
Recovery: restore enforcement
Section titled “Recovery: restore enforcement”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.
-
Find projects whose sync failed. In the Sidekiq logs, collect
json.args(the first argument is the project ID) forSecurity::SyncProjectPolicyWorkerjobs withjson.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. -
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 })endThis is what the Resync policies action does for a single project. It enqueues one
SyncProjectPolicyWorkerjob per policy, each of which sweeps the project’s open merge requests. -
Check merge requests stuck in Checking. A merge request stays blocked while it has policy violations in the
runningstate:Security::ScanResultPolicyViolation.running.where(project_id: project_id).where('updated_at < ?', 1.hour.ago).countOn 19.6 and later,
Security::ScanResultPolicies::SweepStaleRunningViolationsWorkerre-evaluates violations that have beenrunningfor more than an hour. On earlier versions, re-evaluate the merge request withmerge_request.schedule_policy_synchronization, or ask the author to use themergeRequestResyncSecurityPoliciesGraphQL mutation (rate-limited to once a minute per merge request). -
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.
Follow-up checklist
Section titled “Follow-up checklist”- All
run_sidekiq_jobs_*anddrop_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.
How the fan-out works
Section titled “How the fan-out works”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:
- A merge or push to the policy project runs
Security::PersistSecurityPoliciesWorker, which publishes one event per created or changed policy. Security::SyncPolicyWorkerruns once per changed policy and enqueues oneSecurity::SyncProjectPolicyWorkerjob per project in scope.- For approval policies, each
SyncProjectPolicyWorkerjob 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 asSecurity::UnenforceablePolicyRulesNotificationWorkerandSecurity::ScanResultPolicies::SyncPreexistingStatesApprovalRulesWorker. - 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:
| Trigger | First workers to look for |
|---|---|
| Merge or push to a policy project, including an auto-merge after an approval | Security::SyncScanPoliciesWorker, Security::PersistSecurityPoliciesWorker, then Security::SyncPolicyWorker |
Policy resync from the UI or the resyncSecurityPolicies GraphQL mutation, security policy project assigned or unassigned | Security::SyncScanPoliciesWorker with force_resync, Security::SyncPolicyConfigurationWorker, Security::SyncProjectPoliciesWorker |
| Group-level protected branch created or removed | Security::SyncPolicyEventWorker, then one SyncProjectPolicyWorker per project and approval policy |
| Compliance framework or security attribute assigned to many projects | Security::SyncPolicyEventWorker |
| Project created in or transferred into a group with policies | Security::SyncProjectPoliciesWorker, one SyncProjectPolicyWorker per policy |
Default concurrency limits are fixed per worker class and were sized for GitLab.com:
| Worker | Limit |
|---|---|
Security::SyncPolicyWorker | 300 |
Security::SyncProjectPolicyWorker | 300 |
Security::SyncProjectPoliciesWorker | 200 |
Security::SyncMergeRequestsWorker | 200 |
Security::UnenforceablePolicyRulesNotificationWorker | 200 |
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.
Fixes by version
Section titled “Fixes by version”| Change | Merge request | Version |
|---|---|---|
Batch SyncProjectPolicyWorker enqueues with delays | gitlab!216298 | 18.8 |
Fix SyncPolicyWorker timeouts | gitlab!234994 | 19.0 |
Concurrency limit on SyncPolicyWorker | gitlab!236749 | 19.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 review | 19.6 |
| Skip approval rule cleanup for projects that were never linked | gitlab!261734 | 19.6 |
| Skip merge request sweeps for policies an event does not affect | gitlab!263995 | 19.6 |
| Sync only listed projects for project-list scopes | gitlab!263738 | 19.6 |
| Debounce the configuration sync after policy project changes | gitlab!264011 | 19.6 |
| One configuration event for a policy resync | gitlab!265934 | 19.6 |
| Temporary concurrency limit overrides and admin API | gitlab!260640, gitlab!260641 | 19.6 |
| Skip zeroing approval rules that already require no approvals | gitlab!272991 | 19.7 |
| Instance-wide concurrency limit multiplier | gitlab!277261 (environment variable, backport proposed), gitlab!276877 (application setting) | Not merged |
Related bugs:
- gitlab#599018:
SyncPolicyWorkerstatement 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.
Past incidents
Section titled “Past incidents”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
catchallshard withSyncProjectPolicyWorkerjobs. - production#22432: a policy update ran more than 10,000 concurrent
SyncProjectPolicyWorkerjobs, 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 takenfailures each add more jobs. - A worker left deferred after an incident stopped policies from applying for about 11 days before anyone noticed.