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:
- The new shape, and an old key → new key table.
- Subjects: organizations, memberships, or both.
- 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.
- Values that have no old key. The kill switch can’t roll these back, because there is nothing old to read.
- Values that differ by environment. A migration knows which Clerk instance it runs on:
test(local and dev) orlive(production). - 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.
- 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:
Shape and table:
Subject Old key New key Org chat_usage.period_start,.tokens,.updated_atchat_tokens.period.start,.period.used,chat_tokens.updated_atOrg chat_limits.extra_tokenschat_tokens.free.granted(withused: 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_enabledMembership chat_usagechat_tokens.period,chat_tokens.updated_atMembership chat_limits.user_sharechat_tokens.shareSubjects: organizations and memberships.
Private metadata only.
No old key: topped-up tokens, every expiry, both
is_enabledswitches, the free grant a new org gets fromCHAT_FREE_TOKENS, each grant’sstart, and a member’s use of each balance (chat_tokens.freeand.topped_upon the membership:used,start,expires_at, written back by tofu-web). The three sources are counted apart:period.usedis the plan’s tokens this period, and each balance’susedis its current grant’s, across periods until it expires. A newer grant (a laterstart) counts from 0.period.drawn(free,topped_up) is what the period took from each balance, so a lost Redis counter is rebuilt asused+drawn; the olderchat_usage.tokenskeeps that total. The migration writes nostart: 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.By environment: the switches. On
test, free is on and topped-up off; onlive, both are off, except that an org with an olderextra_tokensgrant keeps free tokens on everywhere.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.grantedandchat_limits.extra_tokens.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.
- 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.
- 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
nullvalue deletes a key, so when a value is removed, remove it from both shapes. - The kill switch. Add
<FEATURE>_READ_LEGACY(defaultfalse). When it’strue, readers ignore the new key for every field the old keys hold.- Rust (bonsapi): a field on
AppConfigwithdeserialize_lenient_flag, applied at startup. - tofu-web: an uncached reader in
src/env.ts, with its schema inSERVER_ENVIRONMENT_KEYS; the deployment-env test then requires it in the deployment. - Deployments: add it with
optional: trueto each app’sdeployment/resources/<app>/deployment.yaml. Not todocker-compose.yml: local development reads it unset, which isfalse. - Doppler: add it as
falseto every config. Unset also reads asfalse, 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.
- Rust (bonsapi): a field on
- 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 asservice:bonsapi; a plainwarn!arrives asservice:cloudwatch, where no monitor can match it.
- 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-webapps/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) writeschat_tokensandchat_usage; the sales portal’s free-token, share and reset edits (chat-limits.ts) also writechat_limitsandchat_usage.- Kill switch:
CHAT_TOKENS_READ_LEGACY, in the bonsapi, bonsapi-internal, tofu-web and sales-portal deployments. Leave itfalsebefore, during and after the migration. Set it totrueonly to roll back. While it’strue, new orgs get no free tokens, because their grant lives only inchat_tokens.- Logs: tofu-web
chat_tokens.unreadableandchat_tokens.legacy_newer, withfield,orgIdanduserId; bonsapi eventchat_tokens_unreadable.
Step 3: write the migration #
-
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.instanceistestorlive, for a value that differs by environment. -
Register it in
src/migrations/index.ts, keyed by its id:export const MIGRATIONS = { [chatTokensMigration.id]: chatTokensMigration, [myMigration.id]: myMigration, }; -
Follow these rules:
- The functions are pure. The runner does the reading, backups, writes and logging.
planadds 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 secondapplywrites nothing.plannever deletes. Onlycleanupdeletes.verifyreturns stable codes, prefixed with the key, such aschat_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.
cleanupdecides per subject. Returnnullwhenverifyfinds any issue for that subject, warnings included: an old key that disagrees may be the newer copy.
-
Test the pure functions, and the runner with
memoryClerkfromtests/support.ts(an in-memory Clerk with Clerk’s merge rules). Copytests/chat-tokens.test.tsto 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.
- The migration sets it:
id: 'my-migration'. TheMetadataMigrationtype insrc/types.tsrequires it, in kebab-case. src/migrations/index.tsregisters the migration under it:[myMigration.id].src/cli.tstakes the first argument after--and looks it up inMIGRATIONS. 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.tsexportschatTokensMigrationwithid: 'chat-tokens'. It declares the keyschat_tokens,chat_usageandchat_limits(private), so each is backed up before a write.
plan, for each subject, writes only the parts ofchat_tokensthat are missing, plusv: 1:
periodandupdated_at, from a readablechat_usage(v: 1).- Orgs:
free.grantedfromchat_limits.extra_tokens, withused: 0andexpires_at: null;topped_upwithgranted: 0,used: 0,expires_at: null; and eachis_enabledthat is unset, as decided per instance (free stays on wherever anextra_tokensgrant exists).- Memberships:
sharefromchat_limits.user_share(0 to 1).verifycodes:
- Errors:
chat_tokens.not_an_object,.period_malformed,.updated_at_missing,.period_drawn_malformed,.free_malformed(also a non-numericstart, on orgs and memberships),.topped_up_malformed,.free_switch_malformed,.topped_up_switch_malformed,.share_malformed, and.<part>_missing(period,free,topped_uporshare) whenplanwould still write that part.- Warnings:
chat_tokens.period_mismatch,.free_mismatch,.share_mismatch, when both shapes hold a value and they differ.cleanupsetschat_usageandchat_limitstonull, only for a subject whereverifyfinds 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.
- 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.
- Each watches production only (
env:production, orhost:"/eks/prod/pods"for app pod logs) and follows Triggering Incidents. Like the webapp fatal-error monitor, each is P3, pages@oncall-front-endand posts to@slack-Tofu-eng-prod-alerts, taggedteam:front-end,env:prodandseverity:p3. - 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 #
- Merge the PR from steps 2 and 3.
- 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
applywould 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_tokensgrant 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,verifyfound anerror, or a precondition failed before any write (for example, a missing--backup, or a verify report that can’t unlock cleanup).2: bad usage, noCLERK_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.
-
Dry run on a sample. It writes nothing.
MIGRATE_CONFIG=dev mise run clerk-metadata-migrate -- <migration-id> plan --limit 20Check the
would_writesubject lines:pathslists what would be set. -
Dry run on everything. Note the
would_writecount in the summary.MIGRATE_CONFIG=dev mise run clerk-metadata-migrate -- <migration-id> plan -
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 -
Write everything. Use the same backup file:
restoretakes 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.jsonIf it stops part way, rerun the same command with
--resume. -
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 -
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-tokensas<migration-id>, so the files arebackups/chat-tokens-dev.jsonl,reports/chat-tokens-dev.checkpoint.jsonandreports/chat-tokens-verify-dev.json.
- After step 3, open that org in the sales portal: Private metadata lists
chat_tokensfirst, holding the old keys’ numbers, withfree.is_enabled: trueandtopped_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_tokensgrant 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
verifyreport and bothplansummaries to ENG-10048 (reports, never backups).
Step 7: run on production #
-
Get approval. Post the dev
verifyreport and a productionplansummary in the ticket, and wait for a reviewer’s approval in the ticket.MIGRATE_CONFIG=prd mise run clerk-metadata-migrate -- <migration-id> plan -
Run steps 6.1 to 6.6 with
MIGRATE_CONFIG=prd,-prdin every file name, and--productionon every write. Without--production, a write with the live key exits2. Every report recordsinstance: liveortest, so you can tell where it came from. -
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.jsonOn
live, both switches are written as off, except free tokens for an org with an olderextra_tokensgrant, which bonsapi already reads as on. So no product figure changes.
Step 8: soak for at least 7 days #
Every day:
- All monitors are quiet. A few drift logs right after a deploy are fine. Without monitors,
search Datadog for the migration’s
status:errorlines and its read-failure and drift events instead. - A few known orgs show the same figures in the product.
- A full
verifyin 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:
-
Run a fresh full
verify. No--org,--limitor--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 -
Run
cleanupwithin 24 hours of that report (--verify-max-agechanges the limit; add--productionon 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>.jsonIt refuses a report that is for another migration, isn’t a
verifyrun, covered only some orgs, had errors, or is too old. Subjects with anyverifyissue keep their old keys. -
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.
-
Run
verifyagain. 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_usageandchat_limits, then removesCHAT_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
verifyreports it as a mismatch warning. - Backups: every declared key is saved before each write, as it was or as absent.
- Read-back: after each
applywrite, the result Clerk returns is checked. A wrong result counts asissues. - Rate limits: requests are evenly spaced; a
429waits forRetry-After;5xxand 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--orgfor 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
verifyand a secondplanwithwould_write: 0prove every subject is done.
Troubleshooting #
- Many
429s or a slow run: lower--rpsor--concurrency. Other apps share the Clerk instance’s limit. - A run stopped part way: rerun it with
--resumeand the same--checkpoint. verifywarnings 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--productiononly 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. cleanuprefuses: the message says why. Run a fresh fullverify.- 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.tsfor the interfaces) - Example migration:
src/migrations/chat-tokens.tsandtests/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)