Draft: Share one frozen application settings snapshot per process
What does this MR do and why?
Every request, Sidekiq job and RSpec example builds its own copy of the ApplicationSetting record. The first
Gitlab::CurrentSettings read in a request goes through CacheableAttributes.cached, and the
Gitlab::ProcessMemoryCache read behind it Marshal.loads the whole ~1,000-attribute record, which costs about
2.4 ms and 4,600 objects per request. In specs, ApplicationSetting.build_from_defaults rebuilds the record for every
example.
This MR implements the design from note_4276322613. It is an alternative to !270980 (frozen AR record in the process cache) and !271876 (spec-side rebuild).
This MR is stacked on !272918 (merged), which adds Gitlab::CurrentSettings.writable_application_settings, .update and
.update! and moves the settings writers to them. Until !272918 (merged) merges, the diff here shows both MRs; the commits
of this MR are the last four.
ApplicationSetting#to_materialized_application_settingsbuilds aGitlab::MaterializedApplicationSettings, a frozenDataobject whose class is generated fromApplicationSetting.attribute_names. Values are deep-frozen, and encrypted attributes are decrypted, at build time. Readers and AR-style predicates are generated, andApplicationSettingImplementationruns on top of them, as it already does onGitlab::FakeApplicationSettings. EE methods that only read attributes (EE::Gitlab::MaterializedApplicationSettings::SHARED_METHODS) are copied onto it.- Any other public
ApplicationSettingmethod is delegated toGitlab::CurrentSettings.writable_application_settings. That is the per-request AR record, the same objectcurrent_application_settingsreturns onmaster. Writers (update!, setters,save,reset,!methods) raiseFrozenErrorand namewritable_application_settings. Gitlab::CurrentSettings.materialized_application_settingsholds one snapshot per process. It expires after the sameapplication_settings_cache_secondsTTL,ApplicationSetting#cache!publishes a new one, andApplicationSetting.expiredrops it.current_application_settingsreturns the snapshot when the flag is on.- Writers that called
update*or setters oncurrent_application_settingsmoved towritable_application_settingsin !272918 (merged). This MR moves the rest that the frozen snapshot breaks: the twomarkdown_fieldviews, the EEinvalidate_elasticsearch_indexes_cache*!calls,SecretsManagement::InstanceEnrollment.fallback_settings, and spec writers and stubs. stub_application_settingstores its overrides in the fetcher, which publishessnapshot.with_overrides(...). Examples therefore share one frozen defaults snapshot instead of rebuilding the record. Specs that stubbedcurrent_application_settingsdirectly (RSpec cannot proxy a frozen object) now usestub_application_setting. The defaults snapshot leaves outTime.currentdefaults, which differ on every call and would rebuild it per example. Specs that stubbed EE-prepended predicates withallow_any_instance_of(ApplicationSetting)now usestub_ee_application_setting.- The snapshot class is
Gitlab::MaterializedApplicationSettings::Snapshot. Its policy,Gitlab::MaterializedApplicationSettingsPolicy, subclassesApplicationSettingPolicy, socan?(user, :..., Gitlab::CurrentSettings.current_application_settings)keeps the same rules. - With the flag on,
Gitlab::CurrentSettings.current_application_settings?(used byGitlab.maintenance_mode?) returns true once a snapshot is published, without loading the settings record.
The change is behind the materialized_application_settings feature flag (gitlab_com_derisk, off by default),
checked with Feature.current_request and memoized per request. With the flag off, current_application_settings
returns the same object as on master.
Related to #640053.
Measurements
In-process, test database, bin/rails runner: a request store with 6 Gitlab::CurrentSettings reads, median of
5 × 2,000 iterations.
| Per request | Flag off (master path) |
Flag on | Change |
|---|---|---|---|
| time | 2,897 µs | 85 µs | −97% |
| allocations | 3,446 | 236 | −3,210 |
With the flag on, most of the remaining cost is the Feature.enabled? check. Building a snapshot takes 1.1 ms; the
first build in a process takes 8.9 ms, including the class generation. It runs once per process and TTL.
Reading 21 settings takes 2.5 µs on the snapshot and 7.6 µs on the AR record.
Per RSpec example (body only, median of 140 examples, IN_MEMORY_APPLICATION_SETTINGS=true):
| Per example | Flag off | Flag on | Change |
|---|---|---|---|
| read settings | 3,974 µs / 4,775 objects | 366 µs / 673 objects | −91% / −4,102 |
stub_application_setting + read |
5,122 µs / 6,451 objects | 1,609 µs / 2,308 objects | −69% / −4,143 |
The allocation counts are deterministic; the timings come from a laptop and are noisy. Request-level numbers from the seeded CNG instance are still to come.
Testing
bundle exec rspec spec/lib/gitlab/materialized_application_settings_spec.rb spec/lib/gitlab/current_settings_spec.rbThe first spec checks that every generated member and predicate returns the same value as the record, that values
are deep-frozen, and that writes raise FrozenError. The second checks that one frozen object is shared across
requests, runs no queries after the first read, is replaced after the TTL and after a write, and that the flag-off
path returns the AR record.
What to check by hand with the flag on: admin settings pages and PUT /api/v4/application/settings (writers), and
any feature that changes a setting outside ApplicationSettings::UpdateService (licenses, Duo, Elasticsearch
indexing, secrets management enrollment). A missed writer raises FrozenError.
Open questions
- Methods the snapshot cannot run (associations, license-dependent EE readers, the lazy token readers that persist a
missing token) are delegated to the per-request AR record, which still pays for the
Marshal.loadcopy the first time one is called in a request. Would you rather have the snapshot raise on them, which needs more call sites moved towritable_application_settings? - The 42 direct
ApplicationSetting.currentreaders are unchanged. Should they move in a follow-up?
Production monitoring
I do not have access to GitLab.com logs. These are queries for someone who does to run in Kibana
(log.gprd.gitlab.net) during the rollout. While the flag is partially enabled, compare requests with the flag on
against requests with it off in the same window, splitting by json.feature_flag_states
(materialized_application_settings:1 against materialized_application_settings:0). Check the field names against
the index pattern before running them.
Expected improvement, index pubsub-rails-inf-gprd*: median and p95 of json.mem_objects and json.cpu_s should
drop by about 3,000–4,000 objects and 2–3 ms per request for the same endpoint:
json.meta.caller_id : "GET /api/:version/version" and json.feature_flag_states : "materialized_application_settings:1"
json.meta.caller_id : "GET /api/:version/version" and json.feature_flag_states : "materialized_application_settings:0"Regressions to watch: a missed writer raises FrozenError, and a stale snapshot shows as a settings change that takes
more than one TTL to apply.
json.exception.class : "FrozenError"
json.exception.message : *MaterializedApplicationSettings*The same FrozenError query on pubsub-sidekiq-inf-gprd* covers jobs. Any hit means a writer still goes through
current_application_settings.
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist.
Generated by GitLab Performance Optimisation