Clerk Metadata Migrations

Clerk Metadata Migrations #

Classification: Internal-Only

Use this guide to rename, reshape, merge or move keys in the Clerk metadata of organizations or memberships (public or private) that already exist. User metadata is not supported yet: it needs a user subject kind and its list, get and update calls in src/clerk.ts.

The procedure below is numbered. Do the steps in order; each ends with a Done when check. Every step also says what it means for the first migration built this way, chat-tokens (ENG-10048, cleanup in ENG-10052), so you can follow that migration end to end.

Terms #

Term Meaning
Subject One organization or one membership whose metadata the migration reads or writes.
Old key, new key The metadata key being replaced, and the one replacing it.
Dual-read Apps read the new key first and fall back to the old key.
Dual-write Apps write the new key and the old key in the same Clerk update.
Kill switch A Doppler boolean, <FEATURE>_READ_LEGACY, that makes the apps read the old keys only.
The tool tools/clerk-metadata-migrate: runs a migration over every subject, in stages.
Migration id The kebab-case name of one migration, such as chat-tokens. You type it on the command line.
Stage One kind of run: plan, apply, verify, cleanup or restore.

The procedure at a glance #

Step What you do How to undo it
1. Design Write down the new shape and every reader and writer Nothing to undo
2. App change Dual-read, dual-write, kill switch, runtime logs Revert the PR
3. Migration code Write and test the migration in the tool Revert the PR
4. Monitors Create the Datadog monitors (strongly recommended) Delete them
5. Deploy Ship steps 2 and 3 to every service Revert and redeploy
6. Run on dev plan → apply → verify → plan Kill switch, or restore
7. Run on production The same, human-approved Kill switch, or restore
8. Soak At least 7 days of quiet monitors and clean verify runs Kill switch
9. Cleanup Separate ticket: delete the old keys, then remove the fallback code restore from the cleanup backup

Open two tickets before step 1: the migration, and the cleanup, blocked by it.

Chat-tokens: ENG-10048 is the migration, ENG-10052 the cleanup.

Step 1: design #

Write these in the migration ticket before you write code:

  1. The new shape, and an old key → new key table.
  2. Subjects: organizations, memberships, or both.
  3. Public or private. Public metadata reaches the browser in the session token: never put anything secret or internal there, and keep it small, because it makes every session token larger. Clerk also caps the size of metadata.
  4. Values that have no old key. The kill switch can’t roll these back, because there is nothing old to read.
  5. Values that differ by environment. A migration knows which Clerk instance it runs on: test (local and dev) or live (production).
  6. Every writer of the old key: app code, webhooks, scripts, the sales portal, and people editing in the Clerk dashboard. Code writers move to dual-write in step 2. Dashboard edits can’t: until step 9, anyone editing by hand must set both keys. Say so in the ticket and in the team channel.
  7. Every reader, including browser code. Browser code can’t see the kill switch, so compute the value on the server and send the result.

Done when: the ticket has all seven.

Chat-tokens:

  1. Shape and table:

    Subject Old key New key
    Org chat_usage.period_start, .tokens, .updated_at chat_tokens.period.start, .period.used, chat_tokens.updated_at
    Org chat_limits.extra_tokens chat_tokens.free.granted (with used: 0, expires_at: null)
    Org none chat_tokens.topped_up (granted: 0, used: 0, expires_at: null)
    Org none chat_tokens.free.is_enabled, chat_tokens.topped_up.is_enabled
    Membership chat_usage chat_tokens.period, chat_tokens.updated_at
    Membership chat_limits.user_share chat_tokens.share
  2. Subjects: organizations and memberships.

  3. Private metadata only.

  4. No old key: topped-up tokens, every expiry, both is_enabled switches, the free grant a new org gets from CHAT_FREE_TOKENS, each grant’s start, and a member’s use of each balance (chat_tokens.free and .topped_up on the membership: used, start, expires_at, written back by tofu-web). The three sources are counted apart: period.used is the plan’s tokens this period, and each balance’s used is its current grant’s, across periods until it expires. A newer grant (a later start) counts from 0. period.drawn (free, topped_up) is what the period took from each balance, so a lost Redis counter is rebuilt as used + drawn; the older chat_usage.tokens keeps that total. The migration writes no start: tofu-web counts a grant without one as the grant it has counted all along, where a new start would give the org that grant’s use back.

  5. By environment: the switches. On test, free is on and topped-up off; on live, both are off, except that an org with an older extra_tokens grant keeps free tokens on everywhere.

  6. Writers: tofu-web’s hourly usage write-back, the sales portal’s chat edits, bonsapi’s new-org defaults, and the Clerk dashboard. A free-token grant set by hand sets both chat_tokens.free.granted and chat_limits.extra_tokens.

  7. Browser readers: the sales portal’s member share is computed on the server (OrgMember.chatShare).

Step 2: the app change #

One PR, in every app that reads or writes the keys.

  1. Readers: new key first, then the old one.
    • Read the new key field by field. For each field it lacks or that won’t parse, read the old key.
    • When both shapes carry an updated_at, the newer one wins. That covers a writer that hasn’t moved yet.
    • Keep one parser per language, and test every app against one shared fixture file.
  2. Writers: both keys in one update. Then the old keys are never stale when the kill switch is flipped. Clerk deep-merges metadata, and a null value deletes a key, so when a value is removed, remove it from both shapes.
  3. The kill switch. Add <FEATURE>_READ_LEGACY (default false). When it’s true, readers ignore the new key for every field the old keys hold.
    • Rust (bonsapi): a field on AppConfig with deserialize_lenient_flag, applied at startup.
    • tofu-web: an uncached reader in src/env.ts, with its schema in SERVER_ENVIRONMENT_KEYS; the deployment-env test then requires it in the deployment.
    • Deployments: add it with optional: true to each app’s deployment/resources/<app>/deployment.yaml. Not to docker-compose.yml: local development reads it unset, which is false.
    • Doppler: add it as false to every config. Unset also reads as false, but an explicit entry is quicker to find and flip in an incident.
    • The apps read it at startup, so flipping it needs a restart.
  4. Runtime logs. Two warnings, each with a stable event name, the field, and the org and user ids. Never log metadata values.
    • Unreadable: the new key is present but won’t parse, so the reader fell back. It finds a bad write.
    • Drift: both shapes parse and the old one is newer, so a writer skipped the new key. It finds a writer you missed. A few during a deploy are expected.
    • In bonsapi, log through bonsai_utils::event_log. In production only those lines reach Datadog as service:bonsapi; a plain warn! arrives as service:cloudwatch, where no monitor can match it.
  5. Tests: old only, new only, both (including newer-wins), the kill switch in every reader, and dual-write keeping every other key.

Done when: the PR is approved with these tests, and the Doppler key exists in every config.

Chat-tokens:

  • Readers: bonsapi apps/bonsapi/src/service/billing/chat_usage.rs, tofu-web apps/tofu-web/src/server/ai/limits/chat-tokens-metadata.ts, and the sales portal (which gets its figures from bonsapi).
  • Writers: tofu-web’s write-back (usage-store.ts) writes chat_tokens and chat_usage; the sales portal’s free-token, share and reset edits (chat-limits.ts) also write chat_limits and chat_usage.
  • Kill switch: CHAT_TOKENS_READ_LEGACY, in the bonsapi, bonsapi-internal, tofu-web and sales-portal deployments. Leave it false before, during and after the migration. Set it to true only to roll back. While it’s true, new orgs get no free tokens, because their grant lives only in chat_tokens.
  • Logs: tofu-web chat_tokens.unreadable and chat_tokens.legacy_newer, with field, orgId and userId; bonsapi event chat_tokens_unreadable.

Step 3: write the migration #

  1. Create tools/clerk-metadata-migrate/src/migrations/<file>.ts:

    import type { MetadataMigration } from '../types';
    
    export const myMigration: MetadataMigration = {
      id: 'my-migration',
      description: 'old_key into new_key (ENG-XXXX)',
      subjects: ['organization', 'membership'],
      // Every top-level key the migration reads or writes. Each is backed up before a write.
      keys: { private: ['new_key', 'old_key'] },
      plan(subject, context) {
        // A deep-merge patch adding only what new_key lacks, or null when nothing is missing.
        return null;
      },
      verify(subject, context) {
        // [{ code: 'new_key.field_missing', severity: 'error', message: '…' }]
        return [];
      },
      cleanup(subject, context) {
        // { privateMetadata: { old_key: null } }, or null when this subject isn't safe to clean.
        return null;
      },
    };
    

    context.instance is test or live, for a value that differs by environment.

  2. Register it in src/migrations/index.ts, keyed by its id:

    export const MIGRATIONS = {
      [chatTokensMigration.id]: chatTokensMigration,
      [myMigration.id]: myMigration,
    };
    
  3. Follow these rules:

    • The functions are pure. The runner does the reading, backups, writes and logging.
    • plan adds only what the new key lacks, field by field. It never overwrites a value the new key already has, because a live writer may have written it after the old key. So a second apply writes nothing.
    • plan never deletes. Only cleanup deletes.
    • verify returns stable codes, prefixed with the key, such as chat_tokens.period_missing. Monitors and reports group by them.
      • error: an app would read a wrong value, or the old key holds something the new key lacks. It fails the run and blocks cleanup.
      • warning: the shapes disagree, but the apps still read the right value (for example, the newer copy wins). It’s reported only.
    • cleanup decides per subject. Return null when verify finds any issue for that subject, warnings included: an old key that disagrees may be the newer copy.
  4. Test the pure functions, and the runner with memoryClerk from tests/support.ts (an in-memory Clerk with Clerk’s merge rules). Copy tests/chat-tokens.test.ts to start.

    mise run clerk-metadata-migrate-test
    

