Skip to content

feat: export workspace last used time to Prometheus - #31346

Merged
EhabY merged 5 commits into
mainfrom
feat/workspace-last-used-metric
Nov 11, 2026
Merged

EhabY merged 5 commits into
mainfrom
feat/workspace-last-used-metric

Conversation

@EhabY

@EhabY EhabY commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Adds an opt-in coderd_workspace_last_used_timestamp_seconds{organization_name, template_name, workspace_owner, workspace_name, workspace_id} gauge. It reports workspaces.last_used_at, the value the dormancy threshold measures from.

Closes CLIENT-1065. Follow-up to a comment on CLIENT-1034 (#29940), which only covers per-template app usage time.

Changes

  • --prometheus-collect-workspace-stats / CODER_PROMETHEUS_COLLECT_WORKSPACE_STATS, default false.
  • A new prometheusmetrics.WorkspaceStats collector, which runs only when the flag is set and refreshes once a minute on a quartz ticker.
  • A new GetWorkspaceLastUsedForMetrics query, with a dbauthz entry.
  • A "Workspace last used time" docs section: series and cost, what counts as use, accuracy, and an example query.

Decisions

Question Decision Why
On by default? No, opt-in The query is cheap (about 9 ms at 20k workspaces). The cost is one series per workspace per replica in the customer's TSDB. This matches --prometheus-collect-agent-stats and --prometheus-collect-db-metrics.
Extend Workspaces() or add a collector? A separate collector A bool on Workspaces() is control coupling. The separate query skips the latest-build lookup, so it costs about a tenth of the shared scan, and Workspaces() stays unchanged.
Flag name collect-workspace-stats It names a group, so future per-workspace metrics can join without a new flag. It mirrors collect-agent-stats and the workspacestats package. "Workspace usage" is already the name of an experiment.
Owner label workspace_owner Matches coderd_workspace_latest_build_status.
Series identity Add workspace_id Without it, a workspace that reuses a deleted workspace's name continues the old series and mixes two histories. The series count doesn't change (still one per workspace).
Which workspaces All non-deleted workspaces of non-deleted users, including stopped and unclaimed prebuilds Gives a complete picture. Prebuilds group under workspace_owner="prebuilds". A deleted user's username can be reused, so their rows are excluded rather than colliding with a live user's series.
Size numbers in docs Not included Measured sizes go stale. The docs state the series count per replica.

Accuracy

With default settings, the value trails real use by up to about 2.5 minutes plus the scrape interval:

  • The agent reports activity every 30 s.
  • Activity is saved every 60 s, with the time of the save, not of the activity.
  • The collector refreshes every 60 s.

"Use" means traffic on any agent connection, app traffic through Coder, or the default coder ssh / coder port-forward heartbeat (once a minute, even when idle). The value is also set to the current time on creation, on activating a dormant workspace, and when a template admin resets inactivity.

Benchmarks and verification

Postgres 17, 5,000 users, 50 templates, 2 builds per workspace. pgbench, 1 client:

Workspaces GetWorkspaceLastUsedForMetrics GetWorkspacesForWorkspaceMetrics (existing)
20,000 9.4 ms 86 ms
50,000 23 ms 231 ms

Gauge with 4 labels (GOMAXPROCS=12):

Series Refill per tick Retained heap Scrape (Gather + encode) Uncompressed size
20,000 14 ms 13.4 MiB 26 ms 3.3 MB
50,000 35 ms 33 MiB 127 ms 8.4 MB
100,000 69 ms 66 MiB 360 ms 16.7 MB

coder server against 20,000 workspaces:

  • With the flag: 20,000 series on the first scrape.
  • Without the flag: none.

TestWorkspaceStats uses a mock clock. It covers running, stopped and prebuilt workspaces, excludes deleted workspaces and workspaces of deleted users, checks that a recreated workspace with the same name gets a new series, and checks that a last_used_at update and a deletion are picked up on the next tick. It waits for the first collect by trapping the TickerFunc call. It fails on a mutated value, a skipped commit, and a skipped first collect, and passes 300 times under -race -cpu 1,2,8.

make pre-commit passes. The doc-check self-review found no remaining blocking findings.

Possible follow-up: incremental refresh

Each tick reloads every live workspace. On Postgres 17 with 147k live workspaces (98k users, 300 templates), the full query takes about 183 ms end to end for 14 MB of rows. The plan is already the cheapest available. Returning epoch seconds or resolving names in Go did not help meaningfully.

Loading only rows whose last_used_at moved since the previous tick:

Workspaces used per minute Rows Changed rows only Full query
1% 1,454 17 ms 183 ms
5% 7,070 34 ms 183 ms
20% 28,782 52 ms 183 ms

It still needs a periodic full refresh to drop deleted workspaces and pick up renames and deleted owners. With one every 10 ticks, the average cost per tick is about 2.5x to 6x lower. It also needs an overlapping time window for late saves from other replicas, and the gauge would need per-series updates instead of the full rebuild CachedGaugeVec does on each commit. Not worth the complexity at this scale; worth revisiting if a large deployment shows the cost matters. An index on last_used_at was rejected: it barely helped, and it would slow the table's most frequent update.


Generated by Coder Agents on behalf of @EhabY.

@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Docs preview

Check off each page once it's been reviewed. If a page changes in a later push, its checkbox clears automatically so it gets a fresh look. Pages not yet wired into the docs navigation aren't listed here.

@linear-code

linear-code Bot commented Oct 27, 2026

Copy link
Copy Markdown

CLIENT-1065

@EhabY
EhabY force-pushed the feat/workspace-last-used-metric branch from 5241b0b to 1f50af0 Compare October 27, 2026 14:08
@EhabY
EhabY marked this pull request as ready for review October 27, 2026 14:10
@EhabY
EhabY requested a review from nickvigilante as a code owner October 27, 2026 14:10
@EhabY
EhabY force-pushed the feat/workspace-last-used-metric branch from 1f50af0 to 90104b5 Compare October 27, 2026 14:19

@nickvigilante nickvigilante left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docs LGTM

@EhabY
EhabY requested a review from code-asher October 28, 2026 12:46
@EhabY
EhabY requested a review from jeremyruppel November 9, 2026 21:22

@jeremyruppel jeremyruppel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of small simplifications to WorkspaceStats. None of these are blocking.

I know the file's other collectors use a goroutine with a select loop. I think using TickerFunc here is the right choice: newer code in coderd uses it (metricscache, notifications, agentapi, cryptokeys), and it lets TestWorkspaceStats use Advance().MustWait() instead of polling the way TestUsers does. So these comments only tighten up how TickerFunc is used.


Generated by Coder Agents on behalf of @jeremyruppel.

@EhabY
EhabY removed the request for review from code-asher November 10, 2026 13:11
@EhabY
EhabY force-pushed the feat/workspace-last-used-metric branch from 6ac22d3 to 994fd25 Compare November 10, 2026 14:02
@EhabY
EhabY temporarily deployed to main November 10, 2026 14:02 — with GitHub Actions Inactive
@EhabY
EhabY requested a review from jeremyruppel November 10, 2026 14:03
Comment thread docs/admin/integrations/prometheus.md Resolved
@EhabY
EhabY temporarily deployed to main November 10, 2026 14:08 — with GitHub Actions Inactive
@EhabY
EhabY temporarily deployed to main November 10, 2026 14:26 — with GitHub Actions Inactive
@EhabY
EhabY temporarily deployed to main November 10, 2026 14:37 — with GitHub Actions Inactive
Adds an opt-in coderd_workspace_last_used_timestamp_seconds gauge behind
--prometheus-collect-workspace-stats, collected by a separate
WorkspaceStats collector from a new GetWorkspaceLastUsedForMetrics query.

Closes CLIENT-1065.
Add a workspace_id label so a workspace that reuses a deleted
workspace's name gets its own series, and skip workspaces owned by
deleted users, whose usernames can be reused.
…ckground

Run the first collect in the collector goroutine so server startup does
not wait on the query, pass collect straight to TickerFunc, and drop the
unreachable ticker error branch.
The new-code errcheck config rejects blank-discarded errors, so collect
no longer returns an error and the ticker's Wait result is checked.
@EhabY
EhabY force-pushed the feat/workspace-last-used-metric branch from 5516c95 to 1e00035 Compare November 11, 2026 14:41
@EhabY
EhabY temporarily deployed to main November 11, 2026 14:42 — with GitHub Actions Inactive
@EhabY
EhabY enabled auto-merge (squash) November 11, 2026 14:52
@EhabY
EhabY merged commit 1126533 into main Nov 11, 2026
30 of 31 checks passed
@EhabY
EhabY deleted the feat/workspace-last-used-metric branch November 11, 2026 15:02
@EhabY
EhabY temporarily deployed to main November 11, 2026 15:02 — with GitHub Actions Inactive
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 11, 2026

This branch was previously deployed

1 inactive deployment
main — 1e000358 Deployed Nov 11, 2026 by EhabY via cla #254458
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants