fleet icon indicating copy to clipboard operation
fleet copied to clipboard

[top DB writer bottleneck] Improve windows_mdm_responses table writes on Windows MDM hot path

Open getvictor opened this issue 7 months ago • 12 comments

Problem

Every Windows MDM device check-in that acknowledges a previously enqueued command writes a row to windows_mdm_responses, storing the full inbound SyncML envelope in a MEDIUMTEXT column (up to 16 MB; envelopes are typically 2-20 KB and highly compressible). At 10k Windows hosts under load this is the largest cumulative writer in the system: 54,742 inserts in 6 minutes (~150/sec steady state), Σ 8.6 s wall time, roughly 34% of total writer time, p95 540 ms despite being a single-row INSERT (avg 157 µs, so the tail is bimodal). Large rows expand the redo log record, lengthen the Aurora commit-quorum wait, and increase binlog group-commit stall probability.

The data persisted in windows_mdm_responses.raw_response is redundant with the per-command rows already written to windows_mdm_command_results in the same transaction. Specifically:

  • windows_mdm_command_results.status_code captures *status.Data from the SyncML <Status> element (in MDMWindowsSaveResponse in server/datastore/mysql/microsoft_mdm.go). That is the only field of <Status> that carries information not already implicit in the row's FK to windows_mdm_commands (CmdRef equals command_uuid; the Cmd verb is recoverable from raw_command; CmdID and MsgRef are session-counter bookkeeping).
  • windows_mdm_command_results.raw_result captures the per-command <Results> XML segment (also written in MDMWindowsSaveResponse).
  • The full envelope adds only protocol-level bookkeeping (SyncHdr, MsgID, SessionID), exotic <Status> extras (Chal blocks for auth challenges, Item blocks for extended info, which Fleet does not surface in any API), and the ability to regroup "which commands rode the same SyncML message" (no operator-visible feature uses this).