Done when: the tests pass and the migration is registered.

The migration id #

You choose the id when you write the migration; nothing generates it.

  1. The migration sets it: id: 'my-migration'. The MetadataMigration type in src/types.ts requires it, in kebab-case.
  2. src/migrations/index.ts registers the migration under it: [myMigration.id].
  3. src/cli.ts takes the first argument after -- and looks it up in MIGRATIONS. With no match, it prints the usage line, which lists every registered id.

So you type the id, not the name of the export: myMigration is only a TypeScript name.

The id is also on every log line as @migration, in each report’s file name and summary, in each checkpoint and in each backup line. Don’t rename it after a run: a checkpoint resumes only under the same id, cleanup accepts only a verify report with the same id, and restore replays only backup lines with it.

Chat-tokens: src/migrations/chat-tokens.ts exports chatTokensMigration with id: 'chat-tokens'. It declares the keys chat_tokens, chat_usage and chat_limits (private), so each is backed up before a write.

  • plan, for each subject, writes only the parts of chat_tokens that are missing, plus v: 1:
    • period and updated_at, from a readable chat_usage (v: 1).
    • Orgs: free.granted from chat_limits.extra_tokens, with used: 0 and expires_at: null; topped_up with granted: 0, used: 0, expires_at: null; and each is_enabled that is unset, as decided per instance (free stays on wherever an extra_tokens grant exists).
    • Memberships: share from chat_limits.user_share (0 to 1).
  • verify codes:
    • Errors: chat_tokens.not_an_object, .period_malformed, .updated_at_missing, .period_drawn_malformed, .free_malformed (also a non-numeric start, on orgs and memberships), .topped_up_malformed, .free_switch_malformed, .topped_up_switch_malformed, .share_malformed, and .<part>_missing (period, free, topped_up or share) when plan would still write that part.
    • Warnings: chat_tokens.period_mismatch, .free_mismatch, .share_mismatch, when both shapes hold a value and they differ.
  • cleanup sets chat_usage and chat_limits to null, only for a subject where verify finds nothing at all.

Step 4: monitors #

Strongly recommended, not required. Without them, nothing tells you that a production run errored or that a writer skips the new key: only verify runs and a manual log search would. Skipping them needs a reason in the migration ticket, and step 8 then searches the logs by hand.

  1. Create them in Datadog (the Datadog connector, or Monitors → New Monitor). For a new migration, clone the two chat-tokens monitors below and change their event names. The migration-errors monitor is shared.
  2. Each watches production only (env:production, or host:"/eks/prod/pods" for app pod logs) and follows Triggering Incidents. Like the webapp fatal-error monitor, each is P3, pages @oncall-front-end and posts to @slack-Tofu-eng-prod-alerts, tagged team:front-end, env:prod and severity:p3.
  3. Publish them before step 7. A draft sends nothing.
Monitor Fires on First action
Migration errors Any status:error line of a production run Read that run’s subject lines; rerun with --org, or restore
Chat-tokens unreadable An app couldn’t read the new key in the last hour verify --org <orgId>; if widespread, flip the kill switch
Chat-tokens drift More than 30 drift logs in 2 hours Find the writer that skips the new key, and fix it before step 9

Done when: the monitors are published at P3, or the ticket says why they were skipped.

Chat-tokens: the three monitors in the table are published at P3 (2026-11-24). They stay quiet until the app change deploys, since nothing logs their events before then.

Step 5: deploy the app change #

  1. Merge the PR from steps 2 and 3.
  2. Wait until every service that reads or writes the keys runs the new code. Until then, old pods write only the old key: readers still take the newer copy, but apply would race those pods.

