Draft: Share one application settings snapshot per process
What does this MR do and why?
Every Rails request reads ApplicationSetting at least once — usually in the rate-limit middleware, long before any
controller code runs. The record is already cached per process in Gitlab::ProcessMemoryCache, but that cache is an
ActiveSupport::Cache::MemoryStore, and MemoryStore's default DupCoder runs Marshal.load on every read. So
the cache saves the Redis round trip and the SQL query, but each request still builds its own private copy of a
982-attribute record: ~2.4 ms and ~5,300 allocations, on every request, in every Rails process (web, API, GraphQL,
Sidekiq).
This MR stops making the private copy. Gitlab::ProcessMemoryCache gains a second store built with coder: nil,
which skips DupCoder so a read returns the stored object itself, and ApplicationSetting.cache_backend points at it.
TTL, delete and the after_commit expiry are untouched, so a settings change becomes visible exactly as fast as
before.
The new store is behind the application_settings_cache_frozen feature flag (gitlab_com_derisk, off by default,
rollout issue #640789), scoped to the request with Feature.current_request. With the flag off, settings use the old
Marshal-copy cache_backend and the record is not frozen.
Handing the same object to every request and every Puma thread only works if nothing writes to it, so
ApplicationSetting#cache! publishes a Marshal copy of the record, fully materialised, readonly! and freezed,
and every writer is routed to an uncached record instead. The record cache! is called on stays writable, as on
master. Most writers already went through Gitlab::CurrentSettings.update(!), now defined explicitly rather than
reaching the record via method_missing. Every caller of ApplicationSettings::UpdateService passes a writable record
(Gitlab::CurrentSettings.writable_application_settings, or current_without_cache as in the admin settings
controller and API::Settings, which are unchanged), and the service raises FrozenError when given a frozen one.
The remaining direct writers ask for a writable record too. With the flag off, writable_application_settings returns
the cached record itself, as on master.
Why freeze and not just readonly!: ActiveRecord::ReadOnlyRecord is raised at save time, after
assign_attributes has already written into @attributes. A missed writer would have corrupted the shared record for
every other thread and only then raised. freeze fails at the assignment instead. AR's freeze freezes @attributes
only, so reads, changed?, attributes and association reads all still work.
Related to #640053.
Measurements
tools/perf-request compare -n 40 -w 5 against a seeded CNG instance (v19.3.0), patched webservice vs baseline
webservice, requests interleaved, medians:
| Request | mem_objects |
cpu_s |
wall_s |
|---|---|---|---|
GET /api/v4/version |
22,504 → 18,277 (-4,227, -18.8%) | 25.7 → 19.0 ms (-26.2%) | 31.2 → 24.5 ms (-21.6%) |
GET /users/sign_in (302) |
12,941 → 8,726 (-4,215, -32.6%) | 14.6 → 11.1 ms (-23.8%) | 19.7 → 15.8 ms (-19.9%) |
GET /api/v4/projects/11 |
95,167 → 90,939 (-4,228, -4.4%) | 100.6 → 95.2 ms (-5.4%) | 116.7 → 110.9 ms (-5.0%) |
GET /perf/big/-/issues/1.json |
85,218 → 80,991 (-4,227, -5.0%) | 96.3 → 88.1 ms (-8.4%) | 110.6 → 100.6 ms (-9.1%) |
The allocation counts are deterministic and are the number to trust: the drop is the same ~4,200 objects on all four
paths, which is what a fixed per-request cost looks like. The cpu_s and wall_s columns are medians from a local
machine under load and are noisy — read them as "consistent with the allocation drop", not as precise figures. The last
row in particular ran while the machine was at load 5.2, so treat its timings as indicative only. SQL and Redis counts
are unchanged on all four paths.
In-process microbenchmark of the settings read itself (982 attributes, 300 iterations, GC disabled during timing):
| Per-request settings read | Before | After |
|---|---|---|
| time | 2,389–2,507 µs | 5.3–9.0 µs |
| allocations | 5,289 | 15 |
Two caveats on the A/B, in the interest of not overclaiming:
- The percentages are from a local instance with a tiny seeded dataset, not GitLab.com. The absolute ~4.2k allocations and ~2.4 ms are the per-request constant; the percentage shrinks as the rest of the request grows.
- The patched image could not be built from this commit directly (the branch does not rebase onto the v19.3.0 tag the
CNG image uses). It was built from this MR's production diff — 30 files — minus four that do not exist or have no
settings write in v19.3.0, with
lib/banzai/renderer.rbadapted by hand because v19.3.0 callsrefresh_markdown_cache!directly. None of the omissions is on the measured request paths.
An alternative that keeps the per-request copy but caches the raw attribute hash and instantiates it was measured
first and rejected: it is time-neutral (2.45 ms → 2.38 ms), because instantiate runs 63 jsonb_accessor
after_initialize callbacks that cost as much as the unmarshalling it saves. Only not making a copy removes the
cost.
Queries
No SQL is added or changed. The only query-shape change is that Gitlab::CurrentSettings.update(!) now drops the
:current_application_settings request-store entry after a write, so the next read in that same request costs one
extra SELECT. There are 16 such call sites and none is on a request-serving path.
Testing
bundle exec rspec spec/models/application_setting_spec.rb -e 'process cache' -e 'cache_frozen?'
bundle exec rspec spec/lib/authn/token_field/base_spec.rbThe cache_frozen? examples cover the flag: it is checked once per request, it returns false to a nested read,
and it returns false outside a request store. They also check that with the flag off reads return a writable copy.
Five new examples. Two fail without the production change: object identity across two cache reads, and that a write to
the cached record raises FrozenError without changing the value. The other three guard that the snapshot is fully
materialised before publication and that the two writer funnels return a writable record.
Also worth running: spec/models/concerns/cacheable_attributes_spec.rb,
spec/services/application_settings/update_service_spec.rb, spec/lib/gitlab/current_settings_spec.rb,
spec/controllers/admin/application_settings_controller_spec.rb, ee/spec/requests/api/settings_spec.rb.
What a reviewer should check by hand, because this is where the change can break:
- Settings writes. Change something in Admin → Settings, save, and confirm the new value is visible
immediately and no
FrozenErrororActiveRecord::ReadOnlyRecordappears in the log. Same viaPUT /api/v4/application/settings. - A Sidekiq-side settings write. I could not exercise this (see below) and it is the biggest gap.
/helpand the signup confirmation page, which renderApplicationSettingmarkdown fields.
What I did exercise end to end on the patched instance: two PUT /api/v4/application/settings
(after_sign_up_text) returned 200 with the new value visible on the next read; /help, /explore and
/users/sign_in rendered; no FrozenError, ActiveRecord::ReadOnlyRecord or 5xx in the patched logs. Values were
reverted afterwards.
What I did not exercise: Sidekiq (the CNG Sidekiq container runs the unpatched baseline image), the admin settings form, and the EE writers.
Why the local spec run is weaker coverage than it looks, and a reason to watch the full pipeline rather than my
runs: spec/spec_helper.rb sets IN_MEMORY_APPLICATION_SETTINGS=true for the whole suite, so
Gitlab::CurrentSettings.current_application_settings returns an unfrozen, unpersisted build_from_defaults record
and never touches the process cache. A writer reached through Gitlab::CurrentSettings therefore does not raise in
specs. A writer reached through ApplicationSetting.current does — that is how the lets_encrypt, admin-controller
and License writers were found. The static sweep below is what covers the other half. Specs tagged
:frozen_application_settings do run against the frozen snapshot through Gitlab::CurrentSettings (Web IDE and
workspaces OAuth application writers, the Duo OAuth service lock race, and the Gitlab::CurrentSettings writers), but
the rest of the suite does not.
Risks
- A missed writer. The failure mode is loud (
FrozenErrorat assignment) rather than silent corruption, which is deliberate — but it is still a production exception. I swept all 172 files that read the cached record plus the spec failures; that found 13 writers beyond the obvious two funnels, mostly hidden behind a privateapplication_settingshelper or a local variable rather than a literalcurrent_application_settings.update. All are routed in this MR. Two were only caught becausereload/resetreplace@attributesand so silently un-freeze the record:Gitlab::LetsEncrypt::Client(with_lockreloads) andSecretsManagement::InstanceEnrollment(current_settings.resetafter anupdate_all). The second is the one case that failed quietly, and is why the snapshot carriesreadonly!as well asfreeze. - Associations are per request. AR's
freezefreezes only@attributes, so the fivebelongs_toassociations onApplicationSetting(web_ide_oauth_application,o11y_oauth_application,file_template_project,duo_template_project,workspaces_oauth_application) would otherwise be cached on the shared snapshot for every thread. On a frozen snapshot,association_instance_get/association_instance_set/association_cached?keep them in the request store instead, so each request loads its own association, as it did on its private copy. - Memoised ivars become process-lifetime.
@parsed_grafana_urland@parsed_kroki_urlare pure and idempotent.@default_organization(EE) pins anOrganizations::Organizationfor the cache TTL rather than the request.@latest_cached_markdown_versionpins the phased-rollout roll per process for 60 s instead of per request, which affects only the threecache_markdown_fields onApplicationSetting. - Markdown cache refresh.
Banzai::Renderer.render_fieldrefreshes a stale markdown cache by writing to the record it renders, and two views renderApplicationSettingmarkdown fields (app/views/help/index.html.haml,app/views/devise/confirmations/almost_there.haml). After a markdown cache version bump those pages would have raisedFrozenError, so a frozen record now hands the row toGitlab::MarkdownCache::RefreshWorkerinstead. That worker isdeduplicate :until_executingandidempotent!with a concurrency limit, so a version bump does not turn/helptraffic into one job per request.
Feature flag
application_settings_cache_frozen (gitlab_com_derisk, default_enabled: false), rollout issue #640789.
ApplicationSetting.cache_frozen?checks the flag againstFeature.current_requestonce per request or Sidekiq job. It memoizes the result inGitlab::SafeRequestStore, so.cache_backendand#cache!always agree. The memo is set tofalsebeforeFeature.enabled?runs, so a settings read nested inside the flag check (for example from Redis or database instrumentation) takes the old path instead of recursing.- With the flag off,
.cache_backendreturns the Marshal-copy store and#cache!isreturn super, theCacheableAttributes#cache!frommaster. The writer rerouting and thefrozen?branches only act on a frozen record, so they do nothing then.Authn::TokenField::Base#ensure_token!is unchanged, so the other token models are not affected. The three lazy token readers (runners_registration_token,health_check_access_token,error_tracking_access_token) read the token off the snapshot with no query. Only when it is missing do they callensure_*!, on a writable record fromfind_or_create_without_cache. So they never callensure_*!on the frozen record, and they do not depend on it skipping frozen records. - With the flag on, a cache miss does one extra Marshal round trip to build the copy: +5.4 ms and +7.6k objects
(10.6 ms / 11.6k objects instead of 5.1 ms / 4.0k), once per process every
application_settings_cache_secondsand after each settings change. Cache hits, which is what every request does, do not change. - Outside a request store (Rails console, Rake, boot) the old path is always used, with no flag lookup.
.expiredeletes the key from both process stores, because two requests in one process can be on different sides of a percentage rollout.- The flag check itself costs about 83 µs and 208 objects per request in the test environment, with the flag on or off (in-process, 5 interleaved rounds of 1,000 simulated requests):
| Per-request settings read | Time (median) | Objects |
|---|---|---|
| flag off (Marshal copy) | 2,815.6 µs | 5,511 |
| flag on | 88.9 µs | 226 |
| without the flag check | 6.1 µs | 18 |
The test environment also validates flag definitions on every check, which production does not do.
The CNG measurements above were taken before the flag was added, so they show the flag-on path without that check.
Production monitoring
I do not have access to GitLab.com logs, so these are queries for someone who does to run in Kibana
(log.gprd.gitlab.net) once this is deployed. During the percentage rollout, compare requests with the flag on
against requests with it off in the same window: add json.feature_flag_states: "application_settings_cache_frozen:1"
(or :0) to each query below. Once the flag's milestone has passed its state is no longer logged; then compare
24 hours before against 24 hours after a rollout step. Field names should be checked against the index pattern
before running.
Expected improvement — index pubsub-rails-inf-gprd*. The saving is a per-request constant, so it should show on
any endpoint; pick a cheap one where it is a large fraction:
json.meta.caller_id: "API::API#/api/:version/version"Read the median and p95 of json.mem_objects: expect a drop of roughly 4,000–5,000 objects. This is the
deterministic signal and the one to judge the MR by. Then read the median of json.cpu_s on the same query: expect
roughly -2.4 ms. Locally this was -4,227 objects on this endpoint; the local CPU median moved more than that
(-6.7 ms), which is the noise in a laptop measurement, so judge it by the allocation count.
On API routes json.duration_s starts inside Grape and misses the middleware where the settings read happens, so for
API paths use json.cpu_s, or Workhorse's json.duration_ms in pubsub-workhorse-inf-gprd*:
json.uri: "/api/v4/version" and json.status: 200Also worth a look, since the saving applies to every Rails process:
json.meta.caller_id: "Projects::IssuesController#index"Regressions to watch — these are the behaviours this change can break.
A missed writer raises at assignment time. Any hit here is this MR, index pubsub-rails-inf-gprd*:
json.exception.class: "FrozenError" or json.exception.class: "ActiveRecord::ReadOnlyRecord"Expect zero. A non-zero count names the missed writer in json.exception.message and
json.meta.caller_id, and is a reason to turn the flag off.
The same in Sidekiq, which is the path I could not exercise locally — index pubsub-sidekiq-inf-gprd*:
json.exception.class: "FrozenError" or json.exception.class: "ActiveRecord::ReadOnlyRecord"Settings writes must still succeed. Index pubsub-rails-inf-gprd*:
json.meta.caller_id: "Admin::ApplicationSettingsController#update" and json.status >= 500
json.route: "/api/:version/application/settings" and json.method: "PUT" and json.status >= 400Expect the same rate as before the deploy; a rise means a writer is hitting the frozen record.
The markdown refresh path, in case a version bump starts enqueuing more than expected — index
pubsub-sidekiq-inf-gprd*:
json.class: "Gitlab::MarkdownCache::RefreshWorker"Read the count per hour: deduplication should keep this flat, and a step change after a markdown version bump would
mean the guard in refresh_stale_markdown_cache is enqueuing per request rather than per dedup window.
Finally, settings changes must not take longer to propagate. There is no direct log signal for this; the behavioural check is item 1 in the Testing section.
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist.
Generated by GitLab Performance Optimisation