Changing a production MariaDB safely (schema, data fixes, id generation)
mariadbmysqlmigrationsbackupsalter-tableutf8mb4get_lockproduction
The TLDR database is small (under 10 MB) but it is production, it holds E2E key backups that can
never be regenerated, and it has been changed by many hands. These are the rules that the
db-change workflow settled on, plus schema facts that tripped people up.
Know the engine
The server runs MariaDB 10.11, not MySQL 8, even though every tool and file calls it "mysql". Answer questions about ALTER TABLE behavior, JSON functions, window functions and strict mode from MariaDB's documentation. Strict mode rejects NULL for NOT NULL columns and over-long strings (error 1406, "Data too long"), so an UPDATE that used to silently truncate now fails.
Before any change
- Back up the affected tables with
mysqldumpinto~/backups/pre-<change>-<date>.sqlon the server, and copy anything irreplaceable (key tables) off the box. - Verify the backup: check its size and count
CREATE TABLElines (grep -c 'CREATE TABLE'). A schema-only backup is fine for purely additive migrations. - Write the inverse statement before running the forward one.
- Check table size before an ALTER that rewrites the table (the big ones here were views, notifications and messages).
- Put the migration in
api/migrations/in git, and make it re-runnable (IF EXISTS/IF NOT EXISTS) so it can be applied, re-run, and proven idempotent.
Data fixes
Wrap in a transaction and compare ROW_COUNT() to the number you expect before committing:
START TRANSACTION;
UPDATE post_meta SET meta_value = 'answered' WHERE post_id IN (1449, 1435) AND meta_key = 'ai_status';
SELECT ROW_COUNT(); -- expect 2, else ROLLBACK
COMMIT;
After any production DB change, run the smoke test (Writing a production smoke test that tells you why it failed).
Patterns and lessons
- Id generation without AUTO_INCREMENT. Legacy
post.idisMAX(id)+1, which races under concurrency. The cheap fix that shipped: serialize it with a named lock,SELECT GET_LOCK('tldr_post_id', 5)... insert ...SELECT RELEASE_LOCK('tldr_post_id'). The clean fix (AUTO_INCREMENT pluslastInsertId()) needs an ALTER on prod and was deferred. - Race-free toggles:
INSERT ... ON DUPLICATE KEY UPDATEandINSERT IGNOREfor votes and polls;SELECT ... FOR UPDATEwhen consuming a one-time resource. - Append-only tables for irreplaceable data (encryption key archive): never UPDATE or DELETE; let the application own uniqueness checks if a race could at worst duplicate a row.
- Self-referencing upserts: in
ON DUPLICATE KEY UPDATE a = IF(b = VALUES(b), a, NULL), b = VALUES(b)the IF reads the oldbonly becauseais assigned first. Order matters. - Character set: the database was migrated from latin1 to
utf8mb4withutf8mb4_unicode_ciandROW_FORMAT=DYNAMICon every table, and every connection setscharset=utf8mb4. New tables follow the same settings. Useascii_binfor case-exact tokens. - Widen columns before they overflow. An audit table copied titles into
varchar(50); editing a post with a longer title failed with error 1406 until it was widened to 255. - Primary key on the right column: a password-reset table keyed on the token instead of the username stacked one row per request, and an unordered SELECT returned the oldest token.
- An upsert must refresh every column that means "fresh". After that table was re-keyed by
username, re-requesting a reset ran
ON DUPLICATE KEY UPDATE token = VALUES(token)but leftcreated_datealone. Users with an old unused row got a new link that was already past the 2-day validity window. Update the timestamp (created_date = NOW()) along with the value. - Rehearse multi-step logic against real data inside a transaction you roll back. The AI job table's lifecycle was tested on production by a harness that opened a transaction, ran 25 scenario checks against a fake executor, and rolled back: real schema and data, no lasting writes. Keep such runs short; locks are held until the rollback.
- Soft delete with retention instead of hard delete when many tables reference a row; keep the tombstone, purge the heavy data later. See Accepting and serving user uploads safely from a private bucket.
- Visibility in one SQL clause with a code twin for non-SQL paths; see API authorization from the verified identity (and the holes it closes).
- Watch for junk legacy values: some 2021 rows have a username in the
privacycolumn, which the detail endpoint treats as public and list queries as private.
Renaming a key that other tables copy (usernames)
TLDR identifies users by username in many tables, with no numeric id. Renaming one account
(October 2026) worked like this:
- Find every column holding the exact username (information_schema.COLUMNS plus a COUNT(*) per
candidate), not just the declared foreign keys.
- Collations are case-insensitive (utf8mb4_unicode_ci): renaming Bean to aaron collides
with an existing Aaron. Delete the conflicting account and its rows before the rename.
- Do it as one transaction with FOREIGN_KEY_CHECKS=0, deletes first, then one UPDATE per column;
check for orphans afterward (0 expected). Back up first.
- Look for things derived from the name, which an UPDATE cannot fix: here the E2E conversation
key's HKDF info string contains both usernames, so the renamed user's existing DMs became
undecryptable and were deleted by choice. Existing tokens for the old name stop resolving to a
user (401), and saved logins on devices still hold the old name.
Naming traps in this schema
Singular table names; post_tag.postid (no underscore) next to post_meta.post_id; times as unix
ints in some tables (response.created_date, dm_message.sent_date, all group-chat tables) and
DATETIME in others. Check DESCRIBE before writing a query from memory.
Access
Interactive access is on the server with the app's MySQL user (credentials live in the global
CLAUDE.md and the server's DB config file, not here). Pass passwords to scripts via MYSQL_PWD, not
on the command line where ps shows them.