If the app PR is reverted after a run, the new key goes stale while the old one keeps updating. Redeploying is safe, because readers take the newer copy, but run a fresh verify before step 9.

Done when: every service is on the new release.

Chat-tokens: bonsapi, bonsapi-internal, tofu-web and the sales portal. From this release, an existing org’s free and topped-up switches read as off until the migration sets them (unset means off). In production that’s the intended end state anyway; on dev, an old extra_tokens grant shows again after step 6.

How to run the tool #

Every run uses the same command:

MIGRATE_CONFIG=<config> mise run clerk-metadata-migrate -- <migration-id> <stage> [options]
Part Meaning
MIGRATE_CONFIG=<config> The Doppler config: its Clerk key decides where the run reads and writes, and its ENVIRONMENT_NAME tags the logs. Unset means dev_local.
mise run clerk-metadata-migrate The task in tools/.tasks.toml. It runs doppler run --project bonsai --config <config> -- bun src/cli.ts in tools/clerk-metadata-migrate.
-- Ends mise’s own arguments. Everything after it goes to the tool.
<migration-id> See the migration id.
<stage> See the table below.
[options] See options.
MIGRATE_CONFIG Clerk instance Logs tagged
unset (dev_local) test, the same instance as dev env:dev_local
dev test env:dev
prd live (production) env:production

dev_local and dev hold the same Clerk key, so a run without MIGRATE_CONFIG reads and writes dev’s data. Use MIGRATE_CONFIG=dev for dev runs, so their logs say env:dev.

Relative paths (backups/…, reports/…) are inside tools/clerk-metadata-migrate. Both folders are gitignored. They hold customer metadata: never commit them or share them in Slack, and keep production backups in a private, access-controlled place for at least 30 days.

Stage Writes? What it does
plan Never Dry run: logs what apply would write for each subject (would_write).
apply Only with --write and --backup Writes each subject’s plan patch, backed up first and read back after. Without --write, it’s a dry run.
verify Never Runs the migration’s verify on every subject. Any error issue fails the run.
cleanup Only with --write, --backup and --verify-report Writes each subject’s cleanup patch. Without --write, it’s a dry run.
restore Only with --write Replays a backup file (--from): each subject’s declared keys go back to how they were.

Exit codes:

  • 0: clean.
  • 1: a Clerk call failed after retries, verify found an error, or a precondition failed before any write (for example, a missing --backup, or a verify report that can’t unlock cleanup).
  • 2: bad usage, no CLERK_SECRET_KEY, or a write with a live key without --production.

Step 6: run on dev #

Announce the run in the team channel, and say when you finish. One operator per migration at a time: two runs don’t corrupt data, but their reports and checkpoints get confusing.

  1. Dry run on a sample. It writes nothing.

    MIGRATE_CONFIG=dev mise run clerk-metadata-migrate -- <migration-id> plan --limit 20
    

    Check the would_write subject lines: paths lists what would be set.

  2. Dry run on everything. Note the would_write count in the summary.

    MIGRATE_CONFIG=dev mise run clerk-metadata-migrate -- <migration-id> plan
    
  3. Write one org. Check it in the product before going wide.

    MIGRATE_CONFIG=dev mise run clerk-metadata-migrate -- <migration-id> apply --write \
      --org org_… --backup backups/<migration-id>-dev.jsonl
    
  4. Write everything. Use the same backup file: restore takes each subject’s earliest line, so one file per environment is right.

    MIGRATE_CONFIG=dev mise run clerk-metadata-migrate -- <migration-id> apply --write \
      --backup backups/<migration-id>-dev.jsonl \
      --checkpoint reports/<migration-id>-dev.checkpoint.json
    

    If it stops part way, rerun the same command with --resume.

  5. Verify everything. Keep this report; step 7 needs it.

    MIGRATE_CONFIG=dev mise run clerk-metadata-migrate -- <migration-id> verify \
      --report reports/<migration-id>-verify-dev.json
    
  6. Dry run again. It must report would_write: 0.

    MIGRATE_CONFIG=dev mise run clerk-metadata-migrate -- <migration-id> plan
    

Each write fires Clerk’s organization.updated webhook, which clears the apps’ caches. Where webhooks don’t arrive (a local stack), clear one org by hand.

Done when: verify has 0 errors, the second plan reports would_write: 0, and a few known orgs show the same figures in the product as before.