The sole consumer is the read path in GetMDMWindowsCommandResults (server/datastore/mysql/microsoft_mdm.go), which joins windows_mdm_responses and returns wmr.raw_response as the result field on the public API response. Because Fleet batches all pending commands for an enrollment into a single server-to-device SyncML (createResponseSyncML in server/service/microsoft_mdm.go), a device response envelope can ack N commands at once. The current API therefore returns the entire envelope (including sibling commands' statuses and results) every time an admin queries any single command in that batch, which is both noisier than necessary and the only justification for keeping the table.

Impact

At 10k Windows hosts the table is the dominant database writer at roughly 34% of total writer wall time. Each row is unbounded in size and the table grows monotonically with no truncation policy. The bimodal latency tail (p95 540 ms vs. avg 157 µs) indicates large-row inserts are triggering commit-quorum and binlog group-commit stalls that ripple into other writers on the same host. At higher fleet sizes this becomes both an unbounded storage problem and a sustained throughput bottleneck on the Windows MDM check-in path.

Proposed fix

Drop windows_mdm_responses entirely and reconstruct the read-side result field from per-command data already captured in windows_mdm_command_results. (We could also do a smaller stopgap fix and gzip the response. But we recommend to skip the gzip stopgap; ship the structural fix directly.)

  1. Change GetMDMWindowsCommandResults to stop joining windows_mdm_responses and to build result from wmcr.raw_result plus a synthetic <Status> element constructed from wmcr.status_code. The existing status field on the API response already exposes the parsed code, so callers that only consume the numeric status are unaffected. Callers that consumed the raw envelope receive a compact per-command representation in its place.
  2. Remove the INSERT INTO windows_mdm_responses and the response_id column population in MDMWindowsSaveResponse. Make windows_mdm_command_results.response_id nullable in a transitional migration so existing rows remain valid.
  3. After a soak window confirms no remaining reader, drop the response_id column from windows_mdm_command_results and drop the windows_mdm_responses table in a follow-up migration.
  4. If support workflows turn out to depend on full envelope retention for debugging auth challenges or malformed devices, gate envelope retention behind a config flag rather than writing on every check-in.

Evidence

  • load test analysis: 54,742 inserts in 6 min, Σ 8.6 s, p95 540 ms, ~34% of total writer time at 10k hosts
  • Write path: MDMWindowsSaveResponse in server/datastore/mysql/microsoft_mdm.go (INSERT into windows_mdm_responses, then per-command rows into windows_mdm_command_results in the same transaction)
  • Read path: GetMDMWindowsCommandResults in server/datastore/mysql/microsoft_mdm.go (joins windows_mdm_responses and selects wmr.raw_response as the result column)
  • Outbound batching: MDMWindowsGetPendingCommands in server/datastore/mysql/microsoft_mdm.go returns all pending rows; getManagementResponse and createResponseSyncML in server/service/microsoft_mdm.go send them in a single SyncML
  • API exposure: getMDMCommandResults (windows branch) in server/service/mdm.go; MDMCommandResult struct (Result field, json-tagged) in server/fleet/mdm.go
  • SyncMLCmd shape: SyncMLCmd struct in server/fleet/microsoft_mdm.go (CmdID, MsgRef, CmdRef, Cmd, Data, Items, Chal)
  • Schema: server/datastore/mysql/migrations/tables/20231031165350_AddWindowsMDMTables.go

getvictor avatar Apr 25 '26 19:04 getvictor

Victor: This won't limit the data we're saving. Right now, we're effectively saving the data twice, so this would focus the data we're saving to reduce resource consumption.

lukeheath avatar Apr 27 '26 14:04 lukeheath

This is related to current WIP bug fix: https://github.com/fleetdm/fleet/issues/44170

getvictor avatar Apr 28 '26 15:04 getvictor

@marko-lisica We will be modifying the API response slightly here if we drop the raw response. We won't have access to <SyncHdr> — SessionID, MsgID, Source/Target device URIs <Status><CmdID> and <MsgRef> — session-counter bookkeeping <Status><Items> — extended error info <Status><Chal> — auth challenge blocks The grouping of which commands were acked in the same SyncML message

More explicitly after the change, that opaque "raw response" blob would shrink from entire envelope to per-command fragment with those fields excluded.

ksykulev avatar Apr 30 '26 19:04 ksykulev

@marko-lisica We will be modifying the API response slightly here if we drop the raw response. We won't have access to <SyncHdr> — SessionID, MsgID, Source/Target device URIs <Status><CmdID> and <MsgRef> — session-counter bookkeeping <Status><Items> — extended error info <Status><Chal> — auth challenge blocks The grouping of which commands were acked in the same SyncML message

More explicitly after the change, that opaque "raw response" blob would shrink from entire envelope to per-command fragment with those fields excluded.

Hey @ksykulev, I'm having a hard time to imagine what it would look like for the user. Can you provide an example? If you add a Windows configuration profile with several elements, what does the /commands API return today, and what will it return after this change?

marko-lisica avatar May 01 '26 11:05 marko-lisica

@marko-lisica So when you hit the api GET /api/latest/fleet/commands/results?command_uuid=cmd-uuid-get-swv the server responds with

{
  "results": [
    {
      "host_uuid": "...",
      "command_uuid": "...",
      "status": "200",
      "updated_at": "...",
      "request_type": "...",
      "result": "<base64-encoded>",
      "hostname": "...",
      "payload": "<base64-encoded>"
    }
  ]
}

where result and payload are base64 encoded json.

Given the sample response for microsoft https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-mdm/71a45e87-4c0a-43bc-b76f-b427ac8322be

The result key would look like:

<SyncML xmlns="SYNCML:SYNCML1.2">
  <SyncHdr>
    <VerDTD>1.2</VerDTD>
    <VerProto>DM/1.2</VerProto>
    <SessionID>1</SessionID>
    <MsgID>2</MsgID>
    <Target><LocURI>https://contoso.com/management-server</LocURI></Target>
    <Source><LocURI>{unique device id}</LocURI></Source>
  </SyncHdr>
  <SyncBody>
    <Status>
      <CmdID>1</CmdID><MsgRef>1</MsgRef><CmdRef>0</CmdRef>
      <Cmd>SyncHdr</Cmd><Data>200</Data>
    </Status>
    <Status>
      <CmdID>2</CmdID><MsgRef>1</MsgRef><CmdRef>cmd-uuid-get-swv</CmdRef>
      <Cmd>Get</Cmd><Data>200</Data>
    </Status>
    <Status>
      <CmdID>3</CmdID><MsgRef>1</MsgRef><CmdRef>cmd-uuid-get-hwv</CmdRef>
      <Cmd>Get</Cmd><Data>200</Data>
    </Status>
    <Results>
      <CmdID>4</CmdID><MsgRef>1</MsgRef><CmdRef>cmd-uuid-get-swv</CmdRef><Cmd>Get</Cmd>
      <Item>
        <Source><LocURI>./DevDetail/SwV</LocURI></Source>
        <Meta><Format xmlns="syncml:metinf">chr</Format></Meta>
        <Data>10.0.19045.3803</Data>
      </Item>
    </Results>
    <Results>
      <CmdID>5</CmdID><MsgRef>1</MsgRef><CmdRef>cmd-uuid-get-hwv</CmdRef><Cmd>Get</Cmd>
      <Item>
        <Source><LocURI>./DevDetail/HwV</LocURI></Source>
        <Data>Surface Pro 9</Data>
      </Item>
    </Results>
    <Final />
  </SyncBody>
</SyncML>

After this change it would look like:

<Results>
  <CmdID>4</CmdID><MsgRef>1</MsgRef><CmdRef>cmd-uuid-get-swv</CmdRef><Cmd>Get</Cmd>
  <Item>
    <Source><LocURI>./DevDetail/SwV</LocURI></Source>
    <Meta><Format xmlns="syncml:metinf">chr</Format></Meta>
    <Data>10.0.19045.3803</Data>
  </Item>
</Results>

ksykulev avatar May 02 '26 00:05 ksykulev

@ksykulev We shouldn't update these responses in this way. The fleet's core value is transparency, and we want to present raw responses for every platform. This allows users to troubleshoot issues, and possibly do automations.

marko-lisica avatar May 04 '26 15:05 marko-lisica

Victor: A simpler alternative is to simply gzip the response. Noah: I will prioritize digging into this to understanding the IT Admin experience and decide what we can do here.

lukeheath avatar May 18 '26 14:05 lukeheath

Note: In my 2026/06/05 loadtest, this is the top DB writer query when transferring 30K hosts between 2 teams that each have 40 Windows profiles.

getvictor avatar Jun 05 '26 14:06 getvictor

Hey @getvictor, assuming this doesn't impact the IT admin experience at all, let's go ahead with the gzip solution.

melpike avatar Jun 08 '26 19:06 melpike

Windows MDM load test — 4.89.0 RC sign-off

Environment: 50k Windows MDM hosts enrolled on the 80k-host reference architecture. Aurora MySQL 8.0 (db.r6g.2xlarge writer + 2 readers), Redis, 20 Fleet server containers. Full profile lifecycle exercised per the Windows MDM load test plan.

What was exercised (in order)

  1. Baseline — 50k hosts enrolled, steady-state check-ins, no profiles.
  2. Apply 100 profiles (batch endpoint) → full install fan-out across 50k hosts.
  3. Swap attempt aborted (test-data misconfig on my side — see #49002 below).
  4. Delete all 100 profiles (batch endpoint, empty set).
  5. Re-apply 100 profiles.
  6. Swap the 100 profiles for a different, disjoint set of 100 (replace path: remove 100 + install 100).
  7. Transfer all hosts to a second team carrying a different 100-profile set, in 10k-host batches (async removal + install churn).

Metrics captured at each step in tools/loadtest/metrics/runs/489windows-2/ (timestamped JSON + synopsis; first snapshot is the enrolled-only baseline).

Cross-cutting health (all 7 windows, baseline → transfers)

  • Fleet application errors: 0 in every window.
  • ALB: 0 × 5xx, latency 0s throughout (peak sustained load 100.9M requests / 76 GB over the 2h transfer window).
  • RDS writer never saturated: CPU 22.9% (baseline) → peak 55.5%; InsertLatency peak 7.82 ms; FreeMem steady ~14.4 GB; cache hit ~100%; disk grew 20 → 53 GB across the whole run (all tables).
  • Readers ≤ 60% CPU, replica lag ~8 ms, cache hit ~100%.
  • Redis: 0 evictions, connections peak 196.
  • Containers: 0 abnormal stops.
  • Only threshold trip: RDS Writer Deadlocks = 0.02 (a fractional per-window average — i.e. an occasional single deadlock) during the heaviest profile-batch fan-out windows. It cleared to 0 in the next window each time and produced zero Fleet errors and zero 5xx. Read as expected transient row-lock contention under batch fan-out, not a regression.

Per-issue results

#44629 — IsHostConnectedToFleetMDM 3-table JOIN on every orbit check-in ✅ PASS Fixed by PR #48375 (44629-optimize-orbit-mdm-connection-check), which derives connection state from the already-loaded GetHostMDM data. Across all 7 windows the 3-table enrollment JOIN (mdm_windows_enrollments ⋈ hosts ⋈ host_mdm) never appears in the top-5 reader queries; the top reader query is the single GetHostMDM SELECT it now derives from. With 50k hosts checking in, reader CPU stayed ≤ 60%. The hot-path query is gone.

#44188 — windows_mdm_responses write pressure on the check-in hot path ✅ PASS (mitigated) Shipped as the gzip stopgap (44188-compress-windows-mdm-responses, #48320) — envelopes now stored compressed in raw_response_gz — not the recommended structural table drop. The table remains the #2 writer (load 0.52–0.83 across profile windows), but with compression the writer never saturated (CPU ≤ 55.5%, InsertLatency peak 7.82 ms vs. the pre-fix p95 540 ms on the uncompressed MEDIUMTEXT), with no commit-quorum/binlog-stall symptoms (latency 0s, 0 × 5xx). Acceptable at 50k. Recommend keeping the issue open for the structural drop as future work; it is not a 4.89 blocker.

#45635 — host-finding query dominates profile reconciliation ✅ PASS Fixed by the batched reconciler + per-host-reconcile-on-enroll work (45635-windows-batched-reconciler, 45635-windows-per-host-reconcile-on-enroll). The reconciler kept pace through apply, delete, re-apply, swap, and 10k-batch transfers — each fan-out drained without a growing backlog or error spike. The pre-fix failure mode (27.9s P99 host-finding query at 15 profiles / 30k, exceeding the 30s tick at 30 profiles) did not recur at 100 profiles / 50k hosts.

#46993 — batch-set endpoint times out on large removals ✅ PASS Fixed by async batch removal (46993-windows-batch-remove-async) — definitions are tombstoned into mdm_windows_configuration_profiles_pending_delete (migration 20260702013055) and the cron drains the <Delete> fan-out, exactly the decoupling the issue proposed. The delete-all of 100 profiles across 50k hosts returned successfully instead of the client-timeout/rollback documented at 30k/40 profiles; the swap (remove 100 + install 100) and the 10k-batch team transfers (the issue's documented async workaround) also completed cleanly.

Verdict

All four issues pass at 50k Windows hosts on 80k-host infra across the full profile lifecycle. #44629, #45635, #46993 are resolved by their 4.89 fixes; #44188 is acceptably mitigated (suggest keeping open for the structural fix).

Issues uncovered during this run

  • #48996 — OS Settings tab (15+s) and hosts-list page (1+ min) load slowly with 100 profiles on 50k hosts. Logged separately. Hard to classify as a regression: earlier branches can't be tested at 100 profiles (100-profile batch modify/timeout limits pre-fix), so there's no clean baseline to compare against.
  • #49002 — Replacing profiles with a differently-named set that reuses the old set's LocURIs leaves the old profiles stuck install/verified on hosts (200 shown instead of 100). Triggered by a test-data artifact (my generator reused LocURIs; since fixed), so low real-world likelihood, but it exposes a real removal/state edge case. This was the "swap fail" in step 3 above.

AndreyKizimenko avatar Jul 09 '26 04:07 AndreyKizimenko

Image

AndreyKizimenko avatar Jul 09 '26 04:07 AndreyKizimenko

In the cloud city, Redundant data takes flight. Fleet now sails more light.

Windows MDM path, Unburdened, soars above. Swifter in its wrath.

Streamlined data flows, Fleet users find ease and peace. Bottlenecks now cease.

fleet-release avatar Jul 15 '26 18:07 fleet-release