Chat-tokens: use chat-tokens as <migration-id>, so the files are backups/chat-tokens-dev.jsonl, reports/chat-tokens-dev.checkpoint.json and reports/chat-tokens-verify-dev.json.

  • After step 3, open that org in the sales portal: Private metadata lists chat_tokens first, holding the old keys’ numbers, with free.is_enabled: true and topped_up.is_enabled: false.
  • Its chat usage card and tofu-web’s Overview card show the same usage as before. An org with an old extra_tokens grant now shows it as free tokens.
  • To clear one org’s cache by hand: bonsapi’s POST /internal/api/v1/billings/chat-usage/refresh?clerk_organization_id=org_….
  • Attach the verify report and both plan summaries to ENG-10048 (reports, never backups).

Step 7: run on production #

  1. Get approval. Post the dev verify report and a production plan summary in the ticket, and wait for a reviewer’s approval in the ticket.

    MIGRATE_CONFIG=prd mise run clerk-metadata-migrate -- <migration-id> plan
    
  2. Run steps 6.1 to 6.6 with MIGRATE_CONFIG=prd, -prd in every file name, and --production on every write. Without --production, a write with the live key exits 2. Every report records instance: live or test, so you can tell where it came from.

  3. Watch the migration-errors monitor during the run, and Datadog: service:clerk-metadata-migrate env:production status:error.

Done when: the production verify has 0 errors, the second plan reports would_write: 0, and both reports are on the ticket.

Chat-tokens:

MIGRATE_CONFIG=prd mise run clerk-metadata-migrate -- chat-tokens apply --write --production \
  --backup backups/chat-tokens-prd.jsonl \
  --checkpoint reports/chat-tokens-prd.checkpoint.json

On live, both switches are written as off, except free tokens for an org with an older extra_tokens grant, which bonsapi already reads as on. So no product figure changes.

Step 8: soak for at least 7 days #

Every day:

  1. All monitors are quiet. A few drift logs right after a deploy are fine. Without monitors, search Datadog for the migration’s status:error lines and its read-failure and drift events instead.
  2. A few known orgs show the same figures in the product.
  3. A full verify in each environment has 0 errors.

If the new key reads wrong anywhere, roll back.

Done when: 7 days pass with all three true.

Chat-tokens: watch the three chat-tokens monitors; check the sales-portal chat card and tofu-web’s Overview card for a few orgs.

Step 9: cleanup (separate ticket) #

In the cleanup ticket, in each environment, dev first:

  1. Run a fresh full verify. No --org, --limit or --resume, or the report can’t unlock cleanup.

    MIGRATE_CONFIG=<config> mise run clerk-metadata-migrate -- <migration-id> verify \
      --report reports/<migration-id>-verify-<env>.json
    
  2. Run cleanup within 24 hours of that report (--verify-max-age changes the limit; add --production on production):

    MIGRATE_CONFIG=<config> mise run clerk-metadata-migrate -- <migration-id> cleanup --write \
      --backup backups/<migration-id>-cleanup-<env>.jsonl \
      --verify-report reports/<migration-id>-verify-<env>.json
    

    It refuses a report that is for another migration, isn’t a verify run, covered only some orgs, had errors, or is too old. Subjects with any verify issue keep their old keys.

  3. Ship a PR that removes the fallback reads, the dual writes, the kill switch, and its deployment and Doppler entries. Keep the migration file, for its history and tests.

  4. Run verify again. Mismatch warnings no longer apply, because the old keys are gone.

Done when: no subject holds the old keys, and the PR is deployed.

Chat-tokens: ENG-10052 deletes chat_usage and chat_limits, then removes CHAT_TOKENS_READ_LEGACY, the fallback reads and the dual writes.

Rollback #

Situation Do this
The new key reads wrong in the apps Set the kill switch to true in Doppler and restart the apps. The old keys are current, thanks to dual-write.
A run wrote something wrong restore --write --from <that environment's backup> (with --production on production).
One org is wrong The same, with --org <id>.
After cleanup restore from the cleanup backup, then revert the cleanup PR.

restore puts back only the keys the migration declares in keys. Each subject returns to its earliest line in the backup file, its state before the migration first touched it. It also undoes live writes made since, so prefer the kill switch while it exists.

Chat-tokens: the kill switch is CHAT_TOKENS_READ_LEGACY. It doesn’t cover the values with no old key (step 1.4).

Options #

Option Meaning
--write Write (apply, cleanup, restore). Without it they only log.
--backup <file> Appends each touched key, as it was, before each write. Required to write with apply and cleanup.
--from <file> restore: the backup to replay.
--org <id> Only this org and its memberships. Repeatable.
--limit <n> At most n orgs, with their memberships.
--concurrency <n> Orgs at once (default 4). An org’s memberships run one after another.
--rps <n> Clerk requests per second (default 8; Clerk allows about 100 per 10 seconds).
--checkpoint <file> Saves the org offset reached.
--resume Starts from that checkpoint. The unfinished page is redone, which is safe.
--verify-report <file> cleanup: the verify report that unlocks it.
--verify-max-age <h> cleanup: how old that report may be, in hours (default 24).
--report <file> Where the summary goes (default reports/<migration-id>-<stage>-<time>.json).
--production Required to write with a live Clerk key.
--no-datadog Don’t ship logs to Datadog.

A run with --org, --limit or --resume is marked fullScope: false, so its verify report can’t unlock cleanup.

Logs #

The tool writes JSON lines to stdout. When DATADOG_API_KEY is set (every bonsai Doppler config), it also sends them to Datadog, tagged service:clerk-metadata-migrate and env:<ENVIRONMENT_NAME>, so a run from a laptop reaches the monitors. A failed send prints to stderr and never fails the run.

One line per subject (event: clerk_metadata_migration.subject):

Field Meaning
migration, stage, dryRun Which run
kind, orgId, userId Which subject
outcome unchanged, would_write, written, verified, skipped, issues or error (below)
paths Dotted key paths the patch sets or deletes; never values
issues verify problems: code, severity, message
error A failed Clerk call
level error for a failed call or a verify error, warn for warnings only, else info
Outcome Meaning
unchanged Nothing to write
would_write A dry run found something to write
written Written, and read back clean
verified verify found nothing
skipped The member left between the listing and the write
issues verify problems, or a write that read back wrong
error A Clerk call failed after retries

One summary line at the end (event: clerk_metadata_migration.summary): counts per outcome, issue counts by code, errorIssues, fullScope and lastOffset. The report file holds the same summary plus instance (live or test).

Datadog searches:

service:clerk-metadata-migrate @event:clerk_metadata_migration.summary
service:clerk-metadata-migrate env:production status:error
service:clerk-metadata-migrate @issues.code:chat_tokens.period_missing
service:tofu-web @event:chat_tokens.unreadable
service:tofu-web @event:chat_tokens.legacy_newer
service:bonsapi @event_name:chat_tokens_unreadable

How the tool stays safe #

  • Fresh reads: each subject is read again just before its write, and the patch comes from that copy. A live write can still land in the milliseconds between; dual-write and newer-wins reads make that harmless, and verify reports it as a mismatch warning.
  • Backups: every declared key is saved before each write, as it was or as absent.
  • Read-back: after each apply write, the result Clerk returns is checked. A wrong result counts as issues.
  • Rate limits: requests are evenly spaced; a 429 waits for Retry-After; 5xx and network errors retry up to 5 times, with exponential backoff and jitter.
  • Errors don’t stop the run. A failing subject is logged and counted, the rest carry on, and the run exits 1. Rerun with --org for the failed ones; reruns are safe.
  • Completeness is checked, not assumed. Orgs are listed by offset, oldest first, so an org deleted during a run can shift a page and make the run miss one org. The full verify and a second plan with would_write: 0 prove every subject is done.

Troubleshooting #

  • Many 429s or a slow run: lower --rps or --concurrency. Other apps share the Clerk instance’s limit.
  • A run stopped part way: rerun it with --resume and the same --checkpoint.
  • verify warnings but no errors: expected while a writer hasn’t moved to dual-write, or between a usage write and the next write-back. Look for a pattern before cleanup.
  • A membership is missing from the logs: Clerk sent it without public_user_data, so it isn’t listed.
  • This is a live (production) Clerk key: you’re writing to production. Add --production only once the run is approved.
  • Drift logs keep coming: search them by @orgId. Check that every service runs the new code, then scripts and cron jobs, then the Clerk dashboard’s audit log.
  • cleanup refuses: the message says why. Run a fresh full verify.
  • The usage line instead of a run: the migration id or stage is wrong; the usage line lists the registered ids.

Reference #

  • Tool: tools/clerk-metadata-migrate (README.md; src/types.ts for the interfaces)
  • Example migration: src/migrations/chat-tokens.ts and tests/chat-tokens.test.ts
  • Monitors: Datadog, linked in Step 4
  • Tasks: mise run clerk-metadata-migrate, mise run clerk-metadata-migrate-test
  • Tickets: ENG-10048 (migration), ENG-10052 (cleanup)